newenthusiast newenthusiast - 2 months ago 7
HTML Question

How to separate ajax response and HTML code?

I have an ajax request below:

$.ajax({
url: "/geodata",
data: {'lat':lat,'lng':lng},
type: "POST",
success: function(result) {
if ( typeof result == "string") {
console.log("helo");
} else {
// do things with the result here


the result is an array as such:

arr = [{address: '1300 BRYANT ST',
block: '3903',
cnn: '517000',
latitude: '37.7690871267671',
longitude: '-122.411527667132',
received: '2016-05-06' },

more objects];


I want to use the address and block information and display them as a list of elements on my html page.

My concern is, I do not wish to make my ajax function too long and do my HTML coding inside the request. How can I separate the DOM code (for listing the information) and the result received? I am trying to avoid writing spaghetti code.

Thanks!

Answer

The easiest way without you having to rewrite a lot of your code is to just use functions

function getLocations(lat, lng) {
  let req = $.post('/geodata', {lat: lat, lng: lng});
  req.done(function(result) { renderLocations(result); });
  req.fail(function(jqxhr, textStatus, err) { console.error(err); });
  return req;
}

function renderLocations(locations) {
  locations.foreach(function(location) {
    // render location node
    // <div class="location">
    //   <p>{location.address}</p>
    //   <p>{location.lat} {location.lng}</p>
    // </div>
    $('#locations').append(childNode);
  });
}

Otherwise, if you're OK/familiar with Promises, you can get a much better control over the flow of the program like this

function getLocations(lat, lng) {
  return new Promise(function(resolve, reject) {
    let req = $.post('/geodata', {lat: lat, lng: lng});
    req.done(function(data, textStatus, req) { resolve(data); });
    req.fail(function(req, textStatus, err) { reject(err); });
  });
}

function renderLocations(parentNode) {
  return function(locations) {
    locations.foreach(function(location) {
      // render location node
      // <div class="location">
      //   <p>{location.address}</p>
      //   <p>{location.lat} {location.lng}</p>
      // </div>
      parentNode.append(childNode);
    });
  };
}

function logError(err) {
  console.error('an error occurred:', err.message);
}

// put them together
getLocations(37, -122).then(renderLocations($('#locations')), logError);
Comments