Reputation: 389
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!";
}
?>
Upvotes: 1
Views: 1816
Reputation: 21763
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).
Upvotes: 1