u238
u238

Reputation: 363

Ajax Callback function's location

I had a problem about callback function which was located in $(document).ready . Callback function didn't used to work. When I put it outside of $(document).ready the code has started to work perfectly. I don't understand why. Is location is important?

This works:

$(document).ready(function() {
  $("#button1").click(function() {
    $.ajax({
      url: "http://www.example.com/data.php",
      type: "get",
      dataType: "jsonp",
      jsonpCallback: "read",
    });
  });
});
var read = function(data) {
  console.log(data);
}

This does not work.

$(document).ready(function() {
  $("#button1").click(function() {
    $.ajax({
      url: "http://www.example.com/data.php",
      type: "get",
      dataType: "jsonp",
      jsonpCallback: "read",
    });
  });
  var read = function(data) {
    console.log(data);
  }
});

UPDATE1: Sorry guys, links werent't different. I forgot to change 2nd one. There is just one difference that location of read function.

Upvotes: 2

Views: 516

Answers (4)

ChevCast
ChevCast

Reputation: 59234

The reason you pass in the JsonP callback name as a string like that is because JQuery needs to add it to your URL like this ?callback=read. A JsonP request is just a <script> tag created by JQuery in the background and added to the page <script src="http://www.csstr.com/data.json?callback=read"></script>. Once JQuery adds that script tag to your page the browser will treat it like it's loading a normal JavaScript document to be exectued. Because of the ?callback=read part of the request, the remote server knows to respond with executable JavaScript and not just the raw data. That executable JavaScript is just a function call to a function with the name you provided, in this case the read function. Because the returned script is being executed in the global scope, the read function also needs to exist in the global scope. The global scope in the browser is the window object, so basically the read function needs to be present on the window object in order for the executed script to find the function.

$(document).ready(function() {
  $("#ara-button").click(function() {
    $.ajax({
      url: "http://www.csstr.com/data.json",
      type: "get",
      dataType: "jsonp",
      jsonpCallback: "read",
    });
  });
  window.read = function(data) {
    console.log(data);
  }
});

It works outside of the ready function in your first example because anything defined at the root level like that is globally scoped.

Codpen Demo: http://codepen.io/anon/pen/qNbRQw


If you want to know more about how JsonP works, read on.

If you're still confused it's probably because you're not 100% familiar with how JsonP actually works. JsonP is a hack to get around the Same-origin Policy. The short version of the Same-origin Policy is that the browser won't let you read the response returned from requests to domains other than the one the request originated from unless the server on that other domain says it's okay.

The Same-origin Policy was implemented by most browsers to help protect users from malicious scripts. For example, if you authenticated with your bank website in one browser tab and then went to a nefarious website in another tab, without same-origin restrictions in the browser that nefarious site could make an ajax request to your bank website. That request would carry any cookies your browser has stored for that domain and your cookies would show you as authenticated, thus giving the attacking script access to authenticated data from your bank account. The Same-origin Policy prevents the nefarious site from being able to see the response data from that request.

In the beginning there was no official way for the client and server to opt-in to cross-domain sharing. It was just straight up blocked by the browsers at the time. To get around this JsonP was invented. The Same-origin Policy only hides the response from ajax requests, but as you may have noticed the browser is totally fine with loading scripts from other websites via <script> tags. The script tag just does a plain old GET request for a javascript document, then starts executing that script on your page. JsonP takes advantage of the fact that same-origin restrictions don't apply to <script> tags.

Notice if you go directly to http://www.csstr.com/data.json in your browser you'll see the data you're after. However, try going there with the following query string added.

http://www.csstr.com/data.json?callback=read

Notice anything different? Instead of just returning the data you want the response comes back with your data being passed into a function named read. This is how you know the server understands the JsonP hack. It knows to wrap the data you want in a function call so that JQuery can perform the JsonP hack on the client, which it does by creating a <script> tag and embedding it in your web page. That script tag points to the URL but also adds that querystring to the end of it. The result is a script tag that loads a script from that URL and executes it. That script is being loaded into your page's global scope, so when the read function is called it expects that function to also exist in the global scope.

Today, the official way around the Same-origin Policy is via the Cross-origin Resource Sharing policy (aka CORS). JsonP essentially accomplishes the same thing that a proper CORS request does. The server has to opt-in by knowing how to format the response as executable JavaScript, and the client has to know not to do a normal ajax request but instead dynamically create a script tag and embed it in the page body. However, JsonP is still a hack and as hacks do it comes with its own set of downsides. JsonP is really hard to debug because handling errors is almost impossible. There's no easy way to catch errors if the request fails because the request is being made via a <script> tag. The <script> tag also lacks control over the format of the request being made; it can only make plain GET requests. The biggest downside to JsonP is the need to create a global function to be used as a callback for the data. Nobody likes polluting the global namespace but for JsonP to work it's required.

Proper CORS requests don't require extra effort on the client's part. The browser knows how to ask the server if it is allowed to read the data. The server just has to respond with the right CORS headers saying its okay and then the browser will lift the same-origin restrictions and allow you to use ajax as normal with that domain. But sometimes the resource you're trying to hit only knows JsonP and does not return proper CORS headers so you have to fallback on it.

For more info about CORS I wrote a pretty detailed blog post a little while ago that should really help you understand it. If you control the server that is returning the data you're after then you should consider just having it return the proper CORS headers and forget about JsonP. But it's totally understandable when you don't control the server and can't configure it to return the proper headers. Sometimes JsonP is the only way to get what you need, even if it does make you throw up in your mouth a little bit as you write the code.

Hope that helps clear some things up for you :)

Upvotes: 4

TCHdvlp
TCHdvlp

Reputation: 1334

$(document).ready(function() { means : Do it when the page finished to load. In the second example, you are defining the read function only after the page finished to load.

In the working example, you are defining the read function first and say, "Once the page will be loaded, do the ajax call and then, call read function"

Edit : Also, you can read @IGeoorge answer for a more detailed explaination.

Upvotes: 0

IGeoorge
IGeoorge

Reputation: 160

Your function is defined into Jquery Scope, so at the moment the ajax is executed, cannot find definition of "read" function.

That's why the first example works.

Hope this helps.

Upvotes: -1

Ravisha Hesh
Ravisha Hesh

Reputation: 1504

Add read method before ajax

$(document).ready(function() {
  var read = function(data) {
    console.log(data);
  }
  $("#ara-button").click(function() {
    $.ajax({
      url: "http://www.csstr.com/data.json",
      type: "get",
      dataType: "jsonp",
      jsonpCallback: "read",
    });
  });

});

Upvotes: -1

Related Questions