Search code examples
javascriptjqueryjsonajaxjsonp

AJAX callbacks never called, not succes nor error


document.getElementById('myform').addEventListener('submit', function (e) {

// voorkomt de standaard actie van de submit
e.preventDefault();
$(function () {
    var artiest = document.getElementById("artiest");
    var rijen = document.getElementById("rij");
    var kolommen = document.getElementById("kolom");

    var CGIurl = 'http://localhost:8000/cgi-bin/schuifpuzzel.py?artiest=' + artiest.value +
        "&rijen=" + rijen.value + "&kolommen=" + kolommen.value  + "&callback=jsonp";

    $.ajax({
        type: 'GET',
        url: CGIurl,
        dataType: "jsonp",
        success: function(data){
            console.log(data)
        }

    });

});
});

I am trying to run this AJAX to execute my CGI script when the submit button is pressed. So I made use of an eventListener and preventDefault.

The GET seems to be working fine because these are the results I am getting when testing in the browser

The JSON in the response headers is the one I am trying to retrieve. But for some reason the succes nor the error in my AJAX is called, so I have no way to access to JSON.


Solution

  • There's two things I can see that are incorrect:

    • the JSON response data is sent in the response headers, instead of the response body;
    • jQuery is performing a JSONP request, which means that the response should be valid Javascript (not JSON), which should call the supplied callback function (if that doesn't get called, jQuery won't know the request has been completed, hence neither the success nor error callbacks get called);

    Fixing this depends on whether or not you need JSONP. If not, just use json as data type and make sure that the JSON data is in the response body. If you do need JSONP, your CGI script should provide a valid JS response, which would look something like this:

    jQueryXXX({ "content" : { "size" : ... } });
    

    (where jQueryXXX should be the value of the callback query string parameter)