I now have a json object now, how I make a div with the elements

advertisements

I am using getJson to pull in some info onto the page

$('#request_song').autocomplete({
  serviceUrl: '<%= ajax_path("trackName") %>',
  minChars:1,
  width: 300,
  delimiter: /(,|;)\s*/,
  deferRequestBy: 0, //miliseconds
  params: { artists: 'Yes' },
onSelect: function(value, data){
    // alert('You selected: ' + value + ', ' + $('#request_artist').val());
        $.getJSON('/get_events', function(data) {
                    $(data).each(function(key, value) {
                        console.log(value);
                    });
                });

    },
});

The json will have the name of the event and the city and date

I need to make a have a div that is on the page have the values from the json like

<div id="event_data">

//table info from json


I'm guessing your response looks something like this...

var data = [{
  "event": "Birthday"
  "name": "John Doe",
  "city": "Sunnyvale",
  "date": "04/07/1982"
},{
  ...
}]

If you use $('<div />') or $('<div></div>') to create new elements, jQuery will use regex before creating the element which for obvious reasons will slow you down if you're dealing with large data sets.

For performance use:

var div = $(document.createElement('div'));

or keep it simple...

var div = document.createElement('div');

For performance use standard for loop, not $.each, and cache the length:

var container = $("#event_data");

for(var i = 0, k = data.length; i < k; i++){
  var event = $(document.createElement('div')),
      name = $(document.createElement('span')),
      city = $(document.createElement('span')),
      date = $(document.createElement('span'));

  // add id to event wrapper, if undefined generate random ID to avoid conflicts
  event.attr('id', 'event_'+data[i].event || Math.floor(Math.random()*100));

  // add each item, if undefined then insert empty text
  name.text(data[i].name || "").appendTo(event);
  city.text(data[i].city || "").appendTo(event);
  date.text(data[i].date || "").appendTo(event);

  // append & appendTo do exactly the same thing, markup preference
  container.append(event);
}

If you use text() the value will be treated as just that, text only, and will not be executed. If you use html() you'll have XSS issues.

Hopefully this helps and is what you're looking for.