I am having a little difficulty. Basically I am sending information from a form via jQuery and AJAX to MySQL, then returning a value back to my application.
I am able to add the information to my DB but I cant seem to work out how to retrieve the ID of the data inserted. Here is my code –
function submitDeliveryDetails(){
$.ajax({
url: "http://www.mydomain.co.uk/mobileapp/add_deliverydetails.php?callback=jsonp1",
data: addDeliveryData, // Variable holding said delivery information
jsonp: "callback",
dataType: "jsonp",
success: function(data) {
$.each(data, function(index) {
alert(data[index].orderId);
});
},
error: function(){
//Do Stuff
}
})
}
This sends the information fine. I am able to add to the DB and using the following to return the ID
$orderId = mysql_insert_id();
I then create JSON format for this value,
$orderIdArray = array('orderId'=>$orderId);
echo $_GET['callback'].'('.json_encode($orderIdArray).')';
When I view this in FireBug, I can see the ID, What I need guidance is how to handle this ID to get it back into my application, As I am getting ‘undefined’ doing things my way!
Thanks
Rory
p.s. I am using JSONP as I am dealing with scripts on a separate domain.
Plain text JSON –
({"orderId":125})
The ajax call is asynchronous. That means the ajax call completes and the following functions in your code continue to execute while the ajax call is underway and before it completes. Therefore, the ONLY place you can do anything with the return value is in the success handler for the ajax function or in any functions you call from there.
This requires changing the flow of your coding, but you need to make the ajax call and then continue the flow of execution in the success handler once the ajax call successfully completes.
Conceptually, it’s like this: