Reputation: 155
I'm having trouble making a jQuery AJAX request and getting the data back in the .done and .fail methods. Here is the code the calls the AJAX-requesting code:
async function doSomething(){
const addressValid = await isAddressValid(form.address1.value, form.address2.value, form.city.value, form.state.value, form.zip.value);
if(!addressValid) return
}
And here's the request code:
export default (address1, address2, city, state, zip) => {
console.log(`Checking address`);
return $.post('/api/validate', {
address1,
address2,
city,
state,
zip
})
.done(function(data, status, xhr){
// Address is valid
return true;
})
.fail(function(jqXHR, textStatus, errorThrown ){
// Address is invalid or API is down, etc
return false;
});
}
My problem is that the return statements in the .done() and .fail() do not work. After isAddressValid(), addressValid is either 'OK' if the address is good, or just nothing. There's multiple problems with this - the first is that it disregards my return true;
entirely. The second is that when the address is invalid, the server returns a 400, and that returns nothing at all to addressValid.
Per https://api.jquery.com/jquery.post/:
As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or "jqXHR," returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information).
So it seems like what I'm doing should work. I am thinking the promise will be resolved with my boolean return values, but it's not. I've done this in the past with promises (not jQuery). For example, use request-promise to request something, return the response and store it in a variable.
Would appreciate any assistance.
Upvotes: 2
Views: 1531
Reputation: 164936
My guess is this is due to jQuery's promise-like jqXHR object.
The await
keyword expects a promise and will use the standard then
(and maybe catch
) methods to determine the result.
Try this instead
return $.post(...).then(() => true, () => false)
Alternatively, use something other than jQuery that returns actual Promise
instances. Even the native fetch
API may be better suited.
Upvotes: 3