3

So I have 5 Tab Buttons and 5 Tab Containers. Each container is attached to an AJAX that sends Longitude and Latitude to my php file and after its processed, the container will show the results. I have had no luck consolidating my AJAX's into one function. However, can someone help me add an onclick function to the AJAX call so it only executes when the user clicks the respective tab button?

ALSO

After obtaining the users location in the first AJAX function, can I use those variables again for another AJAX, without requesting location again?

Here is my website: https://www.aarontomlinson.com

Here is the needed code

AJAX FUNCTIONS

$(document).ready(function(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showShopsSponsored);
    } else { 
        $('#ShopsSponsored').html('Geolocation is not supported by this browser.');

    }
});

function showShopsSponsored(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
     $(".spinner").show();
    $.ajax({
        type:'POST',
        url:'ShopsSponsored.php',
        data:'latitude='+latitude+'&longitude='+longitude,
        success:function(msg){
            if(msg){
               $("#ShopsSponsored").html(msg);
            }else{
                $("#ShopsSponsored").html('Not Available');
            }
             $(".spinner").hide();
        }
    });

}   



$(document).ready(function(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showShopsDistance);
    } else { 
        $('#ShopsDistance').html('Geolocation is not supported by this browser.');

    }
});

function showShopsDistance(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
     $(".spinner").show();
    $.ajax({
        type:'POST',
        url:'ShopsDistance.php',
        data:'latitude='+latitude+'&longitude='+longitude,
        success:function(msg){
            if(msg){
               $("#ShopsDistance").html(msg);
            }else{
                $("#ShopsDistance").html('Not Available');
            }
                 $(".spinner").hide();
        }
    });

}   

HTML FOR TAB CONTAINER

  <!-- TAB BUTTONS  -->
  <ul id="tabs" class="menu-left">
      <li><button2><a  id="tab1" ><div style="width:100vw;white-space:nowrap;overflow: hidden;">Suggested</div></a></button2></li>
    <li><button2><a id="tab2">Distance</a></button2></li>
    <li><button2><a id="tab3">Rating</a></button2></li>
    <li><button2><a id="tab4">OPEN</a></button2></li>
    <li><button2><a id="tab5">Delivery Price</a></button2></li>
  </ul>


<!-- TAB CONTAINERS  -->
<div class="tabcontainer" id="tab1C">
    <div style="position: relative;" id="ShopsSponsored">
        <div class="spinner">
          <div class="rect1"></div>
          <div class="rect2"></div>
          <div class="rect3"></div>
          <div class="rect4"></div>
          <div class="rect5"></div>
        </div>
    </div>
</div>

<div class="tabcontainer" id="tab2C">
    <div style="position: relative;" id="ShopsDistance">    
            <div class="spinner">
              <div class="rect1"></div>
              <div class="rect2"></div>
              <div class="rect3"></div>
              <div class="rect4"></div>
              <div class="rect5"></div>
        </div>
    </div>
</div>


// TAB CONTAINER SCRIPT
$(document).ready(function() {    

$('#tabs li a:not(:first)').addClass('inactive');
$('.tabcontainer').hide();
$('.tabcontainer:first').show();

$('#tabs li a').click(function(){
    var t = $(this).attr('id');
  if($(this).hasClass('inactive')){ //this is the start of our condition 
    $('#tabs li a').addClass('inactive');           
    $(this).removeClass('inactive');

    $('.tabcontainer').hide();
    $('#'+ t + 'C').fadeIn('fast');
 }
});

});

**********MY GOAL*****************

I want this function to load with the page and send the results to the container like it does..

$(document).ready(function(){
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showShopsSponsored);
} else { 
    $('#ShopsSponsored').html('Geolocation is not supported by this browser.');

}

});

function showShopsSponsored(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
     $(".spinner").show();
    $.ajax({
        type:'POST',
        url:'ShopsSponsored.php',
        data:'latitude='+latitude+'&longitude='+longitude,
        success:function(msg){
            if(msg){
               $("#ShopsSponsored").html(msg);
            }else{
                $("#ShopsSponsored").html('Not Available');
            }
             $(".spinner").hide();
        }
    });

}

Now I want this function load WHEN I click the TAB

function

function showShopsDistance(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
     $(".spinner").show();
    $.ajax({
        type:'POST',
        url:'ShopsDistance.php',
        data:'latitude='+latitude+'&longitude='+longitude,
        success:function(msg){
            if(msg){
               $("#ShopsDistance").html(msg);
            }else{
                $("#ShopsDistance").html('Not Available');
            }
                 $(".spinner").hide();
        }
    });

}   

tab

<button2><a id="tab2">Distance</a></button2>

BONUS POINTS

Can this function also be written without requesting location? Instead using the location variables from the first function?

$(document).ready(function(){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showShopsDistance);
    } else { 
        $('#ShopsDistance').html('Geolocation is not supported by this browser.');

    }
});

function showShopsDistance(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
     $(".spinner").show();
    $.ajax({
        type:'POST',
        url:'ShopsDistance.php',
        data:'latitude='+latitude+'&longitude='+longitude,
        success:function(msg){
            if(msg){
               $("#ShopsDistance").html(msg);
            }else{
                $("#ShopsDistance").html('Not Available');
            }
                 $(".spinner").hide();
        }
    });

}   

THANK YOU! THIS ONE SHOULDN'T BE THAT HARD I JUST KEEP FAILING!

1 Answers1

0

Some remarks:

  • I would use active class instead of an inactive class as you only really care about the active one.

  • You might find it useful to use HTML5 data attributes for your containers. data-tab is 1-1 mapping for the tabs and their containers. data-url is the url that will be called in the AJAX request.

  • I believe you only need to get the geolocation once. So you could get the latitude and longitude, and store them somewhere such as hidden element or localStorage. Then have your AJAX calls use whatever is stored in the localStorage.

Untested but it would look something like this:

HTML

<!-- TAB BUTTONS  -->
<ul id="tabs" class="menu-left">
    <li class="active"><button2><a href="#" data-tab="ShopsSponsored"><div style="width:100vw;white-space:nowrap;overflow: hidden;">Suggested</div></a></button2></li>
    <li><button2><a href="#" data-tab="ShopsDistance">Distance</a></button2></li>
    <!-- etc -->
</ul>

<!-- TAB CONTAINERS  -->
<div class="tabcontainer active" data-tab="ShopsSponsored" data-url="ShopsSponsored.php">
    <div style="position: relative;">
        <div class="spinner">
            <div class="rect1"></div>
            <div class="rect2"></div>
            <div class="rect3"></div>
            <div class="rect4"></div>
            <div class="rect5"></div>
        </div>
    </div>
</div>
<div class="tabcontainer" data-tab="ShopsDistance" data-url="ShopsDistance.php">
    <div style="position: relative;">    
        <div class="spinner">
            <div class="rect1"></div>
            <div class="rect2"></div>
            <div class="rect3"></div>
            <div class="rect4"></div>
            <div class="rect5"></div>
        </div>
    </div>
</div>
<!-- etc -->

CSS

/* by default, tabs should be hidden */
.tabs li, .tabcontainer {
    display: none;
}
/* only active ones should be visible */
.tabs li.active, .tabcontainer.active {
    display: block;
}

JavaScript

$(function () {

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            saveCoordinates(position.coords);
        });
    } else { 
        // probably good idea to have some default geolocation since all your AJAX calls seem to rely on a geolocation
        saveCoordinates({ latitude: 1, longitude: 2 });
    }

    $('#tabs li a').click(function (e) {
        e.preventDefault();
        var link = $(this), 
            tab = link.closest('li'), 
            tabContainer = $('.tabcontainer[data-tab="' + link.data('tab') + '"]'),
            spinner = tabContainer.find('.spinner');
        // activate tab
        tab.addClass('active').siblings().removeClass('active');
        // activate tab container
        tabContainer.addClass('active').siblings().removeClass('active');
        // make AJAX call
        spinner.show();
        $.ajax({
            type: 'POST',
            url: tabContainer.data('url'), 
            data: { 
                latitude: localStorage.getItem('latitude'), 
                longitude: localStorage.getItem('longitude') 
            }, 
            success: function (msg) {
                spinner.hide();
                if (msg) {
                    tabContainer.find('> div').html(msg);
                } else {
                    tabContainer.find('> div').html('Not Available');
                }
            }
        });
    });

    function saveCoordinates(coords) {
        localStorage.setItem('latitude', coords.latitude);
        localStorage.setItem('longitude', coords.longitude);
    }
});
Mikey
  • 6,728
  • 4
  • 22
  • 45
  • I want to go ahead and say thank you for taking the time to help. I will post an update after I try this out. –  Jun 01 '17 at 21:23
  • Thank you again. @mikey I have been applying your code with a lot of success. I want to ask you about storing the longitude and latitude as session variables? –  Jun 03 '17 at 11:51
  • For the purpose of my website, I want make delivery to the location of the user. If say the user ordered again 24 hours later, would there location still be saved from the day before? I assume the local storage variable is being updated when I load the page. Just wondering if there is a better choice for my situation. @Mikey –  Jun 03 '17 at 12:03
  • I'd be careful with using the geolocation as where I am currently at may not be where I want my delivery to be sent ex. I might be using your site on a train. Instead, I would have a form to let the user explicitly specify their location. I would only use geolocation to map out the nearest store locations. To persist the information, such as my geolocation, you could use [localStorage](https://stackoverflow.com/a/37105645/1022914) but there would need to be a way to update that information. – Mikey Jun 03 '17 at 13:16