Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery shortcut for sending ajax/JSON requests

I am working on a application that uses a REST architecture style. Hence, I often do some calls to the backend with JSON data.

jQuery is new to me and up to now, the only syntax that worked for me is :

$.ajax({
  url: '/api/something/',
  type: 'POST',
  contentType:"application/json", //Or I will get 400 : Bad request
  data: JSON.stringify({key : "value"}),
  success: function (data) {
    console.log("data : %o", data);
  }
});

But I do not want to write explicitly contentType:"application/json" and JSON.stringify at every call. I would prefer something like :

$.someFunction({
  url: '/api/something/',
  type: 'POST',
  data: {key : "value"},
  success: function (data) {
    console.log("data : %o", data);
  }
});

Maybe I could make a function in order to factorize this but I feel that jQuery should have a pre-existing function for that.

Anyone knows such function?

like image 847
Arnaud Denoyelle Avatar asked Nov 24 '25 20:11

Arnaud Denoyelle


1 Answers

Just wrap everything in a function and pass the parameters you need.

var thinPostWrapper = function(url, data, success) {
    return $.ajax({
        url: url
        type: 'POST',
        contentType: "application/json",
        data: JSON.stringify(data),
        success: success
    });
}

thinPostWrapper('/api/something/', {"key" : "value"}, function(data) {
    console.log("data : %o", data);
});
like image 193
Etheryte Avatar answered Nov 26 '25 08:11

Etheryte