I have a voting function which submits a user vote using AJAX and updates the DB without having to refresh the page. All good so far. But I also want to retrive the updated values from the DB and update this on the page.
I’ve nested a second AJAX request inside my first request. This second request calls on the file new_values.php which gets the latest values and puts them into an array and returns as JSON like below
$new_vals = array(
'new_total' => $new_total,
'poll_option_1_val' => $poll_option_1_val,
'poll_option_2_val' => $poll_option_2_val,
);
echo json_encode($new_vals);
Below is the Ajax request – the first request works just fine to update the DB but the inner AJAX request isn’t working. In the below example I try to use alert to show new_total value but nothing happens
$(function () { // SUBMIT FORM WITH AJAX
$('#poll-form').on('submit', function (e) { //on form submit
e.preventDefault(); // prevent default behaviour
if($("form")[0].checkValidity()) { // check if the form has been validated
$.ajax({ // submit process
type: 'post',
url: 'vote-process.php',
data: $('form').serialize(),
success: function () {
$('#vote_submitted').modal('show');
$("input").attr("disabled", "disabled");
$("textarea").attr("disabled", "disabled");
$("#vote_button").attr("disabled", "disabled");
$("#vote_button").text("Vote submitted");
$.ajax({
url : 'new_values.php',
type : 'POST',
data : data,
dataType : 'json',
success : function (result) {
alert(result['new_total']);
},
error : function () {
alert("error");
}
});
},
error: function() {
$('#error').modal('show');
}
});
return false;
} else { // if the form is not valid
console.log("invalid form");
}
});
});
This has been driving me crazy. Any help would be very much appreciated!
2
Answers
What is data in the second ajax request ? data : data ? data is not defined so javascript maybe stop to execute entire code especially if use ‘use strict’
Second Ajax data:data will give you this issue need to pass proper parameter