hiding and showing parts of page with Jquery and JS - javascript

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.

Related

jQuery UI draggable doesn't work on created element

Draggable function works on other already created elements, but not on the one i'm creating within a function after submit button.
I've checked if i'm adding an id to 'li' elements and it works, so why can't I drag it?
It works when I use it on whole 'ul' element.
HTML:
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div id='drag'>" + query + "</div>"
$("#list").append(registry)
$("#entry").val("");
return false; //also stops refreshing
console.log(registry);
}
})
$("#drag").draggable({
axis: "y"
});
You can only use an id once, so I would suggest that you use class for that. Furthermore, you should add the draggable to the element after creation, as Ferhat BAŞ has said.
https://jsfiddle.net/exqn1aoc/2/
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div class='drag'>" + query + "</div>"
$("#list").append(registry);
$('#list').children().last().draggable();
$("#entry").val("");
return false; //also stops refreshing
console.log(registry);
}
});
Just use class instead of id for multi pal created item to drag and put your draggable inside button click.
$("#entryButton").click(function() {
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div id='drag' class='drag'>" + query + "</div>"
$("#list").append(registry)
$("#entry").val("");
$(".drag").draggable({
axis: "y"
});
return false; //also stops refreshing
console.log(registry);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
First you need to put the draggable() function inside your click function.
Second, do not use id . Duplicate id's are not valid HTML and that's what causing only the first #drag to be draggable. Use class instead
See snippet below
$("#entryButton").click(function() {
event.preventDefault(); //stops refreshing
var query = $("#entry").val();
if (query !== "") {
var registry = "<div class='drag'>" + query + "</div>"
$("#list").append(registry)
$("#entry").val("");
$(".drag").draggable()
return false; //also stops refreshing
console.log(registry);
}
})
.drag {
height: 100px;
width: 100px;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>

Adding a onclick function to AJAX

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);
}
});

How to find Next Image src with Javascript

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");

Laravel 5 Paginate + Infinite Scroll jQuery

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.

Multiple Javascript Functions in Jquery

I've been having the same issue for a very long time and I'm wondering if someone can teach me what I'm doing wrong.
I created a multipage Jquery (like the one in the example below) however, when I go to add a reference to a .js file I've saved it always tends to either not load up the pages content or if positions somewhere else it just simply wont work!
My HTML code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Find A Deal</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<style>
img.fullscreen {
max-height: 100%;
max-width: 100%;
}
</style>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript">
$(document).on('pagebeforeshow', '#index', function(){
$("#list").empty();
var url="http://localhost/tmp/json4.php";
$.getJSON(url,function(json){
//loop through deals
$.each(json.deals,function(i,dat){
$("#list").append("<li><a id='"+dat.dealid+"' data-restaurantid=" + dat.restaurantid + " data-image=" + dat.image + "><h1>"+dat.name+"</h1><h6>"+dat.dname+"</h6><h5>"+dat.description+"</h5></a></li>");
$(document).on('click', '#'+dat.dealid, function(event){
if(event.handled !== true) // This will prevent event triggering more then once
{
dealObject.dealID = $(this).attr('id');
dealObject.restaurantid = $(this).attr('data-restaurantid');
dealObject.shortName = $(this).find('h1').html();
dealObject.image = $(this).attr('data-image');
//dealObject.dname = $(this).find('input').html();
//dealObject.dname = $(this).find('desc').val();
dealObject.dealName = $(this).find('h6').html();
dealObject.description = $(this).find('h5').html();
//dataObject.dname=$(this).find('p').html()
//dealObject.name = $(this).find('desc').eq(0).val(dealObject.name);
$.mobile.changePage( "#index2", { transition: "slide"} );
event.handled = true;
}
});
});
$("#list").listview('refresh');
});
});
$(document).on('pagebeforeshow', '#index2', function(){
//$('#index2 [data-role="content"]').html('You have selected Link' + dealObject.dname);
$('#index2 [data-role="content"]').find('#deal-img').attr('src',dealObject.dealObject);
$('#index2 [data-role="content"]').find('#title').html(dealObject.name);
//$('#index2 [data-role="content"]').find('#description').html(dealObject.dname);
$('#index2 [data-role="content"]').find('input#desc').val(dealObject.description);
$('#index2 [data-role="content"]').find('input#tname').val(dealObject.dealName);
$('#index2 [data-role="content"]').find('input#dealid').val(dealObject.dealID);
});
var dealObject = {
dealID : null,
restaurantid : null,
shortName : null,
image : null,
dealName : null,
description: null
}
</script>
</head>
<body>
<div data-role="page" id="index">
<div data-role="header" data-position="fixed">
<h1>Current Deals</h1>
</div>
<div data-role="content">
<div class="content-primary">
<ul id="list" data-role="listview" data-filter="true"></ul>
</div>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</div>
</div>
</div>
<!--New Page -->
<div data-role="page" id="index2">
<!--<script src="js/ammend.js"></script>--!>
<div data-role="header">
<h1> Find A Deal </h1>
</div>
<div data-role="content">
<!-- <?php
if( !isset( $_SESSION ) ){
session_start();
}
if( isset( $_SESSION['username'] ) ){
echo ".";
} ?> --!>
<form id="test">
<label for="name">Deal Name:</label>
<input type="text" value="" name="tname" id="tname"/>
<label for="desc">Description</label>
<input type="text" value="" name="desc" id="desc"/>
<a data-role="button" id="amend" data-icon="star" data-iconpos="left">Amend Deal </a>
<input type="text" value="" name="dealid" id="dealid"/>
<h3></h3>
<!--<img src="" width="100px" height="100px" id="deal-img">
<h1 id="title"></h1>
<h3 id="description"></h3>
<p id="name"></p>--!>
</div>
<footer data-role="footer" data-position="fixed">
<nav data-role="navbar">
<ul>
<li>Home</li>
<li>My Deals</li>
</ul>
</nav>
</footer>
</div>
</body>
</html>
Apologies if it's hard to read. This javascript function will work just fine by itself. When an item in index is clicked it brings you to a new page in index2. On index 2 there's a submit button to which is connect to a file referenced <script src="js/ammend.js"></script>. This is where things normally seem to go wrong for me as it's like they're cancelling eachother out or just not co-operating together.
The js file at that location is:
$(document).on('pagebeforeshow', '#index2', function(){
$('#amend').on('click', function(){
if($('#tname').val().length > 0 && $('#desc').val().length > 0 && $('#dealid').val().length > 0){
userObject.tname = $('#tname').val(); // Put username into the object
userObject.desc = $('#desc').val(); // Put password into the object
userObject.dealid = $('#dealid').val();
// Convert an userObject to a JSON string representation
var outputJSON = JSON.stringify(userObject);
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
ajax.sendRequest({action : 'index2', outputJSON : outputJSON});
} else {
alert('Please fill all nececery fields');
}
});
});
$(document).on('pagebeforeshow', '#index2', function(){
if(userObject.name.length == 0){ // If username is not set (lets say after force page refresh) get us back to the login page
$.mobile.changePage( "#index2", { transition: "slide"} ); // In case result is true change page to Index
}
$(this).find('[data-role="content"] h3').append('Deal Amended:' + userObject.name); // Change header with added message
//$("#index").trigger('pagecreate');
});
// This will be an ajax function set
var ajax = {
sendRequest:function(save_data){
$.ajax({url: 'http://localhost/test/login/amend.php',
data: save_data,
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (num) {
if(num == "true") {
$.mobile.changePage( "#index", { transition: "slide"} ); // In case result is true change page to Index
} else {
alert('Deal has been added successfully'); // In case result is false throw an error
$.mobile.changePage( "#index", { transition: "slide"} );
}
// This callback function will trigger on successful action
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Error: " . mysql_error() . "Query: " . $query;');
}
});
}
}
// We will use this object to store username and password before we serialize it and send to server. This part can be done in numerous ways but I like this approach because it is simple
var userObject = {
tname : "",
desc : "",
dealid: ""
}
The above should be called when the button is being pressed but most of the time I cant even get to the stage of seeing the button once I add the referecne to this code.
If anybody has had the same issue as this before or can shed some light on the problem I'd really appreciate it.
Your problem is related to jQuery Mobile page handling.
Because you are using multiple HTML pages loaded with ajax into the DOM all your js scripts must be referenced from the first HTML files. All other HTML files will be loaded only partially, only BODY part will be loaded while HEAD is going to be discarded.

Categories

Resources