0

In my rails app, i need to populate 1 field with value that came in json, which was returned by clicking on link. Is there any tutorial on how to correctly use ajax to do such thing? Here is my plan how to do this:

1.Send get request to my json appname/controller/action.json

2.parse this json on client side

3.set value of field with parsed json

jvnill
  • 29,479
  • 4
  • 83
  • 86
sanny Sin
  • 1,555
  • 3
  • 17
  • 27
  • 1
    You can read the documentation of: http://api.jquery.com/jQuery.getJSON/. jQuery would take care of parsing the JSON for your but if you have to do it yourself, for whatever reason: [How to parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript). If you have a complex data structure, this might help to figure out how to access it: [I have a nested data structure / JSON, how can I access a specific value?](http://stackoverflow.com/q/11922383/218196). How to set the value of input is also explained in the docs: http://api.jquery.com/val/#val2. – Felix Kling Feb 22 '13 at 09:55

2 Answers2

2

Assuming data is the JSON object, you could use this inside the $.getJSON callback:

var $inputs = $('form input');
$.each(data, function(key, value) {
  $inputs.filter(function() {
    return key == this.name;
  }).val(value);
});

second way
eg: JS fiddle

Raj Adroit
  • 3,828
  • 5
  • 31
  • 44
2

I am assuming your json string is like that

 [{"id":"1","name":"test1"},{"id":"2","name":"test2"},{"id":"3","name":"test3"},{"id":"4","name":"test4"},{"id":"5","name":"test5"}]

use the $.getJSON method:

$.getJSON('/appname/controller/action.json', { get_param: 'value' }, function(data) {
    $.each(data, function(index, element) {
        $('body').append($('<div>', {
            text: element.name
        }));
    });
});
Talha
  • 18,898
  • 8
  • 49
  • 66
  • 1
    this is almost the way i did it. Except i just assigned to value of input data because i have only one item in my json, so each is not necessary – sanny Sin Feb 22 '13 at 10:11