UpQuark
UpQuark

Reputation: 801

How do I pass request data into the Complete event in JQuery.ajax

I'm trying to write code to send a jquery AJAX POST request and I'm having some trouble emulating some examples I see.

I want to send a post request to a third party website, and then call a function that would write the responseText to a div, pretty basic stuff.

function addSearch(searchTerm) {
    $.ajax({
        accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        url: "http://www.website.com",
        contentType: "application/x-www-form-urlencoded",
        beforeSend : function (xhr) {
            xhr.setRequestHeader("AcceptLanguage", "en-US,en;q=0.5");
            xhr.setRequestHeader("AcceptEncoding", "gzip, deflate");
        },
        type: "POST",
        data: createBody(searchTerm),
        complete: doStuffOnComplete(xhr, status)
    });
}

function doStuffOnComplete(xhr, status) {
    var response = xhr.responseText;
    $("#content").append(response);
}

I'm following some other basic examples I've seen on here. While I get no errors about the 'xhr' variable in the beforeSend event, I am getting an error in Complete when the script is called, saying xhr is undefined.

I'm sure I'm just messing up something simple, but not having much experience with Jquery, Ajax, or javascript in general I'm not sure what.

Upvotes: 2

Views: 189

Answers (2)

UpQuark
UpQuark

Reputation: 801

Fun PSA for anyone who comes across this later. Turns out this particular bit is impossible! POST requests cannot be made to external domains, because it violates the same-origin policy. GET requests can be made to external domains using JSONP but sadly there is no way to do this via POST from the client.

The best workaround I've seen discussed (other than using a JSONP GET request, which in my case isn't possible) is sending the POST request to your own server which in turn sends the request to the external domain.

Upvotes: 0

Grim...
Grim...

Reputation: 16953

I expect you're having a problem with the fact the url is a third party.

Try adding dataType: 'jsonp' after type: "POST".

Also, rather than using 'complete', I would use 'success' and 'error':

[...]
    type: "POST",
    dataType: "jsonp",
    data: createBody(searchTerm),
    success: function(data) {
        console.log(data);
    }
    error: function(data) {
        console.error(data);
    }
});

Upvotes: 1

Related Questions