I have the following jQuery AJAX to duplicate a background image. I am stumped as to how to effectively return information back to the original page. Here is the AJAX I send on click of “‘#dupBtn”…
//DUPLICATE BACKGROUND
$('#dupBtn').click(function() {
jQuery.ajax({
type: "POST",
dataType:'json',
url: "../system/bgUpdate.php",
data: {
"user":<?= $_POST['user'] ?>,
"bgID":bgID,
"refID2":<?= $_POST['refID2'] ?>,
"refTable":"<?= $_POST['refTable'] ?>",
"bgTitle":($('#bgTitle').val()),
"path":path,
"bgColor":bgColor,
"bgPoz":bgPoz,
"bgRepeat":bgRepeat,
"attach":attach
}
});
});
Here is the basic MySQL query on the PHP page bgUpdate.php.
mysql_query("INSERT INTO backgrounds (user,title,path,bgColor,bgPosition,bgRepeat,bgAttachment) VALUES ('".$_POST['user']."','$title','".$_POST['path']."','$bgColor','".$_POST['bgPoz']."','$rt','$attach')");
$bgIDnew = mysql_insert_id();
What I want to do is have the following code fired on the original page upon successful execution of the MySQL entry, dynamically catching the ‘$bgIDnew’ from the MySQL PHP page.
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
You can accomplish this with the
successattribute of the.ajax()function:That’s only part of it though… The other half is that your PHP needs to return something that jQuery can understand as a “successful” call. My preference is to use HTTP status codes. In your case, your PHP script should return a
200code if it was successful; otherwise, it should return something in the400range. (By the way, if you want jQuery to do something separate with errors, you can use theerrorproperty of.ajax().)However, if you need to return data from the server to the client-side script, then your PHP can print out that information like this:
This PHP script sends back to the ajax() method a JSON representation of the $response variable. You’ve already configured that ajax() method to read the response dataType as JSON, so it already knows how to read the
responseparameter… Which means your success function can look something like this: