Using JSONP in jQuery Ajax

PHP Server Side

    $callback = $_GET['callback'];
    $result = array();
    $result[0]['id'] = '111';
    $result[0]['title'] = 'Event1';
    $result[0]['start'] = '2014-05-10';
    $result[0]['end'] = '2014-05-12';

    $result[1]['id'] = '112';
    $result[1]['title'] = 'Event2';
    $result[1]['start'] = '2014-05-10';
    $result[1]['end'] = '2014-05-12';
    $jsdata = ($callback.'('.json_encode($result).');'); 
    echo $jsdata;

When using jsonp, it is very important to wrap the data with the callback. Try to look at the $jsdata variable, it is being wrapped by the $callback variable. That’s just how jQuery Ajax works. If you won’t wrap it with that one, you’ll get an error in your console.

Front End (Ajax and jQuery)

  jQuery.ajax({
    type:"GET",
    dataType:'jsonp',
    url: "http://mysite.com",
    error: function(xhr, status, error) {
      console.log(xhr);
      console.log(status);
      console.log(error);
    },
    success:function(data){
      console.log(data);
    }
  });

JSONP is important when trying to call an external domain in your ajax. It’s like when you’re in your http://localhost/myproject/index.php , then calling a domain at http://facebook.com/apiv1/something using ajax.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>