Ajax with JQuery: 200 ok, but not “success”

17,953

Attempted cross domain XMLHttpRequest requests may fool you. In Firefox web console, it may look like URL loaded fine, but body is an empty string.

Confirm that the server supports JsonP. If you don't really know what that means, you need to look it up. It is critically important.

jQuery assumes that the JsonP parameter is going to be "?callback=". If that is not true, you should see this: http://api.jquery.com/jQuery.ajax/

jsonp: Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" }

jsonpCallback: Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function.

If it gets confusing, it may be easier to just do it the old fashioned way and appends the script to the page yourself with a time stamp in the URL to avoid using a cached script page.

BTW, AFAIK, there is no way to combine JSONP and POST. JSONP is a way of working around the same origin security policy of XMLHttpRequest. It requires you to append a script to the DOM. I don't think you can do that and also submit POST variables as part of the process.

Share:
17,953
Swatantra Kumar
Author by

Swatantra Kumar

Swatantra is a technology evangelist and a thought leader. He has deep roots in software engineering, architecture design, server administration and program management. When he is not working, he enjoys reading about new technologies. He has written, co-written and published many articles in international journals, on various topics including Open Source, Networks, Performance Management, and Low-Code. He made a proposal for a social network and media platform for students at the University during his graduation days. Microsoft Certified: Azure Solutions Architect Expert Microsoft Certified: Azure Administrator Associate AWS Certified Solutions Architect Associate The Open Group Certified: TOGAF®9 Certified OutSystems Associate Tech Lead OutSystems Associate Web Developer OutSystems Associate Sales Certified ScrumMaster® SAFe®5 Agilist Agile Business Expert – Agile Coach IBM Enterprise Design Thinking Practitioner PRINCE2® Practitioner Certificate in Project Management ITIL® Foundation Certificate in IT Service Management

Updated on June 04, 2022

Comments

  • Swatantra Kumar
    Swatantra Kumar almost 2 years

    I'm facing the same issue, while trying for cross-domain request. Situation is strange, my data is getting loaded while hit the requested url directly on browser, the strange part is, this gets loaded if requested using jquery ajax as well, but not on firebug console, but on firebug net tab. Console prints: Sample of error data: parsererror {while json data is well-formed and formatted, checked on json validators}

    readyState: 4 status: 200 responseText: undefined
    

    Net tab loads all the data in response and json sub-tab

    My sample code is:

    function fetchJsonData() {
    $.ajax({
        type: 'POST',
        url: 'http://www.meilleurmobile.com/comparateur/resultats-comparateur-json.do',
        data: 'monthDur%5B0%5D=45.75&monthDur%5B1%5D=45.75&monthDur%5B2%5D=45.75&monthDur%5B3%5D=45.75&monthDur%5B4%5D=45.75&monthDur%5B5%5D=45.75&monthDur%5B6%5D=45.75&monthDur%5B7%5D=45.75&monthDur%5B8%5D=45.75&monthDur%5B9%5D=45.75&monthDur%5B10%5D=45.75&monthDur%5B11%5D=45.75&numSms=1000&dataVolume=1000&withoutMobile=-1&commitmentDuration=-1',
        async: false,
        cache: false,
        //contentType: 'application/json; charset=utf-8',
        crossDomain: true,
        dataType: 'jsonp',
        error: function( xhr,err ) {
            console.log( 'Sample of error data:', err );
            console.log("readyState: "+xhr.readyState+"\nstatus: "+xhr.status+"\nresponseText: "+xhr.responseText);
        },
        success: function( data ) {
            if (console && console.log) {
                console.log( 'Sample of data:', data.slice(0,100) );
            }
        }
    })
    .done(function() { alert("success"); })
    .fail(function() { alert("error"); });
    

    }

  • Swatantra Kumar
    Swatantra Kumar about 12 years
    Daniele, It's not going in success, but the error block. Ajax gets failed. In fact proper validated JSON objects appear in NET tab of firebug. try switching JSON to JSONP in dataType :(
  • Swatantra Kumar
    Swatantra Kumar about 12 years
    Yeah true. I guess there is such limitation with AJAX for cross-domain communication. JSONP is the right dataType instead of JSON, but that was also a hack. As any AJAX request was not visible, it throws me the parsererror. In-spite of correct and valid well-formed JSON Object/String. I found one way to solve this using YUI api, jQuery. And most amazing it was using JSONP and POST, in contradict to your statement, and it worked.
  • DG.
    DG. about 12 years
    Regarding "And most amazing it was using JSONP and POST, in contradict to your statement, and it worked." - If you are really adding a JSONP script to the page combined with POST, then you are either using a server side proxy, or using some sort of hack that is not "pure" JSONP and requires the cooperation of the remote server. Such a hack would not be universally usable.
  • DG.
    DG. about 12 years
    To be honest, and I don't mean to offend you with this statement, but it seems to me that you might possibly be relying too heavily on hidden magic of the libraries and don't really know what is happening. I think that might burn you later on. I think it is entirely possible that you are not actually using JSONP or you are not really posting the vars, but instead using GET. Without access to all the code and details, I can't know the details. In any case, if my answer and comments helped you, please accept, or at least vote up.
  • Swatantra Kumar
    Swatantra Kumar about 12 years
    That's correct, I'm using a proxy, and this is not a good practice, and internally it uses GET method, no matter, I'm explicitly calling POST or GET. I am still trying to solve this without using any remote server call. The whole code has been posted in thread, and if you can suggest, that would be much appreciable.
  • DG.
    DG. about 12 years
    If the data provider does not support JSONP, and you must access the code from a different website, then there is NO pure Javascript solution possible without using a web proxy. A Java applet could be used BUT user would need to approve the applet to be run when prompted by the browser. Other than that, you could ask users to install an addon.
  • DG.
    DG. about 12 years
    You accepted your own answer after getting hints from other people about what what wrong?
  • Swatantra Kumar
    Swatantra Kumar about 12 years
    Hi DG. Thanks for all your suggestion. It actually helped me to write the above sample of code, which is the working example, and solved the problem. I would like to request you to add a sample code, which is executable script. So that i can accept it as a correct solution. Undoubtedly your hint helped me to write above piece of code. Many Thanks for the concept.
  • DG.
    DG. about 12 years
    Writing sample code is not a requirement of this website. The goal is to provide help. Help comes in many forms; not always code. I showed you the core problem. As a programmer, you should and then did fill in the details. It is interesting that you found a rather unusual solution of using yahooapis. Many people would not want to rely on this type of solution, but if it works for you, that is great. However, accepting your own answer and then telling me to write code to get accepted is not cool. Not cool at all.
  • Swatantra Kumar
    Swatantra Kumar about 12 years
    DG, I apologize, if you took it personally. My only idea was to post the working solution, irrespective of source. Definitely full credit goes to you. Accepted your concept as the best answer. Thanks for assistance.
  • DG.
    DG. about 12 years
    Posting more details on your particular solution was great. Not accepting my answer was not great. Thank you for the correction. Much appreciated.
  • snakesNbronies
    snakesNbronies over 10 years
    I gave you an imaginary internet point because I feel you were very upset.