0

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.

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
robinhood91
  • 1,641
  • 3
  • 20
  • 36

2 Answers2

1

abstract the logic, create functions that do the tasks you want to achieve (declare them outside the ajax call) and just call them once you have the ajax response;

function insertDataInDom(data){
    document.getElementById("data1").innerHTML = data.block
    document.getElementById("data2").innerHTML = data.address
}

$.ajax({
        url: "/geodata",
        data: {'lat':lat,'lng':lng},
        type: "POST",
        success: function(result) {
            if ( typeof result == "string") {
                console.log("helo");
             } else {
               insertDataInDom(result.data)
             }
StackOverMySoul
  • 1,957
  • 1
  • 13
  • 21
1

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);
Mulan
  • 129,518
  • 31
  • 228
  • 259
  • Is there an advantage to using native promises over the promises returned by jQuery ajax methods? – 1252748 Sep 20 '16 at 21:39
  • if you want my opinion, one is native garbage and the other is 3rd party garbage. I find it easier to rationalize investing time learning natives compared to 3rd party proprietary stuff tho. JavaScript Promise is what we got, so you might as well get to know it :s – Mulan Sep 20 '16 at 21:48
  • What do you feel is lacking about these two implementations? Are there any libraries (node, angular, etc) you find acceptable? – 1252748 Sep 20 '16 at 21:56
  • 1
    Here's more information on [JS Promises vs jQuery Deferreds](http://stackoverflow.com/questions/32831143/javascript-promise-vs-jquery-deferred). My personal problem with JS Promise is that they're eager and excessively complicated. See [folktale/data.task](https://github.com/folktale/data.task) for lazy promises that are so simple you could've probably written it yourself – and with virtually all the power any other more complicated implementation gives you – and then some. – Mulan Sep 20 '16 at 22:11