HTML
<form action='insert.php' method='POST'>
<p><b>Client:</b><input type='text' name='idclient'/>
<p><b>Total:</b><br /><input type='text' name='total'/>
<p><input type='submit' value='Save' id="btnSave"/>
<input type='hidden' value='1' name='submitted' />
</form>
PHP (insert.php)
<?php
echo file_get_contents('php://input');
include_once "connect.php";
if ($db_found){
if (isset($_POST['submitted'])) {
foreach($_POST AS $key => $value) {
$_POST[$key] = mysql_real_escape_string($value);
}
$sql = "INSERT INTO `mytable` ( `idclient` , `total` , ) " .
"VALUES( {$_POST['idclient']} , {$_POST['total']} ) ";
mysql_query($sql) or die(mysql_error());
}
}
mysql_close($db_handle);
?>
This works OK, but when I try to call the insert using Ajax the $_POST function is empty and I cannot access the values from the form.
This is the ajax code and the function call:
<form action="javascript:Save()" method='POST'>
Ajax
function Save()
{
xmlHttp = getXMLHttp(); // returns a new XMLHttpRequest or ActiveXObject
xmlHttp.onreadystatechange = function(){
if(xmlHttp.readyState == 4) {
document.getElementById("btnSave").value = "Saved";
document.getElementById("result").innerHTML = xmlHttp.responseText;
}
else{
document.getElementById("btnSave").value = "Saving...";
}
}
xmlHttp.open("POST", "insert.php", true);
xmlHttp.send(null); // Do I need to create and pass a parameter string here?
}
Doing an echo file_get_contents('php://input'); indeed the $_POST is empty and the parameters values are not passed along.
I could concatenate the params value in the URL like this
xmlHttp.open("POST", "insert.php?idclient=123&total=43", true);
But, is there a way to use $_POST and take advantage of it?
Based on the answers this is what I came up with:
After a while of searching I found out that defining as separate this function (and not inline in onreadystatechange, as in the original question) would get it to work.
However, @Daren made a good point on “special” input values. For example, passing an ‘&’ character in a string field will get incomplete values.