How to use javascript inside PHP?

I need to show an alert box to the user in case a form gets successfully submitted.

But it is not working. The alert box does’nt pop up.

The form is on page contactus.php. I want the user to stay on that page only. So i have added

header(‘Location: contactus.php’);

Here is the code.

$qry = "insert into contactus(name,email,subject,message) values('$name','$email','$subject','$message')";
$result=mysql_query($qry);
if($result)
{

echo "<script type='text/javascript'>\
";
echo "alert('Your message was successfully sent.');\
";
echo "</script>";
header('Location: contactus.php');
}
else
{
echo "<script type='text/javascript'>\
";
echo "alert('Could'nt send your message.');\
";
echo "</script>";
header('Location: contactus.php');
}

remove the header() and it will work :wink:

yeah but i want it to stay on the same page.

It goes to contact_us_action.php which is the php handling the form. I want it to just stay on the same page. That is contactus.php

In that case you need to echo the JavaScript on the final page as currently (as suggested above) the page is redirecting before the JavaScript is seen by the user.

You need to send back a message to contactus.php which allows you to tell the difference between a successful and failed message, you can do this with a query string (?name=value).


$qry = "insert into contactus(name,email,subject,message) values('$name','$email','$subject','$message')";
$result=mysql_query($qry);
if($result){
     header('Location: contactus.php?status=sent');
}else{
     header('Location: contactus.php?status=fail');
}

Add this to the top of contactus.php


if(!empty($_GET['status'])){
     $status = $_GET['status'];
     echo '<script type="text/javascript">';
     echo 'alert("';
     echo ($status == sent) ? 'Your message was successfully sent.':'Could\\'nt send your message.';
     echo '");';
     echo '</script>';
}

Then you must place the javascript code on contactus.php

Alternatively you can use an AJAX request to send the data to contact_us_action.php and put the alert() code after the AJAX request was succesfully completed.
However. I must tell you that users generally dislike the little popup boxes on websites. It’s better to create a different form of feedback.

@NuttySkunk

Your idea worked. Thanks a lot :slight_smile:

You are very welcome.

Your script had some bug. I did’nt work. I used this one.

<?php 
if(!empty($_GET['status'])) 
{  
  $status = $_GET['status']; 
     if($status=="sent") 
     { 
     echo "<script type='text/javascript'>\
";  
echo "alert('Your message was successfully sent.');\
";  
echo "</script>";  
}  
else  
{  
echo "<script type='text/javascript'>\
";  
echo "alert('Could'nt send your message.');\
";  
echo "</script>";  
}    
} ?>