I have a function on a form submit, it executes everything but an ajax request. I do some checks before sending the data, but in the part where I check the checked state of the checkbox, I have a problem, when it is true it redirects to the URL that I specified, and with that the ajax success
never does nothing, actually the data is never sent to the Ajax URL. When checked is false the data is sent to the URL specified inside the ajax method (my ajax function is save_sell
).
And if I put the redirection code inside Ajax, the redirection never happens.
$('#my_form').on('submit', function(event){
event.preventDefault();
if ($('#select1').val()===''){
alert('Message 1');
}
else if ($('#select2').val()===''){
alert('Message2');
}
else if ($('#select3').val()===''){
alert('Message3');
}
else if ($('#select4').val()===''){
alert('Message4');
}
else if ($('#numperinput1').val()==='0.00' || $('#numberinput1').val()==='' ){
alert('Message5');
}
else if ($('#select5').val()===''){
alert('Message6');
}
else {
console.log("form submitted!") // sanity check
var tbl = $('table#My_table tr').get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
$.each(tbl, function(key,value) {
value.pop();
});
tbl.shift();
var tblJson=JSON.stringify(tbl);
save_sell(tblJson);
console.log("saving");
if ($('#checkbox1').is(':checked')) { //here is the problem
$(location).attr('href', '/the_url?number=5');
console.log("downloading");
}
console.log("after download");
}
});
EDIT: Here is my ajax function
function save_sell(table_array) {
$.ajax({
url : "/Store/Sell/",
type : "POST",
data : { table: table_array},
success : function(json) {
console.log('Success!');
var res_sell=json.idsell;
console.log('Sell:'+res_idsell);
$("#sell_result").text(res_idsell);
},
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! Error: "+errmsg+
" <a href='#' class='close'>×</a></div>");
console.log(xhr.status + ": " + xhr.responseText);
}
});
};
Is there a solution to send data through ajax and wait for ajax response before doing a redirect?
EDIT: I tried to add this, just wrote it on the script:
$( document ).ajaxComplete(function( event, xhr, settings ) {
if ( settings.url === "/Store/Sell/" ) {
console.log("Ajax complete");
if ($('#checkbox1').is(':checked')) {
console.log("Checked");
$(location).attr('href', '/the_url?number=5');
}
}
});
I can see the "Ajax complete" in the console, but the "Checked" is never written in the console.
I also tried to append this to the end of my ajax:
function save_sell(table_array) {
$.ajax({
//all the ajax thing that I posted before
}).done(function( data ) {
console.log("Ajax complete");
if ($('#checkbox1').is(':checked')) {
console.log("Checked");
$(location).attr('href', '/the_url?number=5');
}
});
};
And had the same results, I can see the "Ajax complete" in the console, but the "Checked" isn't never written in the console.