Below I have an jquery with ajax code where it will display change the values of course details by inserting the new data from one set of inputs (the set of inputs where the user has made changes) to another set of inputs (the set of inputs where it states the course’s current details). Also the course’s drop down menu changes to accommodate the new change if it needs to change:
function submitform() {
$.ajax({
type: "POST",
url: "updatecourse.php",
data: $('#updateCourseForm').serialize(),
success: function(html){
$("#targetdiv").html(html);
//Get and store the new course number and name.
var newCourseNo = jQuery("#newCourseNo").val();
var newCourseName = jQuery("#newCourseName").val();
var newDuration = jQuery("#newDuration").val();
//Set your current course number and name to your number and name.
jQuery("#currentCourseNo").val(newCourseNo);
jQuery("#currentCourseName").val(newCourseName);
jQuery("#currentDuration").val(newDuration);
//Find the currently selected course and update it.
var selectedOption = jQuery("#coursesDrop option:selected");
var label = selectedOption.text().split(" - ");
selectedOption.text(newCourseNo + " - " + newCourseName);
$('#targetdiv').show();
}
});
}
Now $("#targetdiv") is the id where it displays the success or error message retrieved from the php page which is accessed through ajax:
updatecourse.php:
...//mysqli code
echo "<span style='color: green'>Course details have been updated:<br/>" . $newcourseno . " - " . $newcoursename . "</span>";
}else{
echo "<span style='color: red'>An error has occured, Course Details have not been updated</span>";
}
But the problem I am having is that if the error message from the php code is retrieved in the jquery, then I don’t want the course details to make the edit in jquery to accomodate the current course text inputs to insert the new details. I only want that to happen if the success message appears.
If the error message appears I want no change to happen, the current course details inputs and the new course details input simply remain the same before the submit.
But how can this be achieved?
Get response as JSON (so that you can manipulate the response after you get result…)
try this,
JQUERY
PHP
json_encode()to send the reponse as json…. send response as array with the error flag to check if it is a succcess or error and the msg to print…