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!
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><div style="width:100vw;white-space:nowrap;overflow: hidden;">Suggested</div></button2></li>
<li><button2>Distance</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);
}
});
Related
Below is the script works fine with hover but need it to be either a toggle or a click function if anyone has any ideas on how to achieve this.
it collects data from different php files depending on the button that is hoverd over thats fine but when working on the page it pops up all the time kind of annoying
<script type="text/javascript">
$(document).ready(function(){
$(".container").hide();
$(['btn1', 'btn2', 'btn3']).each(function(){
var btn = this;
var con = $("#"+btn).children('.container');
$("#"+btn).hover(
function(){
$(".hover").mouseout();
$(this).addClass('hover');
var cache = $(con).children('p');
//check to see if content was loaded previously
if(cache.size()){
con.show();
}else{
$(con).show();
$(con).html('<img src="imgs/loader.gif" alt="Loading..." />');
$.ajax({
url: 'data/'+btn+'.php',
type: 'get',
success: function(data){
$(con).html(data);
}
});
}
},
//mouseout
function(){
if($.browser.msie){
$(con).hide();
}else{
$(con).fadeOut(250);
}
$(this).removeClass('hover');
}
);
});
});
</script>
<div id="btn1" class="wrapper">
<div class="button">
<p><i class="fa fa-users" aria-hidden="true"></i></p>
</div>
<div class="content">
</div>
</div>
<div id="btn2" class="wrapper">
<div class="button">
<p><i class="fa fa-comments" aria-hidden="true"></i></p>
</div>
<div class="content">
</div>
</div>
Thanks guys i figured out how to do this and also make the coding less.
so what it does is you create the dropdown button with the btn1 id
and the next button with id of btn2.
the parsing php files called btn1.php you code what you need to display the data in the content div of the buttons
Aaaargh sorry seems like only the first button works shows the conent div and closes when clicked but subsequent new buttons show the content div Ajax requests are all fine
but dont close when clicked again
<script>
$(".wrapper").click( function()
{
var btn = $(this).attr('id');
var conte = $('.content').css('display');
var con = $(this).children('.content');
if (conte == 'block') {
$(con).css('display','none');
} else if (conte == 'none') {
$(con).css('display','block');
$(con).html('<img src="imgs/loader.gif" alt="Loading..." />');
$.ajax({
url: 'configuration/'+btn+'.php',
type: 'get',
success: function(data){
$(con).html(data);
}
});
}
});
</script>
function init_json_table(element) {
var table_name = element;
$.ajax({
url:'get_structure',
type:"POST",
data: JSON.stringify({"table":table_name}),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data) {
$('#' + element).w2grid(data);
}
})
};
$(document).ready(function() {
//initilize all tables on page - fetch data from server
$('.table').each(function() {
init_json_table($(this).attr('id'));
});
// hiding and showing sections on click
$('header nav a').click(function() {
var $linkClicked = $(this).attr('href');
document.location.hash = $linkClicked;
if (!$(this).hasClass("active")) {
$("header nav a").removeClass("active");
$(this).addClass("active");
$('#main-content section').hide();
$($linkClicked).fadeIn();
return false;
}
else {
return false;
}
});
var hash = window.location.hash;
hash = hash.replace(/^#/, '');
switch (hash) {
case 'block2' :
$("#" + hash + "-link").trigger("click");
break;
case 'block3' :
$("#" + hash + "-link").trigger("click");
break;
}
});
#block2, #block3 {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<nav>
<ul>
<li>block1</li>
<li>block2</li>
<li>block3</li>
</ul>
</nav>
</header>
<div id="main-content">
<section id="block1">
<div class="table" id=block1_table1></div>
<div class="table" id=block1_table2></div>
<div class="table" id=block1_table3></div>
</section>
<section id="block2">
<div class="table" id=block2_table4></div>
<div class="table" id=block2_table5></div>
<div class="table" id=block2_table6></div>
</section>
<section id="block3">
<div class="table" id=block3_table7></div>
<div class="table" id=block3_table8></div>
<div class="table" id=block3_table9></div>
</section>
</div>
I tried implementing this idea of page switching with jQuery:
http://netdna.webdesignerdepot.com/uploads7/how-to-supercharge-your-sites-speed-with-ajax-and-jquery/demo1/#page1
The problem is my content isn't just text, but JS-based tables populated with ajax post calls. I want the whole page to finish loading (about 40-50 ajax calls), all JS tables to initialize and then achieve seamless switching between sections. However, only the first page (that is not hidden) loads fine, the rest of the pages load up with empty div's instead of JS tables.
EDIT: I found a workaround:
$('header nav a').click(function() {
var $linkClicked = $(this).attr('href');
document.location.hash = $linkClicked;
if (!$(this).hasClass("active")) {
$("header nav a").removeClass("active");
$(this).addClass("active");
$('#main-content section').hide();
//workaround
$('.table').each(function() {
w2ui[$(this).attr('id')].refresh();
});
$($linkClicked).fadeIn();
return false;
}
else {
return false;
every time the page button is clicked I refresh all the javascript tables in the page. Unfornately this happens every time and is very time consuming.
There is a button in my webpage which calls another page through AJAX.The page carries certain data named "Match" if the query is successfully ran. Now I want that if a Match is recieved from the other page then a pop up comes. Here's my code
<div id="myNav" class="overlay">
×
<div class="overlay-content">
<h>ksadjaskjdaskdjaskdjaskdjaskdjaskdjasdk</h> </div>
</div>
<button class="abc" style="font-size:30px;cursor:pointer" >☰ Accept</button>
<script type="text/javascript">
var a="Match";
$(document).ready(function(){
$(".abc").click(function(){
$.ajax({
type: 'POST',
url: 'accept.php?w1=<?php echo $id ?>',
success: function(data) {
// $("p").text(data);
if(a=data)
{
function openNav()
{
document.getElementById("myNav").style.height = "100%";
}
}
else
{
location.reload();
}
}
});
});
});
function closeNav() {
document.getElementById("myNav").style.height = "0%";
}
I have chosen this way of doing it so i can just drop a hand full of images in to a folder and that's it, I have tried many ways but nothing works, my latest attempt is using
$(".image-container").find("img[src=" + Img + "]").next('img').attr('src');
but still no go.
This is what i have come up with so far, any help would be great, Thank's
<div id="removed-container" style="height: 600px;">
<div id="removed" style="height: 600px;">
<div style="float: left; width: 200px;">
<h1> <span>The Gallery</span> </h1>
<ul id="nav">
<li>Gallery
<ul>
<li>2015</li>
<li>2015</li>
<li>2015</li>
<li>2015</li>
<li>2015</li>
</ul>
</li>
<li>Back to home</li>
</ul>
</div>
<div class="image-container"></div>
<script type="text/javascript"> $(document).ready(function () {
$("a").click(function () {
var dir_path=$(this).data("albumid");
LoadGallery(dir_path);
return false;
});
});
function LoadGallery(dir_path) {
$.ajax({
url: dir_path,
success: function(data) {
$(".image-container").empty();
$(data).find("a:contains(.jpg), a:contains(.png), a:contains(.jpeg)").each(function() {
this.href.replace(window.location.host,"").replace("http:///",""); file=dir_path+$(this).text();
$(".image-container").append($("<a href='java<!-- no -->script:;' class='thumb' data-src='"+file+"'><img src='"+file+"' title='Click to enlarge' alt='#'/></a>"));
if ($(".image-container").children("a").length == 30) {
return false;
}
});
$(".thumb").bind('click', function() {
var Popup="<div class='bg'></div>"+"<div class='wrapper'><img src='<img src=''/>"+"<label href='javascript:;' class='prev-image'>«</label><label href='javascript:;' class='next-image'>»</label><a href='java<!-- no -->script:;' class='close' title='Close'>Close</a>";
Img = $(this).attr("data-src"),
$("body").prepend(Popup);
$(".bg").height($(window).height()*4);
$(".wrapper img").attr("src", Img);
$(".prev-image").bind ('click',function() {
alert("Prev")
})
$(".next-image").bind ('click',function() {
next = $(".image-container").find("img[src=" + Img + "]").next('img').attr('src');
//alert(next)
})
$(".close").bind ('click',function() {
$(this).siblings("img").attr("src", "")
.closest(".wrapper").remove();
$(".bg").remove();
});
});
}
});
} </script>
<div class="clear"></div>
The problem is in the usage of next().
From documentation - Get the immediately following sibling of each element in the set of matched elements.
And as in your case, img are not siblings, hence, there are no matched set of elements.
If your hierarchy is strict and is not going to change, then you can do something like following
/* Find image - go its parent - go to next anchor - get the image - get the source */
$(".image-container").find("img[src='" + Img + "']").parent().next('a').find("img").attr('src');
Else you can iterate over the images.
For reference - http://plnkr.co/edit/onUeWl8mPqVhtaHf37xp?p=preview
Please try this:
$('#id').next().find('img').attr("src");
I am trying to use paginate() to achieve infinite scroll. I think the easiest way is using the 'infinite-scroll' to achieve this. If you have any other suggestion how to do it without infinite-scroll library, just using jQuery, I'd be happy to know..
I am returning the variable to view like this:
public function index()
{
$posts = Post::with('status' == 'verified')
->paginate(30);
return view ('show')->with(compact('posts'));
}
My View:
<div id="content" class="col-md-10">
#foreach (array_chunk($posts->all(), 3) as $row)
<div class="post row">
#foreach($row as $post)
<div class="item col-md-4">
<!-- SHOW POST -->
</div>
#endforeach
</div>
#endforeach
{!! $posts->render() !!}
</div>
Javascript Part:
$(document).ready(function() {
(function() {
var loading_options = {
finishedMsg: "<div class='end-msg'>End of content!</div>",
msgText: "<div class='center'>Loading news items...</div>",
img: "/assets/img/ajax-loader.gif"
};
$('#content').infinitescroll({
loading: loading_options,
navSelector: "ul.pagination",
nextSelector: "ul.pagination li:last a", // is this where it's failing?
itemSelector: "#content div.item"
});
});
});
However, this doesn't work. The ->render() part is working because I am getting [<[1]2]3]>] part. However, the infinite scroll doesn't work. I also don't get any errors in the console.
[<[1]2]3]>] is like this in the view:source:
<ul class="pagination">
<li class="disabled"><span>«</span> </li> // «
<li class="active"><span>1</span></li> // 1
<li>2</li> // 2
<li>3</li> // 3
<li>»</li> // »
</ul>
Easy and helpful is this tutorial - http://laraget.com/blog/implementing-infinite-scroll-pagination-using-laravel-and-jscroll
Final script could looks like this one
{!! HTML::script('assets/js/jscroll.js') !!}
<script>
$('.link-pagination').hide();
$(function () {
$('.infinite-scroll').jscroll({
autoTrigger: true,
loadingHtml: '<img class="center-block" src="/imgs/icons/loading.gif" alt="Loading..." />', // MAKE SURE THAT YOU PUT THE CORRECT IMG PATH
padding: 0,
nextSelector: '.pagination li.active + li a',
contentSelector: 'div.infinite-scroll',
callback: function() {
$('.link-pagination').remove();
}
});
});
</script>
You just need to use laravel's pagination
{!! $restaurants->links() !!}
You should be able to use the Pagination just fine as long as your call to get new posts is different than page load. So you'd have two Laravel calls:
1.) To provide the template of the page (including jQuery, CSS, and your max_page count variable -- view HTML)
2.) For the AJAX to call posts based on the page you give it.
This is how I got my infinity scroll to work...
HTML:
<!-- Your code hasn't changed-->
<div id="content" class="col-md-10">
#foreach (array_chunk($posts->all(), 3) as $row)
<div class="post row">
#foreach($row as $post)
<div class="item col-md-4">
<!-- SHOW POST -->
</div>
#endforeach
</div>
#endforeach
{!! $posts->render() !!}
</div>
<!-- Holds your page information!! -->
<input type="hidden" id="page" value="1" />
<input type="hidden" id="max_page" value="<?php echo $max_page ?>" />
<!-- Your End of page message. Hidden by default -->
<div id="end_of_page" class="center">
<hr/>
<span>You've reached the end of the feed.</span>
</div>
On page load, you will fill in the max_page variable (so do something like this: ceil(Post::with('status' == 'verified')->count() / 30);.
Next, your jQuery:
var outerPane = $('#content'),
didScroll = false;
$(window).scroll(function() { //watches scroll of the window
didScroll = true;
});
//Sets an interval so your window.scroll event doesn't fire constantly. This waits for the user to stop scrolling for not even a second and then fires the pageCountUpdate function (and then the getPost function)
setInterval(function() {
if (didScroll){
didScroll = false;
if(($(document).height()-$(window).height())-$(window).scrollTop() < 10){
pageCountUpdate();
}
}
}, 250);
//This function runs when user scrolls. It will call the new posts if the max_page isn't met and will fade in/fade out the end of page message
function pageCountUpdate(){
var page = parseInt($('#page').val());
var max_page = parseInt($('#max_page').val());
if(page < max_page){
$('#page').val(page+1);
getPosts();
$('#end_of_page').hide();
} else {
$('#end_of_page').fadeIn();
}
}
//Ajax call to get your new posts
function getPosts(){
$.ajax({
type: "POST",
url: "/load", // whatever your URL is
data: { page: page },
beforeSend: function(){ //This is your loading message ADD AN ID
$('#content').append("<div id='loading' class='center'>Loading news items...</div>");
},
complete: function(){ //remove the loading message
$('#loading').remove
},
success: function(html) { // success! YAY!! Add HTML to content container
$('#content').append(html);
}
});
} //end of getPosts function
There ya go! That's all. I was using Masonry with this code also so the animation worked wonderfully.