Iterating over the data received from ajax / json - javascript

Below is the type of data I am getting via ajax.
[{"model": "blogapp.articles", "pk": 1, "fields": {"title": "Rainbow Buildings in Tokyo", "slug": "Rainbow-Buildings-in-Tokyo"}}, {"model": "blogapp.articles", "pk": 2, "fields": {"title": "4 Cool Cube Facades", "slug": "4-Cool-Cube-Facades"}}]
How can I iterate over this data using .each to get the title and the slug for each entry?
The below code gives me a syntax error on the data.
app.js
$(document).ready(function () {
$(".tag-nav-links").on("click", function (e) {
e.stopPropagation();
return $.ajax({
type: "POST",
url: "",
dataType: "json",
data: { filter: `${e.target.textContent}` },
success: function (data) {
var html = "";
$(data).each(function (index, value) {
html += "<h4>{{" + value.title + "}}</h4>";
});
$("trial").append(html);
},
});
});
});

The jQuery function (which you're using like this: $(data)) isn't what you want there. (You may have meant $.each(data, ...), but these days there's no need.) If data really is an array as shown, just use map on it, then join the result together with a blank string:
success: function (data) {
$("trial").append(data.map(value => {
return "<h4>{{" + value.fields.title + "]]</h4>";
}).join(""));
},
If data is really as shown in the screenshot, then it's an object with a data property containing a string of JSON. That's probably a misconfiguration or coding error on the server, current it's returning text something like this:
{"data":"[{\"model\": \"blogapp.articles\", \"pk\": 1,...
when it should be returning something like this:
{"data":[{"model":"blogapp.articles","pk":1,...
Something is pre-stringifying the data before passing it to whatever wraps it in the {"data": ___} wrapper, stringifies it, and returns it.
Until/unless you fix it, you'll have to parse it twice. jQuery is doing one of those for you, but you'll have to do the second one, after which you should be able to use the array:
// Until/unless the server is fixed
success: function (data) {
data = JSON.parse(data.data); // *** Second parse
$("trial").append(data.map(value => {
return "<h4>{{" + value.fields.title + "]]</h4>";
}).join(""));
},
If you fix the server so it's not double-stringifying, you'd use data.data instead (since data is your parameter name, and it refers to an object with a data property that has the array you want to use):
// After the server is fixed
success: function (data) {
$("trial").append(data.data.map(value => {
// ^^^^^^^^^
return "<h4>{{" + value.fields.title + "]]</h4>";
}).join(""));
},

Related

Use form naming to reach json data in Javascript/jQuery?

I have the following input name: dynamic[elements][1][slider][image1]
When performing an ajax call, a json response with settings and its value is returned.
$.ajax({
url: '/get/settings',
type: 'POST',
data: formData,
async: false,
success: function (data) {
});
How can i get the value of dynamic[elements][1][slider][image1] the easiest way? It works to get the value like this:
data.dynamic.elements[1].slider.image1
So:
$.ajax({
url: '/get/settings',
type: 'POST',
data: formData,
async: false,
success: function (data) {
console.log(data.dynamic.elements[1].slider.image1);
});
But isn't their any better way of getting the value? The only identifier I have to get the value, is the name of the input field which is dynamic[elements][1][slider][image1]. So i would need to extract this string and put it together as data.dynamic.elements[1].slider.image1 to then make it a dynamic variable somehow (to finally get the value)?
Example ajax response:
{
"success": 1,
"dynamic": {
"elements": [
{
"title": {
"title": "Our beautiful topic"
}
},
{
"slider": {
"image1": "5zw3ucypzp3qham.png",
"image1_link": "hellor"
}
}
]
}
}
You may choose to write a generic function for the purpose of retrieving data from object. The function should look something like below. Though the function may not be foolproof but should be enough for proof-of-concept.
function getObjectData(target, path) {
// if the path is not in dot notation first convert
if (path.indexOf(".") == -1)
path = path.replace(/\[/g, ".").replace(/\]/g, "");
var parts = path.split(".");
return parts.reduce(function (acc, currentVal) {
return acc ? (acc[currentVal] || undefined) : acc;
}, target);
}
//usage
getObjectData(data, "dynamic.elements.0.slider.image1"); //undefined
getObjectData(data, "dynamic.elements.1.slider.image1"); //5zw3ucypzp3qham.png
getObjectData(data, "dynamic[elements][1][slider][image1]"); //5zw3ucypzp3qham.png
Hope this helps.

Results From A JSON Call to Variable

I am trying to get a ID from a JSON call, and not sure what the issue is. I have a Callback function set up to set a global variable as such.
GOAL: Make a call to a DB, get the ID from the results returning.
STEP 1 - Make call to JSON and Parse Results
callAjaxGet(<set url>,function(myReturn){
var noteID = ''
$.each(myReturn.results, function(i, note){
noteID = JSON.parse(note.id);
});
})
STEP 2 - JSON/Callback Function
function callAjaxGet(url, callBack){
$.ajax({
url: url,
type: 'GET',
timeout: 10000,
success: function(data,textStatus,xhr){
return callBack(xhr);
},
error: function(xhr, status, error){
console.log(xhr.responseText);
}
});
}
STEP 3 - The Returning JSON
{
"next": "http://selleck.beta.org/playlist/notes/?limit=20&offset=20&play=437",
"previous": null,
"results": [
{
"id": 258,
"url": "/playlist/notes/258/",
"content": "testing",
"play": 437
}
]
}
No matter what I'm doing, the noteID comes back without value. I've looked in Google Development Tools, XHR, and can see the JSON coming back, so thinking I've misunderstood something.
Thank you for any thoughts and suggestions
Steve
Figured it out. Two things were wrong.
Was using XHR instead of Data
Wasn't parsing the JSON properly, the ID is in an array, so had to set the first entry, so
noteID = myReturn.results[0].id;
Thanks A.Sharma and ron tornambe for the pointer on the XHR error
Steve

How to display returned JSON from a jQuery

How to get display return values from the JSON values.I need to get value the user id
$('User_id').observe('blur', function(e) {
var txt = $('User_id').value;
jQuery.ajax({
type: 'get',
url: BASE_URL + 'admin/index/user_id',
data: {
user_id: txt
},
dataType: 'json',
success: function(data) {
console.log('success' + data.success);
if (data.success) {
var Value = data.location.user_id;
alert(Value);
}
}
});
});
These values are getting in html form. In that I need to store user id in Value varable. But I receive successundefined as a output..
[{
"user_id": "139",
"mobile": "9042843911",
"gender": "male",
"hashcode": "DfAbMqLApAV6nVa1z940",
"username": "anandhsp21",
"password": "74bcff7d1199012e154f364e3f65e31d:8I",
"authorized_person": "Anandh",
"created": "2015-06-08 13:46:55",
"modified": "2015-06-08 06:43:35",
"logdate": "2015-06-08 08:16:55",
"lognum": "12",
"reload_acl_flag": "0",
"is_active": "1",
"extra": "N;",
"rp_token": null,
"rp_token_created_at": null,
"app_name": "",
"api_key": ""
}]
Please some one help. Thanks in Advance
Your get the data in array so use loop in success data
for (var i=0; i<data.length; i++) {
console.log('success' + data[i].user_id );
}
If you know the record length is 1 then use directly
console.log('success' + data[0].user_id );
Your data is an array that contains one object. So you can access this object using :
success: function(data){
console.log('success' + data[0].user_id );
Trying to log success is pointless, because there is no success key whatsoever in the received data.
Make sure that you get the response in proper json format,and as harshad pointed String male should be wrapped in double quotes.
After you get that fixed,you can access the user_id as:
data[0].user_id
data.success is undefined, because the received data is stored directly in data. That's the first argument of the success block. You can access the received data directly by data[0] to get the object inside of the array, or if you have a larger array you can do a for each loop over it, etc..
Try this, simply use json.parse()
$(document).ready(function() {
var v = ['{"user_id":"139","mobile":"9042843911"}'];
var obj = JSON.parse(v);
alert(obj.user_id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
To get userid please follow below code I edited,
$('User_id').observe('blur', function(e) {
var txt = $('User_id').value;
jQuery.ajax({
type: 'get',
url: BASE_URL + 'admin/index/user_id',
data: {
user_id: txt
},
dataType: 'json',
success: function(data) {
// this below userid is the value user_id you want.
var userid = data[0].user_id;
}
});
});
There is a json error
"gender":male
Strings male should be wrapped in double quotes.
you need to make sure that your response is formatted appropriately and according JSON.org standards.

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];

accessing json data from jquery

I'm creating an ajax app using jQuery 1.4.2 and I've tried using using get(), post() and the ajax() method itself. My php service returns:
[{"k":"label0","v":0.5},{"k":"label1","v":99.43},{"k":"label2","v":2.46},{"k":"label3","v":46.29},{"status":"OK"}]
in my success callback I have tried accessing as json.status and json[0][0]
but it always returns "undefined". what am I doing wrong?
function getSysinfo(source) {
var json = null;
$.ajax({
url: source,
type: 'POST',
dataType: 'json',
success: function (data) {
json = eval("(" + data + ")");
$('#data').html(json.status);
alert(json[0][0]);
refreshChart(json);
},
error: function (request, status, error) {
alert("REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
return json;
}
I've been googling this for days. How the heck do I access the returned data? any help would be appreciated.
To access that status value you would need:
data[4].status
This is because it is an object stored in the the fifth element in an array, with status being a property on the object.
Your JSON-data looks like this:
[
{
"k": "label0",
"v": 0.5
},
{
"k": "label1",
"v": 99.43
},
{
"k": "label2",
"v": 2.46
},
{
"k": "label3",
"v": 46.29
},
{
"status": "OK"
}
]
You would have to read your status using
json[4].status
with the 4 as a magical number or length-1 - not desirable. I would consider modifying your servers response to something more useful like this:
{
"status": "OK",
"entries": [ ... ] // add your data here
}
In your success callback try:
var parsed = $.parseJSON(data);
$.each(parsed, function (i, jsondata) {
alert( jsondata.k );
alert( jsondata.v );
});
You don't need the eval("("+data+")");. jQuery is automatically parsing the JSON response for you because you specified dataType:'json'
From the jQuery docs for dataType:
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
no need to use eval any more use below code which can be more for json
$.getJSON(url+query,function(json){
$.each(json,function(i,value){
});
});
nategood already wrote that you don't need do do anything with data, it's already an object.
In this case it's an array, if you like to access the status, you need to retrieve it from the last item of the data-array(that's where you'll find it in this array):
data[data.length-1].status
But maybe you should think about another structure of your JSON, it doesn't look very comfortable.
Something like that:
{
"items":[
{"k":"label0","v":0.5},
{"k":"label1","v":99.43},
{"k":"label2","v":2.46},
{"k":"label3","v":46.29}
],
"status":"OK"
}
...should be easier to handle, because you can simply access data.status instead of first looking where you may find it inside the response(what may be error-prone ).
The data parameter is the decoded JSON as you can see in this example:
http://www.jsfiddle.net/rLprV/1/
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: formData,
showLoader:true,
success: function (response) {
var parsed = JSON.parse(JSON.stringify(response));
$.each(parsed, function (key, val) {
alert( val.name );
});
},
error: function (err) {
alert("Please enter a valid id")
}
});

Categories