I’m wondering how to reference specific variables in my jquery.ajax() success function.
My php code on addit.php
if ($_POST) {
$user_id = $_SESSION['user_id'];
$filename = $_SESSION['filename'];
$quote = $_POST['quote'];
$query = "INSERT INTO `submissions` (
`id` ,
`user_id`,
`quote` ,
`filename` ,
`date_added` ,
`uploaded_ip`
)
VALUES (
NULL , '{$user_id}', '{$quote}', '{$filename}', NOW(), '{$_SERVER['REMOTE_ADDR']}')
";
$db = DbConnector::getInstance();
$db->insert($query);
// remove funky characters from the quote
$cleanRemove = preg_replace("/[^a-zA-Z0-9\s]/", "", $quote);
// replace any whitespace with hyphens
$cleanQuote = str_ireplace(" ", "-", $cleanRemove);
// get the id of the last row inserted for the url
$lastInsertId = mysql_insert_id();
$returnUrl = array ("lastId"=>$lastInsertId, "cleanQuote"=>$cleanQuote);
echo json_encode($returnUrl);
}
My jQuery code:
$.ajax({
type: "POST",
url: "addit.php",
data: ({
// this variable is declared above this function and passes in fine
quote: quote
}),
success: function(msg){
alert(msg);
}
});
Returns in the alert:
{"lastId":91,"cleanQuote":"quote-test-for-stack-overflow"}
How can I now reference that in the success function? I was trying something like this, but it didn’t work (returns “undefined” in the alert):
$.ajax({
type: "POST",
url: "addit.php",
data: ({
// this variable is declared above this function and passes in fine
quote: quote
}),
success: function(data){
alert(data.lastId,data.cleanQuote);
}
});
It seems like the response JSON isn’t being parsed into an object, which is why the
alert()displays the entire string (otherwise you’d see[object Object]). You could parse it on your own but a better solution might be to do one (or both) of the following:Add
dataType = "json"to the call toajax()to tell jQuery that you’re expecting JSON as the response; jQuery will then parse the result and give you adataobject that you can work with and not just a string. Also, note thatalert()only accepts one argument, all subsequent ones will simply be ignored.Update your PHP to respond with the correct content type
header('Content-type: application/json');– this will allow jQuery to automagically figure out that the response is JSON and it will parse it for you, without needing adataTypevalue. This will also make it easier for other consumers since you’ll be explicitly specifying the data type.