Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax order does not match selection order with async:true

Tags:

jquery

ajax

I have this code which is called at an onChange event of an

function group_changed(obj)
{
  $.ajaxSetup({async:false});
  $.post("/medilab/personnel/groups/getGroupRightsAjax",
    { 'group.id': obj.options[obj.selectedIndex].value },
    function(data){
      $("#div_rights").html(data);
    }
  );
}

This works fine but if i set async:true sometimes the result doesnt match the selection... I guess that this is happening because some requests are lost or that the responses dont come in order.

Any idea what to do to keep it asynchronous?

like image 241
GorillaApe Avatar asked Mar 15 '10 14:03

GorillaApe


People also ask

What is async true in Ajax?

async (default: true ) Type: Boolean. By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false . Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.

What is async false in Ajax call?

Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.

How do you make Ajax not async?

When the async setting of the jQuery AJAX function is set to true then a jQuery Asynchronous call is made. AJAX itself means Asynchronous JavaScript and XML and hence if you make it Synchronous by setting async setting to false, it will no longer be an AJAX call.

Are Ajax calls asynchronous by default?

Yup. Ajax calls are asynchronous by nature and defaults to true.


2 Answers

There are a few plugins for jQuery that support queuing and ordering of the ajax requests. John Resig wrote Ajax Queue. From the plugin description:

Ajax Queue is a plugin that helps to manage Ajax race conditions. When multiple Ajax requests are made in rapid succession, the results can be returned out of order. This can cause weird behavior in your application.

This sounds like it may be what you need, there should also be a couple different plugins available that accomplish the same thing (keeping ajax requests ordered). Ajax Manager looks to be more up-to-date. Browse through some of the plugins, you might find something that already does what you are looking to accomplish, saving you time.

like image 178
Astra Avatar answered Nov 09 '22 23:11

Astra


try this, it may be a better solution.

$.ajax
({
    type:'post',
    data:'',
    dataType: 'html',
    url: '',
    success: function(data) {
        alert('data');
    },
    error: function()   {
       alert("Error");
    }
});
like image 37
Fribu - Smart Solutions Avatar answered Nov 10 '22 00:11

Fribu - Smart Solutions