I have a Drupal 7 form, where on submit i call a PHP function via Ajax like this :
$('input[id*="edit-validate"]').click(function (e) {
var uploadcvPath = Drupal.settings.basePath + 'myfunction_submit';
$.ajax({
url: uploadcvPath,
data: $('form').serialize(),
xhrFields: {
onprogress: function (e) {
var thisResponse, response = e.currentTarget.response;
if (lastResponseLen === false) {
thisResponse = response;
lastResponseLen = response.length;
} else {
thisResponse = response.substring(lastResponseLen);
lastResponseLen = response.length;
}
jsonResponse = JSON.parse(thisResponse);
$('.ajax-res p').text('Processed ' + jsonResponse.count + ' of ' + jsonResponse.total);
$(".progress-bar").css('width', jsonResponse.progress + '%').text(jsonResponse.progress + '%');
}
},
success: function (response) {
alert('Success!!');
},
complete: function () {
//Hide loading container
alert('Done!!');
},
error: function (xmlhttp) {
alert('An HTTP error ' + xmlhttp.status + ' occurred.\n' + uploadcvPath);
},
});
e.preventDefault();
});
What i want to do is to return responses to feed a progress bar, so my PHP function looks like this :
function myfunction_submit() {
//First response
drupal_json_output(array('progress' => 50, 'count' => 50, 'total' => 50));
flush();
ob_flush();
sleep(2);
//Seconde response
drupal_json_output(array('progress' => 80, 'count' => 80, 'total' => 80));
flush();
ob_flush();
sleep(2);
}
This works fine with just the first response, but when i add the seconde one i get the following error :
Uncaught SyntaxError: Unexpected token { in JSON at position 37 at JSON.parse () at XMLHttpRequest.onprogress
position 37 correspond to the seconde { in the JSON response
{"progress":1,"count":1,"total":2}{"progress":2,"count":2,"total":2}
which means the Json format is not valid. My question is : Is there a problem with flush() function in Drupal 7 ? because the code above works to the perfection outside Drupal.
In case someone is having this probleme, i solved it by using
ob_end_flush();
ob_flush();
flush();
ob_start()
instead of
flush();
ob_flush();
I hope this helps someone someday !!