Basim Sherif
Basim Sherif

Reputation: 5440

Get data from Json using jquery

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?

Upvotes: 0

Views: 428

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87073

$.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.

Upvotes: 3

M Abbas
M Abbas

Reputation: 6479

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
});

Upvotes: 1

pdpMathi
pdpMathi

Reputation: 775

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)
 }
});

Upvotes: 1

Related Questions