What are the alternative ways of making an Ajax call?
Solution 1
Yes there are some other ways to call ajax
jQuery
var get_data = function(){
var result = false;
$.get('/rest/computer').done(function(awesome_data){
result = awesome_data;
});
return result;
}
$.getJSON
$.getJSON( '/rest/computer', { assessmentId:"123", classroomId:"234"})
.done( function(resp){
// handle response here
}).fail(function(){
alert('Oooops');
});
If you're not using jQuery in your code, this answer is for you
Your code should be something along the lines of this:
function foo() {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "/rest/computer");
httpRequest.send();
return httpRequest.responseText;
}
var result = foo(); // always ends up being 'undefined'
Solution 2
there is also async api that all of the modern browsers support it
fetch('./api/projects',
{
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'Beispielprojekt',
url: 'http://www.example.com',
})
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.error(error);
});
Solution 3
Not really clear what the underlying context of your question is but for example shown you can use :
$.getJSON( url, { assessmentId:"123", classroomId:"234"})
.done( function(resp){
// handle response here
}).fail(function(){
alert('Oooops');
});
$.getJSON is a wrapper for $.ajax
that simplifies needing to add a number of options that are already preset
Solution 4
Following have also one of the type ajax call using post method.
var assessmentId = "123"
var formURL = '/rest/computer';
var postData = { "action":"add","data":assessmentId};
$.post(formURL, postData, function( response ) {
// handle response here
});
code-8
I'm B, I'm a cyb3r-full-stack-web-developer. I love anything that is related to web design/development/security, and I've been in the field for about ~9+ years. I do freelance on the side, if you need a web project done, message me. ;)
Updated on October 08, 2020Comments
-
code-8 over 3 years
I'm wondering what is the best way to make an AJAX call.
This is what I have right now, and it works just fine.
$.ajax({ url: "/rest/computer", type: "GET", dataType: "json", data: { assessmentId: "123", classroomId: "234" }, success: function(objects) { // .... code .... } });
I'm currently seeking another ways of making an Ajax call. If there is, should I use my approach ?
Should I move an Ajax call into it own function and call it back ?
Any suggestions on this will be much appreciated.