How to access JSON objects in AJAX with jQuery? - javascript

I'am doing a jquery call to API website, which returns me the results in JSON format:
{
"results":[
{
"user":{
"gender":"female",
"name":{
"title":"mrs",
"first":"linda",
"last":"diaz"
},
"location":{
"street":"2333 oak lawn ave",
"city":"red bluff",
"state":"maryland",
"zip":"49309"
},
"email":"linda.diaz55#example.com",
"password":"blackman",
"md5_hash":"3c64b82d048c8754a30e292a1359fa39",
"sha1_hash":"d5095cf146dda75865d348f4ce4820b11b58b9fd",
"phone":"(880)-878-1658",
"cell":"(183)-179-1598",
"SSN":"425-55-1070",
"picture":"http:\/\/api.randomuser.me\/0.2\/portraits\/women\/8.jpg"
},
"seed":"2d589586d34c1c5",
"version":"0.2.1"
}
]
}
How can I access (or get values of) the items, for example: I want to console.log() the first name and the last name, get a phone number ?
Using a .(dot) not working for me, maybe i'am doing something wrong ?
Here is a javascript code
$.ajax({
type: 'POST',
url: url + resultsQuery,
dataType: 'json',
success: function(data){
console.log(data);
}
});

data.results[0].user.name.first
data.results[0].user.name.last
data.results[0].user.phone

For your JSON Structure, try
data.results[0].user.name.first
data.results[0].user.name.last //etc

Related

jQuery won't correctly POST a JSON containing an array as one of its properties

I'm trying to use jQuery to send a JSON object, which has an array as one of its properties, to my API endpoint. I've defined it like this:
let bidding = {
"name": $("#name").val(),
"applicant": $("#applicant").val(),
"start_date": $("#start_date").val(),
"end_date": $("#end_date").val(),
"products": []
}
$("#products").children(".dropdown").each(function(key, value) {
bidding.products.push(
{
"product_name": $(value).children(".btn").text(),
"quantity": $(value).children("input").val()
}
);
});
And when I do a console.log(JSON.stringfy(bidding)) it parses just as expected, for example:
{
"name":"Material de Construção",
"applicant":"Prefeitura",
"start_date":"26/09/2017",
"end_date":"01/10/2017",
"products":[
{"product_name":"Cimento (5kg)","quantity":"200"},
{"product_name":"Tijolo","quantity":"100"},
{"product_name":"Caneta","quantity":"5"}
]
}
But when I POST it using $.post("/api", bidding); my API receives it like this:
{
name: 'Material de Construção',
applicant: 'Prefeitura',
start_date: '26/09/2017',
end_date: '01/10/2017',
'products[0][product_name]': 'Cimento (5kg)',
'products[0][quantity]': '200',
'products[1][product_name]': 'Tijolo',
'products[1][quantity]': '100',
'products[2][product_name]': 'Caneta',
'products[2][quantity]': '5'
}
How can I make it so jQuery will stop creating new properties for each entry in the array and instead send the entire array as a single property?
You need to set to false:
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.
Hence your post will be:
$.ajax({
type: "POST",
url: "/api",
data: JSON.stringify(bidding),
processData: false,
contentType: "application/json",
dataType:"json",
success: function () {
}
});
$.post("/api", JSON.stringify(bidding));
And in the server side decode the json. If you are using php use json_decode
Using json is always a good idea to preserve the data structure

Can't get Data from json object

I have this script:
<script type="text/javascript">
function requestimg(username){
$.ajax({
url: '{% url "image" %}',
data: {
'username': username
},
dataType: 'json',
success: function (data) {
if (data) {
//Printing the whole data
console.log(data);
//Printing to see where I am
console.log("Name: ");
//Trying to rint the name
console.log(data[0].nombre);
}else {
alert("May Day");
}
}
});
}
I have a problem reading the properties in the json object
When i print the data I get this:
{
json: "[
{
"model": "polls.imagen",
"pk": 17,
"fields": {
"n…"36",
"imagen": "polls/static/pictures/dr.jpg"
}
}
]"
}
And when i print the data as I have it on the code i get:
Uncaught TypeError: Cannot read property 'nombre' of undefined
I have tryied writing it like data.nombre but i just get undefined
I have also tried this console.log(data[0].fields); , data[0].model, data.model
IMPORTANT I want to clarify that i wont know why there are 2 json objects im supposed to get just one and even if i try to put a [1] instead of the [0] i get the same mistakes.
I've tried answers from some previous similar questions and they didn't help.
You will be able to access the fields per
data.json[0].fields
the response of your url is an array, named json
Additionally data.json is returning a string, so convert it to JSON with
data.json = JSON.parse(data.json);
Convert it to JSON first JSON.parse(data.json)
This will give you the access to the fields object data.json[0].fields

Rails nested attributes passing with jQuery

I have the following definition:
params.require(:sets).permit(:name, zones_attributes: [:latitude, :longitude])
And i would like to send them by ajax with jQuery, thing is I think i'm constructing it wrong because I keep getting this error:
Unpermitted parameters: 0, 1
This is what I'm sending:
{
"sets"=>{
"name"=>"America",
"zones_attributes"=>{
"0"=>[
"49.95121990866204",
"-117.861328125"
],
"1"=>[
"-33.578014746143985",
"-55.986328125"
]
}
},
"action"=>"create",
"controller"=>"sets"
}
I think the problem is the "key" value being added before the latitude/longitude value.
This is how I'm adding those values:
this.zones.push([marker.position.lat(), marker.position.lng()]);
Is there a way to add them without the keys? Or am I going through the wrong way?
UPDATE
ajax code:
$.ajax({
type: "POST",
url: '/zone_sets',
data: { zone_sets: { name: map.markerListName ,zones_attributes: map.zones } },
success: function (data) { $("input[name=zone_set]").append(data) },
});
Change your current ajax code to:
$.ajax({
type: "POST",
dataType: 'json',
headers: {
'Content-Type': 'application/json'
},
url: '/zone_sets',
data: JSON.stringify({ zone_sets: { name: map.markerListName ,zones_attributes: map.zones } }),
success: function (data) { $("input[name=zone_set]").append(data) },
});
As you can see the actual problem is how the Rails handle and parse a request.
You should be adding them like this:
this.zones.push({'latitude': marker.position.lat(), 'longitude': marker.position.lng()});
Yes, the "key" looks like it's the problem.
params.require(:sets).permit(:name, zones_attributes: [:latitude, :longitude]) is expecting your request to be in the format:
{
"sets"=>{
"name"=>"America",
"zones_attributes"=>[
{
"latitude": "49.95121990866204",
"longitude": "-117.861328125"
},
{
"latitude": "-33.578014746143985",
"longitude": "-55.986328125"
}
]
},
"action"=>"create",
"controller"=>"sets"
}
i.e. the "0" and "1" the error is referring to are like array indices.

Scraping JSON data from an AJAX request

I have a PHP function that echoes out JSON data and pagination links. The data looks exactly like this.
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
Previous
Next
To get these data, I would use jQuery.ajax() function. My code are as follow:-
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: "page="+page,
success: function(msg)
{
$("#area").ajaxComplete(function(event, request, settings)
{
$("#area").html(msg);
});
}
});
}
Using jQuery, is there anyway I can scrape the data returned from the AJAX request and use the JSON data? Or is there a better way of doing this? I'm just experimenting and would like to paginate JSON data.
It's better to not invent your own formats (like adding HTML links after JSON) for such things. JSON is already capable of holding any structure you need. For example you may use the following form:
{
"data": [
{"name": "John Doe", "favourite": "cupcakes"},
{"name": "Jane Citizen", "favourite": "Baked beans"}
],
"pagination": {
"prev": "previous page URL",
"next": "next page URL"
}
}
On client-side it can be parsed very easily:
$.ajax({
url: "URL",
dataType:'json',
success: function(resp) {
// use resp.data and resp.pagination here
}
});
Instead of scraping the JSON data i'd suggest you to return pure JSON data. As per your use case I don't think its necessary to write the Previous and Next. I am guessing that the first object in your return url is for Previous and the next one is for Next. Simply return the below string...
[{"name":"John Doe","favourite":"cupcakes"},{"name":"Jane Citizen","favourite":"Baked beans"}]
and read it as under.
function loadData(page){
$.ajax
({
type: "POST",
url: "http://sandbox.dev/favourite/test",
dataType:'json',
success: function(msg)
{
var previous = msg[0]; //This will give u your previous object and
var next = msg[1]; //this will give you your next object
//You can use prev and next here.
//$("#area").ajaxComplete(function(event, request, settings)
//{
// $("#area").html(msg);
//});
}
});
}
This way return only that data that's going to change not the entire html.
put a dataType to your ajax request to receive a json object or you will receive a string.
if you put "previous" and "next" in your json..that will be invalid.
function loadData(page){
$.ajax({
type: "POST",
url: "http://sandbox.dev/favourite/test",
data: {'page':page},
dataType:'json',
success: function(msg){
if(typeof (msg) == 'object'){
// do something...
}else{
alert('invalid json');
}
},
complete:function(){
//do something
}
});
}
and .. in your php file, put a header
header("Content-type:application/json");
// print your json..
To see your json object... use console.log , like this:
// your ajax....
success:(msg){
if( window.console ) console.dir( typeof(msg), msg);
}
Change your json to something like this: (Use jsonlint to validate it - http://jsonlint.com/)
{
"paginate": {
"previous": "http...previsouslink",
"next": "http...nextlink"
},
"data": [
{
"name": "JohnDoe",
"favourite": "cupcakes"
},
{
"name": "JaneCitizen",
"favourite": "Bakedbeans"
}
]
}
You can try this :-
var jsObject = JSON.parse(your_data);
data = JSON.parse(gvalues);
var result = data.key;
var result1 = data.values[0];

Parsing JSON array in JQuery

I'm trying to get the hand on JQuery and JSON using an ASP.NET webservice. The Webservice returns this result:
{
MyResult: {
Ticket: {
"Author": "rd",
"CssClass": "RED",
"ExpirationDateTime": "2009-08-16T16:55:43.577+02:00",
"id": "38",
"Message": "We are going down",
"ModifiedDateTime": "2009-08-17T11:14:20.5+02:00",
"MoreInfo": null
}
}
}
On the client side I'm using JQuery to get the result using the ajax function like this:
$.ajax({
type: "POST",
url: "TickerFeeder.asmx/GetTicket",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(resultJSON) {
//-- Please fill your code here for getting the first item from the array into variables
}
But I'm missing out the stuff how to retrieve the first item from the JSON array into some variables. Something like this (pseudo-code):
var message = resultJSON[0].Message
var cssclass = resultJSON[0].CssClass
Anybody with a hint,help?
Thanks for your help
Cheers
Frank
Your JSON is not valid, you should use quotes on the MyResult and Ticket members.
{
"MyResult": {
"Ticket": {
"Author": "rd",
"CssClass": "RED",
"ExpirationDateTime": "2009-08-16T16:55:43.577+02:00",
"id": "38",
"Message": "We are going down",
"ModifiedDateTime": "2009-08-17T11:14:20.5+02:00",
"MoreInfo": null
}
}
}
Also there is no array involved, the arrays are defined with the square bracket characters [....] literal notation, so you can access your values directly:
resultJSON.MyResult.Ticket.Message;
resultJSON.MyResult.Ticket.CssClass;
Ok, found out that my Asp.Net webService was producing a wrong result set. So instead of returning a string item I returned a complete object and handled the Json conversion to Asp.Net webservice. That did the trick !

Categories