3

I am trying to make a cross-domain request using jQuery/AJAX. I have the following code;

$.ajax({
   url: "http://www.cjihrig.com/development/jsonp/jsonp.php?callback=jsonpCallback&message=Hello",
   crossDomain:true
})
.done(function( msg ) {
  alert( "Done : " + msg );
})
.fail(function( msg) {
  alert( "Fail : " + msg);
})
.always(function( msg ) {
  alert( "Always : " + msg );
});

The URL http://www.cjihrig.com/development/jsonp/jsonp.php?callback=jsonpCallback&message=Hello returns JSON object when calling directly and works fine when using JSONP in traditional manner (i.e. through dynamic script tag injection)

But why do I get an error when using it with jQuery/AJAX ?

copenndthagen
  • 49,230
  • 102
  • 290
  • 442

2 Answers2

1

Try this code because the error isn't set the dataType and isn't expect a jsonp default
dataType: (default: Intelligent Guess (xml, json, script, or html))
Type: String

  $.ajax({
   url: "http://www.cjihrig.com/development/jsonp/jsonp.php?callback=jsonpCallback&message=Hello",
   dataType: 'jsonp',
   crossDomain:true,
    jsonp: false,
    success: jsonpCallback,
})
.done(function( msg ) {
  alert( "Done : " + msg );
})
.fail(function( msg) {
  alert( "Fail : " + msg);
})
.always(function( msg ) {
  alert( "Always : " + msg );
});

 function jsonpCallback(data){
        alert("jsonpCallback");
    }

DEMO

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171
0

I would use $.ajax with the option:

dataType: "jsonp"

This automatcially adds the callback option to the url. http://api.jquery.com/jQuery.ajax/

SteveP
  • 18,840
  • 9
  • 47
  • 60