0

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?

1
  • 3
    The manual has examples. api.jquery.com/jQuery.getJSON if those aren't enough, you'll need to explain in more detail where you are stuck Commented Aug 14, 2012 at 7:43

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.