Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the alternative ways of making an Ajax call?

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.

like image 458
code-8 Avatar asked Dec 02 '22 16:12

code-8


2 Answers

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'
like image 147
Bhavin Solanki Avatar answered Dec 18 '22 01:12

Bhavin Solanki


There is a new async Fetch API that all of the modern browsers support:

fetch('./api/projects', {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            title: 'Beispielprojekt',
            url: 'http://www.example.com',
        })
    })
    .then(response => { console.log(response); })
    .catch(error => { console.error(error); });

See this post for more information.

like image 39
Nasser Abbassi Avatar answered Dec 17 '22 23:12

Nasser Abbassi