0

I get the data from the json file from my localhost but the var html only returns the data in html when i call alert throughout the the loops and it only works in Firefox.

My Questions

1.How do i take out alert in my javascript to where the function still returns var html

2.What can i use besides alert to show my data from my json file

3.Why isn't my code running on all internet platforms

function myFunction()
{
var html=new String();
    $.getJSON('GroupID.json',function(data)
    {
        var h=new String();
        for(var i=0;i<data.length;i++)
        {
            h+='<div class="data">';

            h+=data[i]['group_option'].OptionsID+'<br>';
            h+=data[i]['group_option'].MenuGroupID+'<br>';
            h+=data[i]['group_option'].group_options_name+'<br>';

            for(var iter = 0; iter < data[i]['group_option']['option_items'].length; iter++)
            {

                h+=data[i]['group_option']['option_items'][iter]['item'].OptionItemID+'<br>';
                h+=data[i]['group_option']['option_items'][iter]['item'].option_name+'<br>';
                h+='<br><br><br>';
            }   
            h += '</div>';
        }
        alert("h");
        alert(h);   
        alert("html equals ");
        html=h; 
        alert(html);

    });

alert("returning html");
alert(html);
return html;
}

DEMO: http://jsfiddle.net/97Fzt/1/

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Jonathan
  • 11
  • 1
  • 5
  • 1
    Please post a minimal yet complete code example directly in your question. – cookie monster Apr 17 '14 at 18:01
  • 1
    When the editor gives you an error, you are supposed to ***SOLVE*** it, not workaround it by posting the link without `http://`. – gen_Eric Apr 17 '14 at 18:02
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – cookie monster Apr 17 '14 at 18:03
  • AJAX is ***asynchronous***. This means it runs in the background and calls its callback function at some point in the future when the request is complete. It does *not* wait for the request to complete before continuing on with your code. Your `return html;` is ran *way* before the AJAX request is complete. You *cannot* return from an AJAX call. You need to rethink your strategy here. You need to put all code pertaining to the AJAX call into its callback. This is usually solved by passing a callback to `myFunction` to be called instead of expecting a return value. – gen_Eric Apr 17 '14 at 18:04
  • P.S. the `alert()` will *pause* JavaScript execution. This lets your code wait until the AJAX call is done. That's why it works with the `alert()`s. – gen_Eric Apr 17 '14 at 18:08

0 Answers0