0

How to use Jquery and Javascript to extract JSON from $ajax and then do a foreach, and create a string that will append to html DOM?

Something like:

$(document).ready(function (e) {

$.ajax({
    type: "POST",
    url: "Companies/GetSearchRatios",
    context: this,
    success: function (data) {
       //return JSON
    }
});

Result JSON

[{"name":"MyNAme","value":350},{"name":"Hello","value":356}]

I can easily acces this values inside $ ajax method success, but how can I extract this value outside of method and use it to append to DOM?

This is what I need as a result of some for/foreach method:

  var $gElemRatios =
    '<option value=""></option>' +
    '<option value="350">MyNAme</option>' +
    '<option value="356">Hello</option>';

Then I use this var to combine with another:

 var $gElem =
    '<div class="cbox cboxQuarterWidth">' +
         '<select id="combobox_0">' +
               $gElemRatios + // here I add previous generated elem
         '</select>' +
    '</div>';

And finally:

$("#main").append($gElem);

Any ideas?

1 Answer 1

3

You can use $.each to loop through the data passed to the success handler:

$.ajax({
    type: "POST",
    url: "Companies/GetSearchRatios",
    context: this,
    success: function (data) {
       $.each(data,function(){
          console.log(this.name); //just an example how to access things
          $('#select').text(this.value); //maybe?
       });
    }
});

See this fiddle

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

8 Comments

ok, great, how can i create string as show in question and get this var outside of success method?
I need this string as a var, global, I cannot directly append data to DOM, because of other things...
@Ingol create an array or object in the scope that you need and use it to store your data.
well I thing this is my main problem, together with creating multiple strings, because of success asynchronous, my scope is undefined?
No that should not be the problem. See: jsfiddle.net/zDJez/1 for a basic approach. Also see the cat example here: api.jquery.com/jQuery.getJSON
|

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.