AJAX post data is not recognized - javascript

I have a made an AJAX request.
Here is its setting:
$.ajax({
data : { id : 25 },
dataType : 'json',
contentType : 'application/json; charset=utf-8',
type : 'POST',
// the rest of the setting
});
And here is the server side:
header("contentType=application/json");
// and then the rest of the request
Everything works. Data is returned through JSON and no problem. But the $_POST is not filled with any data, though when I check the ajax request log through firebug I see that it sends the id...what could be the problem? The problem exists when I set the contentType header and dataType...
I also have set Allow Origin header but the problem is not solved...
I also have checked the data with $_POST and $_REQUEST
I use LARAVEL framework...

The default method type for jQuery's ajax method is GET. Try to set the method type to POST in your settings, like this:
$.ajax({
type: 'POST', // <<<<
data : { id : 25 },
dataType : 'json',
contentType : 'application/json; charset=utf-8',
// the rest of the setting
});
For more information about ajax method, please refer here.
Update
I think it would be better not to specify the contentType. The official documentation says:
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.

you should check with $_GET to see if the data is there.
if you are not explicitly defining any method by which to send the data, then by default the GET method is used.
either set the method as POST or retrieve the data through $_GET to see if it is there.

add type in ajax
$.ajax({
data : { id : 25 },
dataType : 'json',
type :'POST'
contentType : 'application/json; charset=utf-8',
// the rest of the setting
})

Your are not passing type so it is a Get Request by default, check in $_GET[] or add type POST in the ajax call.

you miss to declare type POST use as following way
$.ajax({
data : { id : 25 },
dataType : 'json',
type :'POST',
contentType : 'application/json; charset=utf-8',
// the rest of the setting
});

Related

jQuery - Ajax POST request converted to GET request

I am trying to POST json data via ajax. The json data contains a large html table. However, this POST request is converted to GET request and I get Error 414 (Request-URI too long). I know jsonp POST requests are converted to GET, but why my json request is converted to GET?
$.ajax({
url: 'api.php',
method: 'POST',
data: {
'call': 'emailSalesReportToAdmin',
'tableHtml': $('#tblSalesReport').parent().html()
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
});
Yes , for older version, please use type:'POST' instead of method:'POST'
As mentioned on jQuery documentation
type (default: 'GET') Type: String An alias for method. You should use
type if you're using versions of jQuery prior to 1.9.0.
I found the issue and it was an older version of jQuery. The above code worked fine in jQuery version 1.12.

Javascript POST to API

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}}',
});

Sending form JSON data to server via AJAX

I want to manually send my form data in JSON format to the server.
I changed my form data to a JSON fomat below.
The data I have in my clients-side javascript is in JSON (ie{"firstname":"john","lastname":"smith"}
$.ajax({
type: 'POST',
url: "http://localhost:3000/UserRegistration",
dataType: 'application/json',
data: JSONData,
success: function(data) {
}
});
I am using body-parser and in my server.js code, I do console.log(req.body) but the data is shown in this format
{ '{"firstname":"john","lastname":"smith"}': '' }
It added more curly braces. Why is that? How can i access the data in the server side
You can just serialize the form and bodyparser will parse it into json for you.
$.post('http://localhost:3000/UserRegistration', form.serialize(), function(data) {
...
});
dataType: 'application/json' will expect json response from server
Set processData : false and contentType : 'application/json'[Ref]
processData: By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false
contentType: When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent)
Please directly parsed your object to json. for example: JSON.Stringfy(obj)

Is explicitly setting the contentType for jQuery ajax necessary when posting JSON?

$.ajax({
url: Settings.get('serverURL') + 'PlaylistItem/CreateMultiple',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(newItems)
});
I'm explicitly setting the contentType of the AJAX request to indicate JSON is being sent across the wire. However, I seem to be inconsistent in my application of contentType across my code and all AJAX requests are working properly.
Is it necessary or beneficial to be explicit with the JSON contentType or should I omit it?
According to the JQuery documentation
contentType (default: 'application/x-www-form-urlencoded;
charset=UTF-8') Type: String When sending data to the server, use this
content type. Default is "application/x-www-form-urlencoded;
charset=UTF-8", which is fine for most cases. If you explicitly pass
in a content-type to $.ajax(), then it is always sent to the server
(even if no data is sent). The W3C XMLHttpRequest specification
dictates that the charset is always UTF-8; specifying another charset
will not force the browser to change the encoding.
In practice I have found it beneficial to explicitly state it either in $.ajax or through
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});
as application/x-www-form-urlencoded has caused me the occasional null value in MVC action parameters as per this article
http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx/

Setting the POST-body to a JSON object with jQuery

I'm trying to write a JSON-based web API in a Sinatra app. I want to POST a JSON object as the post body (with the proper content-type set) but I'm struggling.
In Cocoa, I'd do something like
[mutableHTTPRequest setHTTPBody:dataRepresentationOfJSONObject];
And the content type, set to JSON, would then post the HTTP body as a JSON object. I'm trying to do this with jquery. The best I can do so far just takes the JSON object and turns it into a normal style key=value&… style post body, and that's not what I'm after.
My Javascript:
var data = { "user" : "me!" };
$.ajax({
type: "POST",
url: "/api/user/create",
contentType: 'application/json',
data: data,
success: function(r) {
});
Any pointers on how to do this? My goal is for my Sinatra to do like the following
post "/api/user/create" do
js = JSON.parse(request.body.read)
# do something with the js object… this works when POSTing from Cocoa
end
Add the processData parameter to your ajax request and set it to false. Additionally, you need to stringify your object to turn it into JSON.
var data = { "user" : "me!" };
$.ajax({
type: "POST",
url: "/api/user/create",
processData: false,
contentType: 'application/json',
data: JSON.stringify(data),
success: function(r) {
}
});
JSON.stringify will not work in older versions of IE unless you implement it. http://json.org

Categories