tags:

views:

918

answers:

2

I have jQuery Ajax request that sends data to a PHP page that then insert a record into MySQL.
With my current setup, this all works fine.

However, as part of the PHP script, i use mysql_insert_id() to retreive the ID of the last record.
I need the Ajax Success function to return this ID value as a javascript variable.

PHP Code

if ($_GET['Ajax'] == 1) {         
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);

$LastID = array('LastID' => mysql_insert_id());
$LastID = json_encode($LastID);
}

Javascript

$.ajax({
    type: "GET",
    url: "AddFunction.php",
    data: {"Ajax":"1", "Data":"Test"},
    dataType: "json",
    success: function(data) {
     var LastID = data;
     alert(LastID);
    }
});

I've read of using PHP's json_encode to create a JSON object and then pass that back, but i've had no luck.
How can i return this value?

+3  A: 

just use

echo $LastId;

to send a response.

If you pass only one value you dont need JSON:

PHP Code

if ($_GET['Ajax'] == 1) {                                 
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);

$LastID = mysql_insert_id();
echo $LastID;
}

Javascript

$.ajax({
    type: "GET",
    url: "AddFunction.php",
    data: {"Ajax":"1", "Data":"Test"},
    dataType: "text",
    success: function(data) {
        var LastID = data;
        alert(LastID);
    }
});

with JSON:

PHP Code

if ($_GET['Ajax'] == 1) {                                 
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);

$jsonArray= array('LastID' => mysql_insert_id()); //*1 value is named LastID
echo json_encode($jsonArray);
}

Javascript

$.ajax({
    type: "GET",
    url: "AddFunction.php",
    data: {"Ajax":"1", "Data":"Test"},
    dataType: "json",
    success: function(data) {
        var LastID = data["LastID"];//use the same name as above (*1)
        alert(LastID);
    }
});
Ghommey
Okay this method of not using JSON and just echo the value is working.However, i can see in the future i will have multiple values returned, how would i correctly use JSON to do this?
ticallian
k try the code above :)
Ghommey
Great stuff, works prefect. Thanks
ticallian
A: 

Maybe it is because your LastID is in array so the resulting object would be a JS array.

If you just need the ID don't use JSON encode and just pass the ID in Javascript.

So in PHP:

if ($_GET['Ajax'] == 1) {                                 
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);

$LastID = mysql_insert_id();
echo $LastID;
}
andreas