Sam Sam - 4 months ago 13
PHP Question

execute ajax inside condition before execute next ajax

I have two tables in a database , when pressing the submit button I want to insert new trader into trader table and get id using

laravel 5.2
by using post ajax under condition ,then execute another post ajax for invoice insert , but the problem in this case is when I press the submit it execute second ajax before the first ajax .. why?

$(document).ready(function(e) {

$('#invoiceForm').validate({

//rules: itemRules,

errorPlacement: function (element) {
return false;
},
submitHandler: function (event) {
//event.preventDefault();
// $('#selectedTraderName').valid();
var allItems = [];
$('tr.inputsItem').each(function () {
rowData = $(this).children('td').find('.form-control').map(function () {
return $(this).val();
}).get();
rowData.push(parseInt($(this).children('td').find('strong#autoTotal').text().trim()));
if($('select[id=selectedTraderName]').val() <= lastTraderID) {
rowData.push($('select[id=selectedTraderName]').val());
}
else{
newTrader = [];
newTrader.push($('#name').val());
newTrader.push($('#traderMail').val());
newTrader.push($('#mobileNumber').val());
newTrader.push($('#address').val());
$.ajax({
type: 'POST',
url: insertNewTrader,
data:{_token:token, trader:newTrader}
}).done(function (msg) {
rowData.push(msg['id']);
});

}
alert(rowData[6]);
allItems.push(rowData);
$.ajax({
type: 'POST',
url: insertNewItem,
data:{_token:token, items:allItems}
}).done(function () {
alert('done');
});
});


}

});

Answer

Of course, you can't nest ajax calls because of the if/else statement instead you can use a Deferred object like this:

rowData.push(parseInt($(this).children('td').find('strong#autoTotal').text().trim()));
// Create a new Deferred object
var deferred = $.Deferred();
if ($('select[id=selectedTraderName]').val() <= lastTraderID) {
    rowData.push($('select[id=selectedTraderName]').val());
    //Nothing to wait just resolve the deferred
    deferred.resolve();
} else {
    newTrader = [];
    newTrader.push($('#name').val());
    newTrader.push($('#traderMail').val());
    newTrader.push($('#mobileNumber').val());
    newTrader.push($('#address').val());
    $.ajax({
        type: 'POST',
        url: insertNewTrader,
        data: {
            _token: token,
            trader: newTrader
        }
    }).done(function(msg) {
        rowData.push(msg['id']);
        //Resolve the deferred
        deferred.resolve();
    });

}
//When the deferred resolved then execute your next ajax request
deferred.then(function() {
    allItems.push(rowData);
    $.ajax({
        type: 'POST',
        url: insertNewItem,
        data: {
            _token: token,
            items: allItems
        }
    }).done(function() {
        alert('done');
    });
});

I hope thsi will help you.