I would like to send JSON post request to rails 3 server. I have following ajax request:
$.ajax({
type: 'POST',
contentType: "application/json",
url: url,
data: {email: "example#test.com", password: "password"},
success: onSuccess,
error: onError,
dataType: "json"
});
However the rails server receive the data as following:
{"_json"=>["object Object"]}
Where I want it to receive it as:
{"email"=>"exmaple#test.com", "password"=>"[FILTERED]"}
I think this is happening because the jquery wraps the data with _json object if the content type is json.
Does anybody know how I should do this?
This turns out to be because of bugs in old version of jquery. I now user jquery version 1.5 and send post request as follow:
$.post(url, { email: emailVal, password: passwordVal }, callback, "json").error(errorHandler);
It now works perfectly fine.
have you tried doing the serialization yourself (using jQuery.param)?
jQuery.param({email: "example#test.com", password: "password"})
==> "email=example%40test.com&password=password"
So that your ajax request becomes:
$.ajax({ type: 'POST',
contentType: "application/json",
url: url, data: $.param({email: "example#test.com", password: "password"}),
success: onSuccess,
error: onError,
dataType: "json"
});
According to jquery docs it seems like if you pass in an object to data it will try some automatic deserialization.
Set processData: false and then set data to json string.
http://api.jquery.com/jQuery.ajax/
Related
I am trying to make an AJAX request from my client to my NodeJS/ExpressJS backend.
However, when the request is fired, my backend receive it well but doesn't recognize the custom headers . e.g.
$.ajax({
type: "POST",
url: "/foo",
headers: {"authorization": "Bearer 12345"},
data: formData,
dataType: "json",
encode: true,
})
in Node , when I do req.headers['authorization'] I get undefined.
I don't understand what I did wrong.
Any advice ?
I'm not sure whether the request you're making is cross-url or not, but if it is try the following:
$.ajax({
url: "yoururl",
type: "GET",
dataType: 'json',
xhrFields: {
withCredentials: true // edited
},
//...
});
I ran into the same error a few times before and it was due to me not adding this important attribute to the request - when authentication is required.
I've got an ajax call to the following php method:
public function test(){
die(json_encode(['test' => 'test1']));
}
My ajax call works when set as GET but not as POST. The GET call is:
$.ajax({
type: 'get',
url: url,
success: function(msg) {
log(msg);
},
dataType: 'json'
});
Which successfully returns the JSON element. But when I set it as POST:
$.ajax({
type: 'post',
url: url,
success: function(msg) {
log(msg);
},
dataType: 'json'
});
Returns nothing. If I removed the dataType it will return the whole webpage where it's being triggered from.
I do need to make the request as POST since I'll be sending a large amount of data.
Thanks.
Do you have CSRF protection enabled?
So I am a bit lost and hoping you can help me out. I am writing an app in simple PHP/HTML/Javascript app.
My Goal: To POST json data to an API.
How can I go about this? I just can't find any good examples to show me the best way to handle this.
In my request I need to send Basic Authorization as well as the json values.
This is what I have right now
$.ajax({
type: "POST",
url: "host.com/api/comments",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxx"
},
data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
success: function (){
alert('Comment Submitted');
}
});
I can't get the above code to work. Im using a button to call a function that will start the ajax call but nothing is happening.
Any help be be amazing! Thank You.
Use
contentType:"application/json"
You need to use JSON.stringify method to convert it to JSON format when you send it,
And the model binding will bind the json data to your class object.
The below code will work fine (tested)
$(function () {
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
});
If you're writing the API in PHP, and it uses $_POST to get the parameters, you shouldn't send JSON. PHP only knows how to decode multipart/form-data and application/x-www-form-urlencode. If you pass an object to $.ajax, jQuery will use the urlencode format.
Just take the quotes off the object that you're passing to the data: option.
$.ajax({
type: "POST",
url: "host.com/api/comments",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxx"
},
data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
success: function (){
alert('Comment Submitted');
}
});
You also shouldn't use async: false, it is deprecated. Learn to write proper async code.
Nobody seems to have addressed one issue - the URL
If the page this is requested from is http://yourhost.com/path/file.html the request will be sent as http://yourhost.com/path/host.com/api/comments
As you have host.com in the URL, I assumed the request is to a different domain?
use one of
http://host.com/api/comments
https://host.com/api/comments
//host.com/api/comments
will only work if your page is loaded http and not https
will work only if the remote API supports https
will only always work properly if the remote API supports both http and https
The other issue is regarding the format of the sent data
The default content-type for $.ajax POST is application/x-www-form-urlencoded; charset=UTF-8
So, sending a POST request with various combinations of contentType and data shows the following
Firstly, without setting contentType
data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
request is sent as formData '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
request is sent as formdata, the following values:
value1: 2.0
value2: setPowerState
value3[state]: 0
looks better, because there's actually multiple values, not just a string
Now, let's set contentType
contentType: 'json', data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
firefox does not tell me the format of the following string: 'value1=2.0&value2=setPowerState&value3%5Bstate%5D=0' - looks useless
And finally
contentType: 'json', data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
sends the following JSON: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
So, finally, if the API requires JSON request data, and it's actually on a domain called "host.com"
$.ajax({
type: "POST",
url: "//host.com/api/comments",
dataType: 'json',
contentType: 'json', data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
});
I have an ajax POST method that, despite what I am sending to the server, is apparently appending a '↵' character to the value field. My code:
$.ajax({
url: url,
type: "POST",
data: {"name" : "lol"},
dataType : "json",
contentType : "application/json; charset=utf-8"
});
The error returned is error code 400 "Client submitted invalid JSON: lexical error: invalid string in json text.↵" and the console reports that this name=lol↵ is the data being sent.
I just read the error message again and checked with the docs here.
What you need to do is to send your request in JSON format, not as form-data. You specified the right contentType, but you need to convert your data using JSON.stringify
Look at this answer here for a possible solution.
In your case it would be something like this:
$.ajax({
url: url,
type: 'POST',
data: JSON.stringify({
name: 'lol',
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
});
I hope that works for you. If this didn't work either, I would check with the docs at dev.groupme.com. Maybe you have misspelled some of the JSON fields?
Trying to send json. Here's my function:
var object = ... ;
$.ajax({
type: 'POST',
url: '<url>',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: object
});
But whenever I check Chrome, it always sends it as query params:
Request Payload:
startDate=Wed+Dec+19+2012+19%3A00%3A00+GMT-0500+(EST)&endDate=Thu+Dec+20+2012+19%3A00%3A00+GMT-0500+(EST)&
How do I get it to send as JSON?
With JSON.stringify(object)
Sample:
$.ajax({
type: 'POST',
url: '<url>',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(object)
});
Note JSON.stringify is not supported in all browsers (http://caniuse.com/#feat=json ), in particular browsers IE7 and lower.
If you need to support this browsers too you can use this Javascript library: https://github.com/douglascrockford/JSON-js
Stringify using JSON.stringify(object)
Modify the data field to:
...
data: JSON.stringify(object),
...
The way you are doing it, IMO, jQuery sees the parameter as a dictionary (key-value pairs), and constructs a percentile-encoded string from that; and hence you see that output.
I have found it easier to send data in default 'application/x-www-form-urlencoded' format with JSON as a field like this:
$.ajax({
type: 'POST',
url: '<url>',
dataType: 'json',
data: {json:JSON.stringify(object)}
});
On server use the regular method to receive field called json.
Just shared to see if this is valid for you.