I have spent hours looking for help with returning to Javascript the AJAX call to a php script.
What I am trying to do, is insert a value into a table, then return the id for that inserted row, which can then be used in a form, so when the time to update the table with the form data, it can specify where it should go (which row). I need to do this, so I can basically reserve the row, and it won't be stolen by another user.
This is the call I have been using:
id = getID('<?php echo $q; ?>','<?php echo $i; ?>');
The php values are valid (looking at the code, the values are displayed), and the var is declared outside of the javascript function.
This is the AJAX function:
var xmlhttp;
function getID(q, i)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Sorry but your browser does not support AJAX or Javascript has been disabled");
return;
}
var url = "getID.php";
url = url + "?q=" + q;
url = url + "&i=" + i;
// execute the fully formed request
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
id = xmlhttp.responseText;
// alert(xmlhttp.responseText);
// return xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
and the php code:
$q = $_GET['q'];
$i = $_GET['i'];
$query = "INSERT INTO parts (q, i) VALUES ('".$q."','".$i."')";
$results = mysql_query($query) or die(mysql_error());
$nextId = mysql_insert_id();
echo "$nextId";
If I alert the value, it will return properly, but in the form, which is creating a DOM dynamic row for this value and data to be entered, it comes up with "undefined". Can anyone guide me how to make this work? I will admit I'm no AJAX expert, and I can't seem to get callbacks to work when I try them, and frankly, don't really understand how...
Thank you in advance for any help anyone can offer.