My JSON:
{
"operatorname": "LUKUP",
"Schedule": {
"channel": [
{
"bouquet": "Music",
"channelgenre": "English Music",
"prepaid_price": 15
},
{
"bouquet": "News",
"channelgenre": "English News",
"prepaid_price": 7
}
]
}
}
Ajax call:
$.ajax({
type: "POST",
url: my_url,
async: false,
success: function(result){
alert(JSON.stringify(result));
message= JSON.parse(result);
alert(message.Schedule.channel.length);
}
});
My json is coming. First alert message is giving my JSON. When i parse that json, error is coming like
Uncaught SyntaxError: Unexpected token o
Location: jquery.min.js.2
I tried solving this issue. Couldnt able to figure out where it is going wrong.
Can anyone help me
Remove the comas after "prepaid_price": 15 and "prepaid_price": 7. You are also missing a closing } at the end of your JSON.
You can validate your JSON here: http://www.jsoneditoronline.org/
{
"operatorname": "LUKUP",
"Schedule": {
"channel": [
{
"bouquet": "Music",
"channelgenre": "English Music",
"prepaid_price": 15
},
{
"bouquet": "News",
"channelgenre": "English News",
"prepaid_price": 7
}
]
}
}
You can use dataType: 'json', in your AJAX-call, then your JSON will be parsed automatically and you don't need to call message = JSON.parse(result); because your result will be already an Object.
Then you can call alert(result.Schedule.channel.length); direct.
Your code would look like:
$.ajax({
type: "POST",
url: my_url,
async: false,
dataType: 'json',
success: function(result){
alert(result.Schedule.channel.length);
}
});
Related
I have an application that on click of a button, it makes an ajax post request to a flask backend(flask restless). As mentioned, I get an error with the message "Request must have 'Content-Type:application/vnd.api+json'", even though I have that same statement as part of my header.
Pointer, the post request gets posted successfully on the postman.
$(function() {
$('#add_details').on('click', function() {
$.ajax({
type: 'POST',
url: 'http://127.0.0.1:5000/api/v1/user',
data: {
"data": {
"type": "user",
"attributes": {
"first_name": "first",
"last_name": "second",
"email_address": "user43#gmal.acbde",
"phone_number": "4202024234",
"gender": "FEMALE"
}
}
},
headers: {
Accepts: 'application/vnd.api+json',
ContentType: 'application/vnd.api+json',
},
dataType: "json",
success: function(newUser) {
console.log('success', newUser)
},
error: function() {
alert('error encounted while adding user');
}
});
});
});
headers: {
Accepts: 'application/vnd.api+json',
ContentType: 'application/vnd.api+json',
},
I noticed an extra comma at the end of ContentType. Have you tired removing that?
Im trying to access to parameter value from response.
$.ajax({
type: "POST",
url: "",
dataType: 'text',
async: false,
headers: {
"Authorization": "Basic " + btoa(username + ":" + password)
},
data: '{ "action" : "create", "resource" : {"name" : "teddssssssssddsssdsddddsdddwdsdssdsddi", "description": "Test Tenant Description","parent": {"href": "localhost"}}}',
success: function(as) {
alert(as[0][0]["id"]);
}
});
in the success area i got the response, in json. I want to access to the id value, but i cant. always says undefined, i tried different options.
this is the response format.
{
"results": [
{
"href": "localhost/1111111",
"id": "100000000111",
"name": "test",
"ancestry": "1000011111",
"divisible": true,
"description": "Test Tenant Description",
"use_config_for_attributes": false,
"default_miq_group_id": "10021200000173"
}
]
}
I dont know if i can access direct to the parameter or better get the response as text and split.
The response has a different structure.
Your response is an object with one property and value is an array of objects.
something like {'results': [...{}]}
Key 0 does not exist.
const data = {"results":[{"href":"localhost/1111111","id":"100000000111","name":"test","ancestry":"1000011111","divisible":true,"description":"Test Tenant Description","use_config_for_attributes":false,"default_miq_group_id":"10021200000173"}]};
console.log(data.results[0].id);
This question already has answers here:
Jquery - How to make $.post() use contentType=application/json?
(17 answers)
Closed 6 years ago.
I tried in 2 ways:
saving the json on a var
var dataLog = JSON.stringify( {
"clientId": "1",
"sensor": "Temp",
"dateStart": "2016-09-03 00:00:00",
"dateEnd": "2016-09-03 00:59:59"
} );
$.post(data , {dataLog})
.done(function( data ) {
console.table(data);
});
and adding the same json directly into the data parameter
$.post( url, {
"clientId": "1",
"sensor": "Temp",
"dateStart": "2016-09-03 00:00:00",
"dateEnd": "2016-09-03 00:59:59"
})
.done(function( data ) {
console.log(data);
});
but none of the 2 options works, it is possible or im doing something wrong?
here one example
var promise = $.ajax({
url: url,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: dataLog
});
I have this code which spits out all the content for the first post only. I would like it to spit out the first image from all posts.
$.ajax({url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function(results){
console.log(results);
var postBody = results.response.posts[0].body;
$(".x").html(postBody);
}});
And this is a ajax response:
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"blog": { ... },
"posts": [
{
"blog_name": "citriccomics",
"id": 3507845453,
"post_url": "http:\/\/citriccomics.tumblr.com\/post\/3507845453",
"type": "text",
"date": "2011-02-25 20:27:00 GMT",
"timestamp": 1298665620,
"state": "published",
"format": "html",
"reblog_key": "b0baQtsl",
"tags": [
"tumblrize",
"milky dog",
"mini comic"
],
"note_count": 14,
"title": "Milky Dog",
"body": "<p><img src=\"http:\/\/media.tumblr.com\
/tumblr_lh6x8d7LBB1qa6gy3.jpg\"\/><a href=\"http:\/\
/citriccomics.com\/blog\/?p=487\" target=\"_blank\">TO READ
THE REST CLICK HERE<\/a><br\/>\n\nMilky Dog was inspired by
something <a href=\"http:\/\/gunadie.com\/naomi\"
target=\"_blank\">Naomi Gee<\/a> wrote on twitter, I really
liked the hash tag <a href=\"http:\/\/twitter.com\/
search?q=%23MILKYDOG\" target=\"_blank\">#milkydog<\/a>
and quickly came up with a little comic about it. You can
(and should) follow Naomi on twitter <a href=\"http:\/\
/twitter.com\/ngun\" target=\"_blank\">#ngun<\/a> I'm on
twitter as well <a href=\"http:\/\/twitter.com\
/weflewairplanes\"target=\"_blank\">#weflewairplanes<\/a>
<\/p>\n\nAlso, if you’re a Reddit user (or even if
you're not) I submitted this there, if you could up vote
it I'd be super grateful just <a href=\"http:\/\
/tinyurl.com\/5wj3tqz\" target=\"_blank\">CLICK HERE<\/a>"
},
...
],
"total_posts": 3
}
}
As you can see, images in the body are wrapped with tags.
How i get the images?
Using jQuery, see the sample code:
$(results.response.posts[0].body).find('img').first();
It is probably not the best alternative, but it should do.
If you wanna do it for multiple posts use array of images:
var img = new Array();
$.each(results.response.posts, function (ix,el){
img.push($(el.body).find('img').first());
})
try this:
$.ajax({url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function(results){
console.log(results);
var postBody = results.response.posts[0].body;
var html = $(postBody);
var firstImage = $(postBody).find("img:first");
}});
var $ct = $('.x');
$.ajax({
url: "http://api.tumblr.com/v2/blog/sjtest1.tumblr.com/posts?api_key=mykey",
dataType: 'jsonp',
success: function (results) {
console.log(results);
$.each(results.response.posts, function (_, post) {
$(post.body).find('img:first').appendTo($ct)
})
}
});
I am trying to make a cross domain request to send/recieve some data. I can't get past the object error. Before I was getting the No Transport Error but adding Query.support.cors = true; solved this issue.
var url = "http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract";
$.ajax({
type: 'GET',
url: url,
data: 'tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation',
datatype: "jsonp",
contentType: "application/json",
success: function (response) {
alert(response.data);
},
error: function (error) {
alert(error.statusText);
}
});
If I type the url out in a browser:
http://CROSSDOMAINSERVER:PORT/Service1.svc/GetDataUsingDataContract?&tool=1&product=Some%20Product&details=9&bogus=should%20not%20pass%20validation
I get the correct response.
{"d":{"__type":"ClientSideData:#ProdResourceToolService","details":"9","product":"Some Product","result":"1","site":"Somewhere, SD","systime":"2\/6\/2013 2:50:20 PM","team":"0000000000","tool":"1","user":"username"}}
When I use ajax it does not submit it to the database or return data, just object error. Does anyone have any suggestions on how to get around this?
I should also specify if I remove http://CROSSDOMAINSERVER:PORT/ from var url when debugging locally I get the correct json response. Why does cross domain not work?
This is your current response:
{
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
}
This is a valid JSON string. However, its not valid JSONP. If possible, make your service wrap the json in a function:
responseFunc({
"d": {
"__type": "ClientSideData:#ProdResourceToolService",
"details": "9",
"product": "Some Product",
"result": "1",
"site": "Somewhere, SD",
"systime": "2/6/2013 2:50:20 PM",
"team": "0000000000",
"tool": "1",
"user": "username"
}
});
And in your $.ajax() call, add a property: jsonpCallback: 'responseFunc'.
Also, I would suggest passing the data as an object:
data: { tool: 1, product: 'Some Product' } //etc...
If you can access the service from the serverside without any issues you could create a httphandler (.ashx for example) and let it generate the JSON for you. Then you wouldn't have to deal with the cross domain issues on the client side.