Vanilla Js Vs JQuery Ajax Call
I want to do an ajax call with vanilla js. In jQuery, I have this working ajax call: $.ajax({ url:'/faq/ajax', datatype: 'json', type:'POST', data: {search:'banana'
Solution 1:
You haven't told the server how you are encoding the data in the request.
r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Presumably whatever server side handler you are using to process the data isn't parsing it correctly, so isn't finding the data it needs, and then returns a blank array as the result.
Solution 2:
Beyond printing out r.responseText
to the console, you can also inspect the HTTP response from dev tools built into the browser itself.
On Firefox, for instance:
- Tools -> Web Developer -> Network (this should open a panel listing all the HTTP requests and responses)
- Go through the process you use to execute your AJAX call
- Look at the corresponding HTTP request by clicking on the item in the list in the panel shown in step 1 (a panel on the right should appear with more details about the request and subsequent response)
Digging around in these tools can give you a lot of insight into the the HTTP request your code is making and the values it's getting back in the response.
A similar process can be performed for all the major browsers out there.
Solution 3:
You can use this simple and lightweight Ajax module with the following syntax:
import {ajax} from '/path/to/ajax.min.js';
ajax('https://api_url.com')
.data('key-1','Value-1')
.data('key-2','Value-2')
.send()
.then((data) => { console.log ('success', data) })
.catch((status) => { console.log ('failed', status)} );
Post a Comment for "Vanilla Js Vs JQuery Ajax Call"