javascript - jQuery $.ajax success firing last -
this question has answer here:
i have following javascript , it's returning results out of order expect them.
function getcurrentitems(id){ alert("2"); $.ajax({ url: "somephpurlthatspitsoutajsonencodedarray.php", type: "post", datatype: "json'", data: {id:id}, success: function(data){ alert("3"); } }); alert("4"); } $(document).on('click', '.eventclass', function(e){ alert("1"); var id = "someid"; var results = getcurrentitems(id); alert("5"); }); i think i'd alerts in order of 1, 2, 3, 4, 5.
instead them in order of 1, 2, 4, 5, 3.
i can't figure out why success alert (5) fires last?
ajax short asynchronous javascript , xml. asynchronous keyword here. i'll use allegory explain async.
lets you're washing dishes manually. can't else while doing that, synchronous.
lets put dishes in dishwasher. can other things, you've delegated task dishwasher, asynchronous. asynchronous better, because can multiple things @ 1 time. javascript asyncs when requesting info server, javascript single threaded (it runs on 1 cpu core , can 1 thing @ time on it's own).
a callback function called when async task completes. dishwasher finishes, have empty complete you're doing when finshed.
so in code, start dishwasher, you're going alert("3") when dishwasher finishes running, , go alert 4 , 5. when dishwasher finishes/your server returns data, alert 3 said would.
that make sense?
Comments
Post a Comment