I try to send list of object like [{"name":"Vasya"},{"name":"Lila"}]
It's my code:
$.ajax({
url: url
, type: 'POST'
, contentType: 'application/json'
, data: data
, success: function(response) {
showPopup(response.successMessage);
}
});
Where alert(JSON.stringify(data)); shows: [{"name":"Vasya"},{"name":"Lila"}]
But when I am checking my request in chrome debug mode the request contains undefined= instead correct data.
What I do wrong? Is this syntax incorrect according to JSON?
You need to stringify the object when sending it so that you send JSON.
, data: JSON.stringify(data)
Related
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?
How can I convert the output of drp.getDateRange to an array so that I can post it via AJAX?
I have updated this code to represent the advice given below
<script>
var drp;
var myArray = [];
function makedatepicker() {
drp = $("#myDate").datepicker({});
}
function getRange() {
var data = $("#myOutput").serialize();
console.log("This is the serialized element");
console.dir(data);
$.ajax({
url: "myurl.com",
type: 'post',
data: data,
success: function(response) {
console.log("This is the response from your ajax script");
console.dir(response);
}
});
}
$(document).ready(function () {
makedatepicker();
});
</script>
Update
Note on JSON. The default encoding will be url form encoded. If you want the request to send the data as JSON, you will need to add..
content-type: "application/json; charset=utf-8",
also if you are returning JSON, you should add ...
datatype : "json",
Not sure which scripting language your using on the back end, but if PHP, you can send back array data like this
echo json_encode($myArray);
I will add the JSON stuff to the sample code below.
End Update
If you use .serialize() you an send it as ajax data and it will show up in your post or get array.
If you are working with an array, you might want to use .serializeArray()
You can view an object or array in your developer tools (F12 in Chrome or FF), by using console.dir(someObject);
var data = $("#myOutput").serialize();
console.log("This is the serialized element");
console.dir(data);
$.ajax({
url: "myurl.com",
type: 'post',
datatype : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
beforeSend : function (){
console.log("Before Send: Data looks like..");
console.dir(data);
},
success: function(response) {
console.log("This is the response from your ajax script");
console.dir(response);
console.log("parsing JSON ...");
console.dir($.parseJSON(response));
}
});
Chrome Developer Tools Console, this is where you will see anything that you console.log or console.dir
You can check the JSON that is being sent by clicking the Network tab. Then click the name of the ajax script and it will show you the data being sent. (Also, clicking on the "response" tab will show you what is being sent back by your script.)
In the example below I am sending an ajax request using the above code and it is showing that the data is indeed a JSON object.
I have a mobile application and I have a lot of data that I am putting in to a JSON object to store in localStorage. I need to get this data to PHP to process it. I have chosen to use jQuery.ajax to send the data as a JSON object to PHP. However, when I run the function, it gives a success message, but does not go to the url specified. I have a lot of PHP experience but this is my first JS intensive project.
Here is my JS code:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
ATRdataJSON is a JSON object that has several JSON objects nested inside.
The URL may not be pointing where you think it's pointing. Try:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "/email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
i'm afraid you cannot send the json object without stringifying it, it may be sent but as a string [object] try to check it first then you may make sure of the url is absolute to make sure it goes to the right controller.
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