1

I have AJAX code here that pass multiple values to PHP. But the problem is that the PHP can't get the value pass by AJAX and nothing is added on the database. However in my submit button I have an onclick event that calls addAnnouncement() and I think it is working because I put an alert in my ajax code and everytime I click that button it says OK. So I think the part of the problem is in the passing of the variables.

What do you think is the problem in my code?

AJAX CODE:

  function addAnnouncement()
{
    var subject = document.getElementById("subject").value;
    var name = document.getElementById("name").value;
    var announcement = document.getElementById("announcement").value;

    var xmlhttp;
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }




    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4)
        {
            if(xmlhttp.status==200){
                alert("OK");
                document.getElementById("result").innerHTML=xmlhttp.responseText;
            }
        }
      }

     var variables = "subject=SAMPLE&name=HARVEY&announcement=HELLO";
      xmlhttp.open("POST", "addAnnouncement.php", true);          
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");      
      xmlhttp.send(variables);  

     return false;
          }

This is the PHP code that gets the values pass by AJAX. PHP CODE:

<?php
require_once("config.php");

$subject = $_POST['subject'];
$name = $_POST['name'];
$text = $_POST['announcement'];
$dateTimeNow = date("Y-m-d H:i:s");


$query = "INSERT INTO table_announcement(subject, name, text, dateTimePosted)". 
                "VALUES('$subject', '$name' , '$text', '$dateTimeNow')";
$data = mysql_query($query)or die(mysql_error());       

if($data){
    echo "ADDED!";
}   
else{
    echo "ERROR!";
    }   
?>
11
  • Beware of SQL injection in your code. Commented Dec 8, 2013 at 16:07
  • And what is the response of the XHR? Does it show ERROR!, implying that the query returned FALSE? Commented Dec 8, 2013 at 16:12
  • Okay thank you for that. I'll modify my code later. But do you think that's the reason why this is not working? sorry I'm newbie here. Commented Dec 8, 2013 at 16:13
  • And please look at your network tab in the Inspector to see if a network request is made and if so, what's sent. Commented Dec 8, 2013 at 16:14
  • @MarcelKorpel No it doesn't show anything, it only reloads the current page. Commented Dec 8, 2013 at 16:14

1 Answer 1

1

Just return false when exiting from the event handler to prevent the default behaviour of the submit button (i.e. submit the form):

function addAnnouncement() {
    // …
    return false;
}

Also check the status of your XMLHttpRequest when it reaches readyState 4 (it might be something different then 200) and properly encode query string parameters with encodeURIComponent. Last, but not least, your code is open to SQL injection. Fix that by using prepared statements (available in MySQLi and PDO. If you can't decide which, this article will help you. If you pick PDO, here is a good tutorial).

Sign up to request clarification or add additional context in comments.

9 Comments

Sir I've edited my question. I've also tried your suggestions, added a condition after the readyState which is if(xmlhttp.status==200). And the alert OK now is not popping not like before. So it means that it does not pass the condition. Do you think that's the problem?
@Harvey It is at least a problem that it doesn't give back status 200. Then you should debug further, outputting the status using console.log (or check what's sent using the network tab of the browser's inspector).
Okay, thank you. But how can I use console.log to output the status? Is there a tutorial on how to do that?
@Harvey Just output the status with console.log(xmlhttp.status) and look at the console (or better, look at the network tab).
Sorry I'm newbie here, last question where in part of the code will I put the console.log(xmlhttp.status);?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.