I am not an expert in json parsing so please bear with me if i ask simple question.I have a json response like this :
{
"resp": [{
"Key": "123423544235343211421412",
"id": "12"
}]
}
I want to access value of key and id (123423544235343211421412,12)
.I tried following but i can't get the values!
I appreciate if you guys show me how to get those values.Thanks
var postData = {
Name: "Galaxy",
action: "token"
};
$.ajax("https://someapiurl/getit.aspx",{
type : 'POST',
data: JSON.stringify(postData),
contentType: "application/json",
success: function(data) {
var json = JSON.parse(data);
alert(json.resp[0].Key);
alert(json.resp[1].id);
},
contentType: "application/json",
dataType: 'json'
});
You're almost there. jQuery automatically parses the response as JSON for you when you specify dataType: 'json'
$.ajax('https://someapiurl/getit.aspx', {
method: 'POST',
contentType: 'application/json; charset=UTF-8',
dataType: 'json',
data: JSON.stringify(postData)
}).done(function(obj) {
alert(obj.resp[0].Key);
alert(obj.resp[0].id);
})
Related
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 have a JSON object that I'm getting as a response to an AJAX call:
{ "Score": 5, "OS": "Windows 7" }
I want to add it to a div but the following does not work, data.OS or data.Score just return as undefined
$.ajax({
type: "POST",
url: '/details',
data: JSON.stringify(IP),
contentType: 'application/json;charset=UTF-8',
success: function(data) {
$('#OSdetails').append('<div id="details">Operating System: ' + data.OS + '</div>');
}
});
What am I doing wrong?
$.ajax({
dataType: 'JSON', <==== THIS IS MISSING
type: "POST",
url: '/details',
data: JSON.stringify(IP),
contentType: 'application/json;charset=UTF-8',
success: function(data) {
dataType specifies the expected data type and allows for automated conversion
I'm trying to use jQuery and Ajax to send a POST request to my API.
$.ajax({
url: '/api/Orders',
headers: {
contentType: "application/json"
},
type: "POST",
data: JSON.stringify({'description':'test'}),
});
When I'm using postman (chrome extension) the POST request is fine and everything works great.
If I'm trying to use the above code with AJAX the response is:
message:"Request must have "Content-Type: application/json" header"
I find it really weird because I set contentType : "application/json".
Did you have tried to set the property dataType to JSON?
Your code will looks like:
$.ajax({
url: '/api/Orders',
headers: {
contentType: "application/json"
},
type: "POST",
data: JSON.stringify({'description':'test'}),
dataType: "json"
});
After 6 hours i found the correct answer.
$.ajax({
url: 'http://127.0.0.1:5000/api/Orders',
headers: {
accepts: 'application/vnd.api+json'
},
contentType: "application/json",
type : 'post',
data: JSON.stringify({
'description' : 'test'
}),
dataType: "json",
success: function(data) {
console.log(data);
}
});
First of all. I read many questions about this problem here in stackoverflow but nothing helps me.
I've this function:
function ip_login(){
//alert(JSON.stringify(arr_login));
$.ajax({
crossdomain: true,
url: 'https://****/Token',
type: 'POST',
data: JSON.stringify(arr_login),
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
}
And this is my JSON string:
{"grant_type":"password","username":"mail#mail.de","password":"blabla"}
With the google chrome extension 'postman' it works fine!
If I test my code above I got the popular 400 bad request message.
When I take the code of the extension 'postman' it doesn't work too.
This is the code of postman:
var settings = {
"async": true,
"crossDomain": true,
"url": "https://*****/Token",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded"
},
"data": {
"grant_type": "password",
"username": "mail#mail.de",
"password": "blabla"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
I can't fine my issue..
I searched on Google and SO but no reply helped me.
Edit:
This is in my console:
"NetworkError: 400 Bad Request - https://awesome-url.de/Token"
The problem is in stringifiing JSON. Server expects json but you send string(stringified JSON). Try
function ip_login(){
//alert(JSON.stringify(arr_login));
$.ajax({
crossdomain: true,
url: 'https://****/Token',
type: 'POST',
data: arr_login,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
success: function (data) {
console.log(data);
}
});
}
Not sure if this helps, but try anyways.
When I'm sending Json, I didn't use "JSON.stringify(arr_login)"
All I did was something like "data:{arr_login:arr_login}"
This is how my variable looks like.
var req = new Object();
req["type"] = 'refresh';
req["time"] = window.page_ordertime;
This is how my ajax looks like
$.ajax( {
url:"listorder_process.php",
method: "POST",
dataType:"json",
data:{request:req}
} )
This is in my default.aspx
$.ajax({
url: "Default.aspx/Myfunction",
dataType: "json",
type: "POST",
data: {someParameter: "some value"},
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
error: function (d) {
alert("error");
}
});
And this is in my codebehind:
[WebMethod]
public static string Myfunction(string someParameter)
{
return "hello";
}
It keeps going to the error. I see that if I send the Ajax request with null for data and no parameters on the function I get the data "hello" out. So there is some issue in how I send the data, but it is unclear what
Put your parameters in quotes
$.ajax({
url: "Default.aspx/Myfunction",
dataType: "json",
type: "POST",
data: {'someParameter': 'some value'},
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
error: function (d) {
alert("error");
}
});
Data object must be a single string.
data: JSON.stringify({someParameter: "some value"})
Change this line:
data: {someParameter: "some value"},
to:
data: {"someParameter": "some value"},
JSON object properties needs to be enclosed with quotes.
Here is how I do the same thing:
$.ajax({
type: "POST",
dataType: "json",
url: "RouteService.asmx/getRouteData",
data: { techID: techID, jobID: jobID },
success: function(msg) {
processRouteData(msg);
}
Try removing this line:
contentType: "application/json; charset=utf-8",