views:

544

answers:

2

Hi all,

I am using jquery's $.post for ajax (like populating a selectbox with a value selected in different selectbox). I used the following code for this

$('#cmbState').change(function(){
 $.post('<?php echo APP_URL."include/ajax.php"; ?>', {stateid: $(this).val(), option: 'getCitiesList'}, function(response){
  if(response != '')
  {
   $('#cmbCity').html(response);
  }
 })
});

The code above works perfectly fine but it does not notify the user that the ajax request is in process and he has to wait a bit.

I want to show an image next to the html control which is displayed until the response is loaded.

I want the answer in terms of jquery only. Found something related to this on jquery docs also ($.ajax) but I want to achieve this functionality using $.post method (if it is possible).

Please help me with this. any clues are greatly appreciated

thanks

+4  A: 
$.ajax({
    url:'/',
    data: params,
    type:'POST',
    beforeSend: function() {
        alert("loading")
    },
    success:function(html){ alert(html) }
});

Put your loading code inside the beforeSend function, which fires before success is invoked.

meder
thanks for your answer Mr. meder,can the same functionality be achieved using $.post method of jquery.?
Gaurav Sharma
I always tend to use the lower level `.ajax` because if you have to switch methods you can keep the rest of it intact, it's just more flexible.
meder
+4  A: 

You can use the ajaxStart and ajaxComplete global Ajax Events to execute a piece of code whenever an AJAX request starts or completes, for example:

// show the '#loading' element when ajaxStart, and hide it when ajaxComplete
$("#loading").bind("ajaxStart", function(){
  $(this).show();
}).bind("ajaxComplete", function(){
  $(this).hide();
});

By doing so, you don't need to add any logic for handling the loading message on all the Ajax requests you make.

CMS
Thanks Mr. CMSYour answer worked perfect.:)
Gaurav Sharma
You're welcome Mr. Gaurav, glad to help!
CMS