0

I am getting data from the server side using AJAX, I am now trying to populate data from from a list of objects into divs, the problem I am having is that I can not create the div while inside of the foreach loop.

    $(document).ready(function () {

        var divs = "";

        var url = "../Graphs/CreateChart";


        $.ajax({
            type: 'POST',
            url: url,
            success: function (data) {
                for (var i in data) {

                    var x = data[i];

                    for (var j in x) {
                        var val;
                        if (x.hasOwnProperty(j)) {

                            val = x[j].SpName;

                            if (x[j].SpName != "undefined") {
                                $('#a').appendTo('#content');
                                createBarChart("#a", "USP_Charts_BarChart1"); 
                            }
                        }
                    }
                }
            }, dataType: "json",
            cache: false
        });
    });
</script>

I am trying to populate where it says "#a" with val and also then I need to populate the div I write with the val for the id, but when I try to put the document.write inside of the loop, I get a blank screen, any ideas why it would do this?

  • [Why shouldn't I use document.write?](http://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) "_document.write executed after the page has finished loading will overwrite the page, or write a new page_" – blex Jul 29 '14 at 16:00
  • Okay, so I removed the document.ready but I still can't place it inside the AJAX loop –  Jul 29 '14 at 16:04
  • You are using jQuery, learn how to use append() – epascarello Jul 29 '14 at 16:06
  • I don't think append will work, I need to create divs not append them? –  Jul 29 '14 at 16:15
  • `append()` adds content so it surely can create new elements. If not, than all the scripts I been writing for 10 years would not be working. – epascarello Jul 29 '14 at 16:16
  • Mhmm I tried to use: $('#a').appendTo('#content'); and it just seems to do nothing –  Jul 29 '14 at 16:19
  • Mind just having a look to see if I have done that right? I updated the code with Jquery Append –  Jul 29 '14 at 16:27

1 Answers1

0

you're trying to append a created variable to your content? Try making the markup a string FIRST then appending it.

To test it try it without data.

$("<h2>HI</h2>").appendTo("#content");

If that works, then make a string that is the markup you want, with the data you need.

$("<a data='"+data.variable+"'></a>").appendTo("#content");

append and appendTo are VERY similar, but you need to use a string, not just an identifier, if the object doesn't exist yet.