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?
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);
});
Try extending jQuery:
$.extend({doPost: function(url, data, success, error) {
$.ajax({
url: url,
type: 'POST',
contentType: "application/json",
data: JSON.stringify(data),
success: success,
error: error
});
}
});
$.doPost('/api/something/', {"key" : "value"}, function(data) {
console.log("data : %o", data);
});
Try
$.post(
'api/something',
{ key: 'value' },
function( data ) {
...
},
'json'
);
See http://api.jquery.com/jquery.post/ for more details
Try with $.post
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Related
GET:$.get(..)
POST:$.post()..
What about PUT/DELETE?
You could use the ajax method:
$.ajax({
url: '/script.cgi',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
$.ajax will work.
$.ajax({
url: 'script.php',
type: 'PUT',
success: function(response) {
//...
}
});
We can extend jQuery to make shortcuts for PUT and DELETE:
jQuery.each( [ "put", "delete" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
and now you can use:
$.put('http://stackoverflow.com/posts/22786755/edit', {text:'new text'}, function(result){
console.log(result);
})
copy from here
Seems to be possible with JQuery's ajax function by specifying
type: "put" or
type: "delete"
and is not not supported by all browsers, but most of them.
Check out this question for more info on compatibility:
Are the PUT, DELETE, HEAD, etc methods available in most web browsers?
From here, you can do this:
/* Extend jQuery with functions for PUT and DELETE requests. */
function _ajax_request(url, data, callback, type, method) {
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
}
jQuery.extend({
put: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'PUT');
},
delete_: function(url, data, callback, type) {
return _ajax_request(url, data, callback, type, 'DELETE');
}
});
It's basically just a copy of $.post() with the method parameter adapted.
Here's an updated ajax call for when you are using JSON with jQuery > 1.9:
$.ajax({
url: '/v1/object/3.json',
method: 'DELETE',
contentType: 'application/json',
success: function(result) {
// handle success
},
error: function(request,msg,error) {
// handle failure
}
});
You should be able to use jQuery.ajax :
Load a remote page using an HTTP
request.
And you can specify which method should be used, with the type option :
The type of request to make ("POST" or
"GET"), default is "GET". Note: Other
HTTP request methods, such as PUT and
DELETE, can also be used here, but
they are not supported by all
browsers.
ajax()
look for param type
Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
For brevity:
$.delete = function(url, data, callback, type){
if ( $.isFunction(data) ){
type = type || callback,
callback = data,
data = {}
}
return $.ajax({
url: url,
type: 'DELETE',
success: callback,
data: data,
contentType: type
});
}
You can do it with AJAX !
For PUT method :
$.ajax({
url: 'path.php',
type: 'PUT',
success: function(data) {
//play with data
}
});
For DELETE method :
$.ajax({
url: 'path.php',
type: 'DELETE',
success: function(data) {
//play with data
}
});
If you need to make a $.post work to a Laravel Route::delete or Route::put just add an argument "_method"="delete" or "_method"="put".
$.post("your/uri/here", {"arg1":"value1",...,"_method":"delete"}, function(data){}); ...
Must works for others Frameworks
Note: Tested with Laravel 5.6 and jQuery 3
I've written a jQuery plugin that incorporates the solutions discussed here with cross-browser support:
https://github.com/adjohnson916/jquery-methodOverride
Check it out!
CRUD
this may make more sense
CREATE (POST)Request
function creat() {
$.ajax({
type: "POST",
url: URL,
contentType: "application/json",
data: JSON.stringify(DATA1),
success: function () {
var msg = "create successful";
console.log(msg);
htmlOutput(msg);
},
});
}
READ (GET)Request
// GET EACH ELEMENT (UNORDERED)
function read_all() {
$.ajax({
type: "GET",
url: URL,
success: function (res) {
console.log("success!");
console.log(res);
htmlOutput(res);
},
});
}
// GET EACH ELEMENT BY JSON
function read_one() {
$.ajax({
type: "GET",
url: URL,
success: function (res) {
$.each(res, function (index, element) {
console.log("success");
htmlOutput(element.name);
});
},
});
}
UPDATE (PUT)Request
function updat() {
$.ajax({
type: "PUT",
url: updateURL,
contentType: "application/json",
data: JSON.stringify(DATA2),
success: function () {
var msg = "update successful";
console.log(msg);
htmlOutput(msg);
},
});
}
DELETE (DELETE)Request
function delet() {
$.ajax({
type: "DELETE",
url: deleteURL,
success: function () {
var msg = "delete successful";
console.log(msg);
htmlOutput(msg);
},
});
}
GitHub Reference
You could include in your data hash a key called: _method with value 'delete'.
For example:
data = { id: 1, _method: 'delete' };
url = '/products'
request = $.post(url, data);
request.done(function(res){
alert('Yupi Yei. Your product has been deleted')
});
This will also apply for
I would like to post Json to a web service on the same server. But I don't know how to post Json using JQuery. I have tried with this code:
$.ajax({
type: 'POST',
url: '/form/',
data: {"name":"jonas"},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
But using this JQuery code the data is not received as Json on the server. This is the expected data at the server: {"name":"jonas"} but using JQuery the server receive name=jonas. Or in other words, it's "urlencoded" data and not Json.
Is there any way to post the data in Json format instead of urlencoded data using JQuery? Or do I have to use a manual ajax request?
You're passing an object, not a JSON string. When you pass an object, jQuery uses $.param to serialize the object into name-value pairs.
If you pass the data as a string, it won't be serialized:
$.ajax({
type: 'POST',
url: '/form/',
data: '{"name":"jonas"}', // or JSON.stringify ({name: 'jonas'}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Base on lonesomeday's answer, I create a jpost that wraps certain parameters.
$.extend({
jpost: function(url, body) {
return $.ajax({
type: 'POST',
url: url,
data: JSON.stringify(body),
contentType: "application/json",
dataType: 'json'
});
}
});
Usage:
$.jpost('/form/', { name: 'Jonh' }).then(res => {
console.log(res);
});
you can post data using ajax as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
I tried Ninh Pham's solution but it didn't work for me until I tweaked it - see below. Remove contentType and don't encode your json data
$.fn.postJSON = function(url, data) {
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json'
});
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {
"name":"jonsa",
"e-mail":"qwerty#gmail.com",
"phone":1223456789
};
$.ajax({
type: 'POST',
url: '/form/',
data: Data,
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.
var DoPost = function(url, body) {
try {
body = JSON.stringify(body);
} catch (error) {
return reject(error);
}
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: url,
data: body,
contentType: "application/json",
dataType: 'json'
})
.done(function(data) {
return resolve(data);
})
.fail(function(error) {
console.error(error);
return reject(error);
})
.always(function() {
// called after done or fail
});
});
}
i got my json string inside the ajax as function like this way
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
},
error: function () {
alert('Error');
}
});
here i get data like
[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
i want it in a variable like
var myjsonobject =[{"main":{"sub":[],"tittle":"manu","startvalue":"","stopvalue":"","status":"","accumalated":"","comment":""}}]
There you go :
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
alert('Success');
var jsonobject = data;
},
error: function () {
alert('Error');
}
});
Also I strongly advise you to use promises to make API calls: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
var jsonobject= null;
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
jsonobject=data;
alert('Success');
},
error: function () {
alert('Error');
}
});
If you want wait for ajax response and fill up variable then pass async: false in ajax request options.
Based on your comment, you need to parse the JSON in your success handler,
success: function (data) {
alert('Success');
var myjsonobject = JSON.parse( data );
},
Here is the code I am using to access my web API controller named Owner; the success function is not being called. Any ideas?
$.ajax({
type: "GET",
url: 'http://localhost:26533/api/Owner',
contentType: "application/json",
dataType: "jsonp",
success: function (response) { alert("yes"); }
});
Remove the contentType and dataType and check the response..
Here an example:
$.ajax({
type: 'GET',
url: 'http://localhost:26533/api/Owner',
success: function(data){
alert(data);
},
error: function(xhr, type, exception) {
// if ajax fails display error alert
alert("ajax error response type " + type);
}
});
With this you can see what's wrong...
Here is my script:
$.ajax({
type: "Get",
url: "Sample.js",
datatype: 'json',
data: JSON.stringify({ key:key }),
success: function (data) {
var sample = data.name;
$("#html").html(sample);
},
error: function () {
alert("Error");
}
});
This is my Sample.js file:
{ "name": "user" }
When I run this code I get a blank screen. This is my script using getJSON():
$.getJSON("Sample.js", function (data) {
var sample = data.name;
$("#html").html(sample);
})
This produces "user" perfectly. What is the problem with $.ajax code?
In the getJSON version your don't send any data. Could this be the reason why that works? To me it looks like this could be sth. on the server side that delivers an empty JSON object when you pass the key parameter.
As the jQuery documentation states:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Try modifying the dataType param.
change your datatype to dataType. Its case sensitive. Refer http://api.jquery.com/jQuery.getJSON/
Remove JSON.Stringify and change Get to GET
$.ajax(
{ type: "GET",
url: "Sample.js",
dataType: "json",
data: {key:key },
success: function (data)
{ var sample = data.name; $("#html").html(sample); },
error: function () { alert("Error"); }}
);