Get data from Json using jquery - javascript

I have the following json data, which is located in the url http://localhost/stock/index.php/masterfiles/itemgriddata
[{"name":"asdasd","code":"123","id":"1","unit":"Nos","purprice":"25000"},{"name":"Item2","code":"1235","id":"2","unit":"Nos","purprice":"0"}]
I want to get the value of name and code where id equal to 1, and store them as variables using jquery .
I know there is a method like,
$.getJSON('http://localhost/stock/index.php/masterfiles/itemgriddata', function(data) {
console.log(data);
});
but I don't know how to implement it. Can any one help me find the solution?

$.getJSON('http://localhost/stock/index.php/masterfiles/itemgriddata', function(data) {
$.each(data, function(index, val) {
if( val.id == '1'){
var name = val.name,
code = val.code,
unit = val.unit,
purprice = val.purprice,
id = val.id;
}
})
});
But if you want to store all result in array then:
var dataarr = [];
$.getJSON('http://localhost/stock/index.php/masterfiles/itemgriddata', function(data) {
$.each(data, function(index, val) {
if( val.id == '1'){
dataarr.push(
val.name,
val.code,
val.unit,
val.purprice,
val.id;
);
})
});
For more more detail see doco.

You can iterate over the array and check for the object which has id "1" as
arr = [{"name":"asdasd","code":"123","id":"1","unit":"Nos","purprice":"25000"},{"name":"Item2","code":"1235","id":"2","unit":"Nos","purprice":"0"}]
$.each(arr, function(i,ele){
if (ele.id =="1"){
alert(ele.name)
alert(ele.code)
}
});

You can try something like:
$.getJSON('http://localhost/stock/index.php/masterfiles/itemgriddata', function(data) {
var results = [];
$.each(data, function(key, val) {
if (val.id === "1") {
results.push(val.name);
results.push(val.code);
}
});
// Then you can do whatever you want to do with results
});

Related

loop for fetching json data in html [duplicate]

On the jQuery AJAX success callback I want to loop over the results of the object. This is an example of how the response looks in Firebug.
[
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]
How can I loop over the results so that I would have access to each of the elements?
I have tried something like below but this does not seem to be working.
jQuery.each(data, function(index, itemData) {
// itemData.TEST1
// itemData.TEST2
// itemData.TEST3
});
you can remove the outer loop and replace this with data.data:
$.each(data.data, function(k, v) {
/// do stuff
});
You were close:
$.each(data, function() {
$.each(this, function(k, v) {
/// do stuff
});
});
You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.
You can also use the getJSON function:
$.getJSON('/your/script.php', function(data) {
$.each(data, function(index) {
alert(data[index].TEST1);
alert(data[index].TEST2);
});
});
This is really just a rewording of ifesdjeen's answer, but I thought it might be helpful to people.
If you use Fire Fox, just open up a console (use F12 key) and try out this:
var a = [
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];
$.each (a, function (bb) {
console.log (bb);
console.log (a[bb]);
console.log (a[bb].TEST1);
});
hope it helps
For anyone else stuck with this, it's probably not working because the ajax call is interpreting your returned data as text - i.e. it's not yet a JSON object.
You can convert it to a JSON object by manually using the parseJSON command or simply adding the dataType: 'json' property to your ajax call. e.g.
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: data,
dataType: 'json', // ** ensure you add this line **
success: function(data) {
jQuery.each(data, function(index, item) {
//now you can access properties using dot notation
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
Access the json array like you would any other array.
for(var i =0;i < itemData.length-1;i++)
{
var item = itemData[i];
alert(item.Test1 + item.Test2 + item.Test3);
}
This is what I came up with to easily view all data values:
var dataItems = "";
$.each(data, function (index, itemData) {
dataItems += index + ": " + itemData + "\n";
});
console.log(dataItems);
Try jQuery.map function, works pretty well with maps.
var mapArray = {
"lastName": "Last Name cannot be null!",
"email": "Email cannot be null!",
"firstName": "First Name cannot be null!"
};
$.map(mapArray, function(val, key) {
alert("Value is :" + val);
alert("key is :" + key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
if you don't want alert, that is u want html, then do this
...
$.each(data, function(index) {
$("#pr_result").append(data[index].dbcolumn);
});
...
NOTE: use "append" not "html" else the last result is what you will be seeing on your html view
then your html code should look like this
...
<div id="pr_result"></div>
...
You can also style (add class) the div in the jquery before it renders as html
I use .map for foreach. For example
success: function(data) {
let dataItems = JSON.parse(data)
dataItems = dataItems.map((item) => {
return $(`<article>
<h2>${item.post_title}</h2>
<p>${item.post_excerpt}</p>
</article>`)
})
},
If you are using the short method of JQuery ajax call function as shown below, the returned data needs to be interpreted as a json object for you to be able to loop through.
$.get('url', function(data, statusText, xheader){
// your code within the success callback
var data = $.parseJSON(data);
$.each(data, function(i){
console.log(data[i]);
})
})
I am partial to ES2015 arrow function for finding values in an array
const result = data.find(x=> x.TEST1 === '46');
Checkout Array.prototype.find() HERE
$each will work.. Another option is jQuery Ajax Callback for array result
function displayResultForLog(result) {
if (result.hasOwnProperty("d")) {
result = result.d
}
if (result !== undefined && result != null) {
if (result.hasOwnProperty('length')) {
if (result.length >= 1) {
for (i = 0; i < result.length; i++) {
var sentDate = result[i];
}
} else {
$(requiredTable).append('Length is 0');
}
} else {
$(requiredTable).append('Length is not available.');
}
} else {
$(requiredTable).append('Result is null.');
}
}

Only 1 result from JSON loop

Could somebody explain how come this is only returning 1 result (there should be 4). Its only returning the most recent post title, where I would like to be getting all the post titles in the category (ID: 121) which in this case is four.
<script type="text/javascript">
var posturl = "http://www.tropical420.com/api/get_posts/?posts_per_page=-1";
$.ajax({
type: 'GET',
url: posturl,
complete: function(){
},
success: function (data) {
var response = data; //JSON.parse(data);
//loop through posts
for(var i = 0; i != response.posts.length; i++) {
//get each element in the array
var post = response.posts[i];
// post vars
var postTitle = post.title;
var postContent = post.content;
var postCategory = post.categories[i].id;
// output stuff so we can see things
if (postCategory == '121') {
$("#post").append(postTitle + "<br />").trigger('create');
}
}
},
error:function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
</script>
<div id="post"></div>
The problem you have is that you aren't iterating through all the categories, instead you are just referring with the same index as to your posts array. You should iterate all the categories through like this
var postCategories= post.categories;
for (var postCategoryIndex in postCategories)
{
var postCategory = postCategories[postCategoryIndex].id;
if (postCategory == '121') {
$("#post").append(postTitle + "<br />").trigger('create');
}
}
The JSON returned does indeed include 49 posts, and you would know that if you had tried console.log(response.posts.length)
sanfor has pointed out the logic error in your code, but your whole callback function can be written much more cleanly, like this:
function (data) {
data.posts.filter(function (post) {
return post.categories.filter(function (cat) { return cat.id === '121'; });
}).forEach(function (post) {
$("#post").append(post.title + "<br />").trigger('create');
});
}

parse value from a php jsonstring in jquery

I am getting following json from php
{"status":{"message":"success","undeleted":[],"code":200}}
{"status":{"message":"success","undeleted":[{"id":7844118,"error":"This Document already Published"}],"code":200}}
I just want to check 'undeleted' is empty or not in jquery.If not empty,I need to take every ids and its error message from 'undeleted'.I am not getting an idea how to do this .I will get only one at a time.
Thinking about something like this
var result = jQuery.parseJSON(data);
$.each(result.data, function(index, value) {
});
I have done something like this but not getting desired answer
var result = jQuery.parseJSON(data);
$.each(result.status, function(index, value) {
alert(value);
});
Here is how to do it:
http://jsfiddle.net/2zLby4r8/3/
var result = jQuery.parseJSON('{"status":{"message":"success","undeleted":[{"id":7844118,"error":"This Document already Published"},{"id":999999,"error":"New Errr"}],"code":200}}');
if (result.status.undeleted.length > 0) {
$.each(result.status.undeleted, function(index, value) {
alert("ID: " + value.id);
alert("Error: " + value.error);
});
} else {
alert("blank");
}

Parsing Json using jquery - not getting value

I am getting following values from server
{"status":{"message":"success","code":200},"data":[{"sent":"test","category":"Appo","experience_time":"2014-10-07","sent_id":4501922,"categoryId":4011,"score":"Negative","feature":"emp","op":"challenges"}]}
I need to get the value of sent,category,experience_time,sent_id,score,feature,op etc
I have tried following so far.But not getting any value.
var result = jQuery.parseJSON(data);
$.each(result, function(index, value) {
alert(value.score);
});
try this,
var jsonString = '{"status":{"message":"success","code":200},"data":[{"sent":"test","category":"Appo","experience_time":"2014-10-07","sent_id":4501922,"categoryId":4011,"score":"Negative","feature":"emp","op":"challenges"}]}';
var result = jQuery.parseJSON(jsonString);
$.each(result.data, function(index, value) {
alert(value.score);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Parse json object of multidimensional array

{
"prev": [
"demo/medium/Web081112_P002_medium.jpg",
"demo/medium/Web081112_P003_medium.jpg"
],
"curr": [
"demo/medium/Web081112_P004_medium.jpg",
"demo/medium/Web081112_P005_medium.jpg"
],
"next": [
"demo/medium/Web081112_P006_medium.jpg",
"demo/medium/Web081112_P007_medium.jpg"
]
}
This is the json I got :
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "scandir.php",
data: "page=5",
dataType: 'json',
success: function (data) {
$.each(data, function(i, data){
$('#img'+i).attr('src',data[1]);
});
}
});
});
</script>
I would like to do this: Assign <img id = "img1" src="demo/medium/Web081112_P002_medium.jpg"> and so on....
The collected data [1] only capture the values in column (3,5,7) . How to implement this? Thanks
since your are just setting the src attribute of the second data object here...
$('#img'+i).attr('src',data[1]);
you are getting the (3,7,5) only...
you have to use two $.each loops to get all the src..
try this
var k=1;
$.each(data, function(i, data1){
$.each(data1, function(j, data2){
$('#img' + k).attr('src', data2);
k++;
});
});
Try this if your array always has two elements:
$.each(data, function(i, data){
$('#img'+(2*i)).attr('src',data[0]);
$('#img'+(2*i + 1)).attr('src',data[1]);
});
If you have more than two, then you'll need an inner loop:
var idx = 0;
$.each(data, function(i, data) {
$.each(data[i], function(j, dataj) {
$('#img'+(idx)).attr('src',dataj[j]);
++idx;
});
});
That's not a multidimensional array, that is an object that has arrays as properties.
To loop through the arrays, you need another loop inside the loop. Use a separate counter to keep track of the image numbering.
var count = 1;
$.each(data, function(i, row){
$.each(row, function(j, item){
$('#img' + count).attr('src', item);
count++;
});
});
Note: There is no specific order to the properties in an object, so they may end up in different order depending on which browser the visitor is using.

Categories

Resources