Binyamin
Binyamin

Reputation: 7803

jQuery: How to enable `beforeSend` for `$.ajax({dataType:'jsonp'...`? Is there any solution?

jQuery: How to enable beforeSend for $.ajax({dataType:'jsonp'...? Is there any solution? http://jsfiddle.net/laukstein/2wcpU/

<div id="content"></div>
<script>
$.ajax({
    type:"GET",
    url:'http://lab.laukstein.com/ajax-seo/.json',
    dataType:'jsonp',
    async:false,
    beforeSend:function(data){ // Are not working with dataType:'jsonp'
      $('#content').html('Loading...');
    },
    success:function(data){
        $('#content').html(data.content);
    }
});
</script>

Upvotes: 2

Views: 16031

Answers (3)

codeandcloud
codeandcloud

Reputation: 55248

As per jQuery documentation

When data is retrieved from remote servers (which is only possible using the script or jsonp data types), the operation is performed using a tag rather than an XMLHttpRequest object. In this case, no XMLHttpRequest object is returned from $.ajax(), and the XMLHttpRequest object and the textStatus arguments passed to the handler functions such as beforeSend will be undefined. The error callback will never be fired for JSONP requests.

The same question is asked at the jQuery forums ajax:beforeSend for jsonp requests don't fire

The question's status is Status : Working on it. So it might be there at a future release.

And as Mike Alsups noted

I would name than function something other than 'beforeSend' since the semantics are not the same.

Also related : jsonp is not firing beforeSend?


Cannot use beforeSend with jsonp. Period.

Upvotes: 4

Behnoosh Moshtagh
Behnoosh Moshtagh

Reputation: 41

you can use this code:

befor $.ajax put it, and you should have an image(or div,span ,...) loading with "div_loading" id.

$("#div_loading").ajaxStart(function(){$(this).show();});
$("#div_loading").ajaxStop(function(){$(this).hide();}); 

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630549

This is just the nature of how JSONP works, creating a <script> tag, not actually using a XMLHttpRequest to get data. For what you're doing, you can just run the code before, like this:

$('#content').html('Loading...');
$.ajax({
  type:"GET",
  url:'http://lab.laukstein.com/ajax-seo/.json',
  dataType:'jsonp',
  async:false,
  success:function(data){
    $('#content').html(data.content);
  }
});

Upvotes: 5

Related Questions