I have a button with onclick="sendNews()" and a PHP script which does the database work.
The problem is that the $_POST array is empty when sendNews runs.
Javascript:
function sendNews()
{
var title=document.getElementById("title").innerHTML;
var body=document.getElementById("boddy").innerHTML;
var params="title="+title+"&body="+body;
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");
}
//Send the proper header information along with the request
xmlhttp.open("POST","sendnews.php",true);
xmlhttp.send(params);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("newsAddResult").innerHTML=xmlhttp.responseText;
}
}
}
PHP:
<?php
include("../inc/functions.php");
if(!loginCheck())
header('Location: index.php');
$title=@$_POST['title'];
$body=@$_POST['body'];
var_dump($_POST);
$q=sprintf("insert into `news`(`id`,`title`,`body`,`time`) values(NULL,'%s','%s','%s')",$title,$body,jgmdate('l jS F Y h:i:s A'));
mysql_query($q) or die("خطا".mysql_error());
echo "با موفقیت ارسال شد";
?>
Where’s the problem?
Edited to correct errors in the code and to make it compatible with more browsers.
Thanks to @Mr. BeatMasta and @Felix Kling for setting me straight on placement of onreadystatechange, sending the header, and browser compatibility issues.
.
Javascript:
In your php you have:
That should be: