Question

I am setting up a geo search bar on the sidebar of my website. When the user clicks a link to allow geo location, I am trying to display their zipcode in the header of the sidebar. This works fine, but upon initial click, you have to refresh the page in order for the zip code to appear.

The way I have it set up currently, it returns "Undefined" on click and then on refresh it shows the correct zip. I'm assuming I have to set up some sort of wait function or something so that the function that replaces the header text doesn't fire until a zip code is defined.

Any ideas? Thanks!

Here's the javascript:

// Set sessionStorage paramater on click
$('#findLocations').click(function() {
    jQuery.ajax({
      type: "GET",
      dataType: "html",
      url: "/search/georesults.html",
      success: function(closestLocation) {
        jQuery('.result').html(closestLocation);
      } // end success
    }); // end ajax
    $('.resultHeader').html('Stores nearest <div class="zip">' + userZip + '</div>');
    sessionStorage.UseIP = "Yes"
});

// Check for UseIP and display nearest locations if set
if ( sessionStorage.UseIP == "Yes" ){
    jQuery.ajax({
      type: "GET",
      dataType: "html",
      url: "/search/georesults.html",
      success: function(closestLocation) {
        jQuery('.result').html(closestLocation);
      } // end success
    }); // end ajax
    $('.resultHeader').html('Stores nearest <div class="zip">' + userZip + '</div>');
}
Était-ce utile?

La solution

I would move the result header changes into the same success callback like this:

// Set sessionStorage paramater on click
$('#findLocations').click(function() {
    $.ajax({
      type: "GET",
      dataType: "html",
      url: "/search/georesults.html",
      success: function(closestRep) {
        $('.result').html(closestRep);
        $('.resultHeader').html('Stores nearest <div class="zip">' + userZip + '</div>');
      } // end success
    }); // end ajax

    sessionStorage.UseIP = "Yes"
});

// Check for UseIP and display nearest locations if set
if ( sessionStorage.UseIP == "Yes" ){
    $.ajax({
      type: "GET",
      dataType: "html",
      url: "/search/georesults.html",
      success: function(closestLocation) {
        $('.result').html(closestLocation);
        $('.resultHeader').html('Stores nearest <div class="zip">' + userZip + '</div>');
      } // end success
    }); // end ajax

}

Note, it might be worth-while to add a separate function for changing both at the same time. You can use that as your callback and avoid 2 sections of code to maintain.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top