2

How to retrieve status field from json file using text field as source for identificator code?

My data.json file:

[{
        "code":"001",
        "status":"ready"
    },
    {
        "code":"002",
        "status":"not ready"
    }
]

My jquery file:

$(document).ready(function() {
$('#ticketsearch').click(function() {
  var ticketcode = $('[name=ticketcode]').val();
  $('.ticket').text(ticketcode);
  $.getJSON('data.json', function(data) {
  $('.status').text(data.status);
  });
  });
});

3 Answers 3

2

In this case you need to loop through until you find the code that matches, like this:

$(document).ready(function() {
  $('#ticketsearch').click(function() {
    var ticketcode = $('[name=ticketcode]').val();
    $('.ticket').text(ticketcode);
    $.getJSON('data.json', function(data) {
      $.each(data, function(i, obj) {
        if(obj.code == ticketcode)
          $('.status').text(obj.status);
      });
    });
  });
});

If it's an option, just simplify your JSON to where code is the key, like this:

{
   "001":"ready",
   "002":"not ready"
}

Then you can access it via that key, like this:

$(document).ready(function() {
  $('#ticketsearch').click(function() {
    var ticketcode = $('[name=ticketcode]').val();
    $('.ticket').text(ticketcode);
    $.getJSON('data.json', function(data) {
      $('.status').text(data[ticketcode]);
    });
  });
});
Sign up to request clarification or add additional context in comments.

4 Comments

I like your second version, but $('.status').text(data[ticketcode]); returns no value. PS. I updated my JSON file
@adpo - if you alert ticketcode what do you get? If it's not "001", or "002", etc...when it just isn't finding the key.
@adpo - Your file looks like I have above? No other syntax at all?
I just deleted the square brackets from JSON. And everything works. Thank you.
0

Which one do you want? You get back an array. If you want the first status: data[0].status. If the 2nd element: data[1].status

1 Comment

I will select the id from the text field and then submit. Can I use for example data[ticketcode].status
0

You have an array of dictionary objects, so you'll need to use data[0].status up to data[n].status.

3 Comments

I will select the id from the text field and then submit. Can I use for example data[ticketcode].status
yup, if ticketCode is the id you want, then that's what you do.
Take a look at @Nick Craver's answer. He has an example for you.

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.