Pass Pagination data to Page - php

I have a page that I'm trying to get AJAX thumbnail replacement & pagination to work. The page loads the initial thumbs: http://www.partiproductions.com/vault_test/1-a-b.php
But when clicking nav buttons, it should change the thumbnails, but doesn't.
My click function (forward button):
$('#gort').mouseup (function() {
var curpg = parseInt($('.thumbwrap').attr('data-cpg'),10);
console.log('Cur Pg: ' + curpg);
var newpg = curpg + 1;
console.log('New Pg: ' + newpg);
var $totpgs = parseInt($('.thumbwrap').attr('data-tpgs'),10);
console.log('Total Pages: ' + $totpgs);
if (newpg > 1) {$('#goleft').show(200)}
if (newpg == $totpgs) {newpg = $totpgs; $('#gort').hide()} // limit page to total pages
if (newpg < $totpgs) {$('#gort').show(200)}
$('.thumbwrap').attr('data-cpg', newpg);
var $start = (newpg - 1) * 15;
console.log('Start: ' + $start);
// my attempt to pass $start to pagination.php
$.ajax({
url:'pagination.php',
type:'POST',
data:{start:$start},
dataType:'JSON'
success: function(response) {
thumbparse(response);
}
});
});
Currently simple thumbparse function:
function thumbparse(response) {
alert(response);
console.log('Thumbparse output: ' + $navresults);
}
Pagination.php:
<?php
$thumbst = $_POST['start']; // capture input from AJAX
echo "Inside Pagination: $thumbst";
require_once 'meekrodb.2.2.class.php';
require_once 'dconnect.php';
// pull from database using specific page items
$navresults = DB::query("SELECT substr(theme, 1, 1) as Alphabet, theme, developer, thumb, thumb_lg FROM gallery ORDER BY (CASE Alphabet
WHEN '1' THEN 1
WHEN '2' THEN 2
WHEN '3' THEN 3
WHEN 'A' THEN 4
WHEN 'B' THEN 5
ELSE 6
END), theme
LIMIT $thumbst,15");
if(isset($_POST['start']) && !empty($_POST['start'])) {
echo json_encode($navresults);
}
// my attempt to loop through assigned variables that are echoed in main pg
$x = 0;
foreach ($navresults as $row) {
$x++;
if ($x == 1) {
$t1 = $row['theme'];
$d1 = $row['developer'];
$th1 = $row['thumb'];
$thlg1 = $row['thumb_lg'];
}
... other x's
}
I'm not seeing the echoes from pagination.php How do I get the new thumb data ($navresults) passed back to main page and get that data into the DOM? Code please, as I'm just learning - thanks.
Update 1:
function thumbparse(response) {
alert(response);
var obj = JSON.parse(response);
alert(obj.count);
console.log('Thumbparse results: ' + $navresults);
}
Update 2:
function thumbparse(response) {
alert(response);
console.log(response);
var x = 0;
var obj = response;
$.each(obj, function(key, val) {
x++;
var y = x - 1;
$('ul.thumbwrap .thumb:nth-of-type(y) img').attr({
alt: obj.theme,
src: obj.thumb,
'data-retina': obj.thumb_lg
});
$('ul.thumbwrap .thumb:nth-of-type(y) p.hname').text(obj.theme);
$('ul.thumbwrap .thumb:nth-of-type(y) p.hdev').text(obj.developer);
});
}
Update 3:
function thumbparse(response) {
alert(response);
console.log(response);
var x = 0;
var obj = response;
$.each(obj, function(key, val) {
x++;
var y = x - 1;
console.log('Exist. src: ' + $('.thumb').eq(y).find('img').attr('src')); // correct
console.log('New src: ' + obj.thumb); // undefined
$('.thumb').eq(y).find('img').attr({
alt: obj.theme,
src: obj.thumb,
'data-retina': obj.thumb_lg
});
$('.thumb').eq(y).find('p.hname').text(obj.theme);
$('.thumb').eq(y).find('p.hdev').text(obj.developer);
});
}
Update 4:
function thumbparse(response) {
alert(response);
console.log(response);
var x = 0;
var obj = response;
$.each(obj, function(key, val) {
x++;
var y = x - 1;
console.log('Exist. src: ' + $('.thumb').eq(y).find('img').attr('src'));
console.log('New src: ' + obj[key].thumb);
$('.thumb').eq(y).find('img').attr({
alt: obj[key].theme,
src: obj[key].thumb,
'data-retina': obj[key].thumb_lg
});
$('.thumb').eq(y).find('p.hname').text(obj[key].theme);
$('.thumb').eq(y).find('p.hdev').text(obj[key].developer);
if (obj[key].theme == '') {$('.thumb').eq(y).hide()}
});
}

Try this:
function thumbparse(response) {
console.log(response);
var x = 0;
var obj = response;
$.each(obj, function(key, val) {
x++;
var y = x - 1;
console.log('Exist. src: ' + $('.thumb').eq(y).find('img').attr('src'));//Actual src
console.log('New src: ' + obj[key].thumb); //new src from json response
$('.thumb').eq(y).find('img').attr({
alt: obj[key].theme,
src: obj[key].thumb,
'data-retina': obj[key].thumb_lg
});
$('.thumb').eq(y).find('p.hname').text(obj[key].theme);
$('.thumb').eq(y).find('p.hdev').text(obj[key].developer);
if (obj[key].theme == '') {$('.thumb').eq(y).hide()}
});
}

Related

Jquery Scroll Loading All The Rows At Once And Should Only Load 5 At A Time

I am using the following script to load more, 5 rows at a time from the database, on scroll. All the rows are loading at once on scroll after the initial loads correctly. In realtime, the first 5 load. Then on scroll the last 14 load at once. Like it rushes to the end instead of incrementally loading 5 at a time. I use the same code for a load more button and it works fine. Same PHP file for both. No issue with that. Can anyone see why all the rows are being loaded on scroll instead of 5 at a time.
<script>
//SET NUMBER OF ROWS TO DISPLAY AT A TIME
rowsPerPage = 5;
$(document).ready(function() {
// GETTING DATA FROM FUNCTION BELOW
getData();
window.onscroll = function() {
if ($(window).scrollTop() >= $('#load-container').offset().top + $('#load-container').outerHeight() - window.innerHeight) {
$('#load-more').html('Loading...');
var rowID = Number($("#row-id").val());
var allCount = Number($("#count").val());
rowID += rowsPerPage;
if (rowID <= allCount) {
$("#row-id").val(rowID);
getData();
} else {
$('#load-more').html('End Of Data');
//$('#load-more').html('');
}
}
}
/* REQUEST DATA */
function getData() {
var rowID = $("#row-id").val();
var allCount = $("#count").val();
$('#load-more').html('Loading...');
$.ajax({
url: 'promotions/newest-load-scroll-data-invalid.php',
type: 'post',
data: {
rowID: rowID,
rowsPerPage: rowsPerPage
},
dataType: 'json',
success: function(response) {
setTimeout(function() {
loadData(response)
}, 1000);
},
});
}
/* LOAD DATA TO PAGE */
function loadData(data) {
var dataCount = data.length;
for (var i = 0; i < dataCount; i++) {
if (i == 0) {
var allCount = data[i]['allcount'];
$("#count").val(allCount);
} else {
var promoID = data[i]['promoid'];
var promoNameNewest = data[i]['promoname'];
var promoNameNewestVideo = data[i]['promoname'];
var promoRefNum = data[i]['promorefnum'];
var promoType = data[i]['promotype'];
var theBanner = data[i]['thebanner'];
var email = data[i]['email'];
var customerType = data[i]['customerType'];
if (email == "") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="visitor-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="visitor-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
if (customerType == "p") {
if (promoType == "Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewest + '</div></div>');
$('#load-container').append('<div><div class="wrap-content"><img class="mobile-banner-scale" id="advertiser-banner-click" src=' + theBanner + '></div></div>');
}
if (promoType == "Video Banner") {
$('#load-container').append('<div class="row-center-center padding-top-5 padding-bottom-2"><div>' + promoNameNewestVideo + '</div></div>');
$('#load-container').append('<div><video class="mobile-video-size" id="advertiser-banner-click" src=' + theBanner + ' autoplay muted loop></video></div>');
}
}
}
$('#load-more').html('Loading...');
}
}
});
</script>
I was able to utilize flags to make it work right with a couple other small changes. Appreciate the input, Taplar.

How to do "If div class is 0 then start from 1 to append"

I'm trying to make multiple upload images via ajax with XMLHttpRequest. Everything is okay. Images post successfully and data returns as expected. So returned images are appending to related div class. But every time i upload images one by one, div class start from zero.
With this code,before to send file(s) i'm creating progressbar div, after each image loaded successfully, image replace to loder.
for (var i = 0; i < input.files.length; i++) {
var fileId = i;
$('.up_preview').append('<div class="uploaded_photo_grid '+ fileId +'">' +
'<div class="pro_bar" id="progressbar_' + fileId + '" style="width:0%"></div>' + loader +
'</div>');
}
With this function, no matter how many files, im uploading them:
for (var i = 0; i < this.files.length; i++) { //Progress bar and status label's for each file genarate dynamically
var fileId = i
$('.up_preview').append('<div class="uploaded_photo_grid '+ fileId +'">' +
'<div class="pro_bar" id="progressbar_' + fileId + '" style="width:0%"></div>' + loader +
'</div>');
}
function uploadSingleFile(file, i) {
var fileId = i;
var ajax = new XMLHttpRequest();
//Progress Listener
ajax.upload.onprogress = function (e) {
var percent = (e.loaded / e.total) * 100;
$('#progressbar_' + fileId).animate({"width": percent + "%"},800);
};
//Load Listener
ajax.onreadystatechange = function (e) {
if (this.readyState == 4 && this.status == 200) {
var data = ajax.responseText;
var rep = JSON.parse(data);
$('#progressbar_' + fileId).css("width", "100%");
setTimeout(function(){
$('#progressbar_' + fileId).remove();
$('.uploaded_photo_grid.'+ fileId).html('');
$.each(file, function(){
if(rep.error !== ''){
$(".uploaded_photo_grid."+ fileId ).html(rep.name + ' yüklenemedi');
} else {
$(".uploaded_photo_grid."+ fileId ).html(
'<img class="previewItem" src="'+rep.fcontent+'" id="img_'+rep.id+'">');
}
});
},1500);
}
};
Rest of code...
}
Also i tried editing these lines of code. It increases the value of div for each file but just first image appears.
var zero = $('.uploaded_photo_grid.0').length;
for (var i = 0; i < this.files.length; i++) { //Progress bar and status label's for each file genarate dynamically
var fileId;
if(zero == 0){
uploadSingleFile(this.files[i], i);
console.log(this.files[i]);
fileId = i;
} else {
uploadSingleFile(this.files[i+1], i+1);
fileId = i+1;
console.log(this.files[i]);
}
$('.up_preview').append('<div class="uploaded_photo_grid '+ fileId +'">' +
'<div class="pro_bar" id="progressbar_' + fileId + '" style="width:0%"></div>' + loader +
'</div>');
}
What should i do? Is there a way to do this better? I mean upload images without form via XML with progressbar for each file. I don't choose to use plugin, that's not for me.
The following is the problematic line.
uploadSingleFile(this.files[i+1], i+1);
You want the value for i passed in uploadSingleFile to be the total number of images uploaded incremented by one.
One approach to do this is to sum $('.up_preview').children().length, i, and 1. 1 is added in the sum because the in the loop i starts at 0.
// var zero = $('.uploaded_photo_grid.0').length;
var numImages = $('.up_preview').children().length;
if (numImages === 0) {
//...
} else {
uploadSingleFile(this.files[i+1], numImages + i + 1);
}

JQUERY and AJAX Pagination and Calling Data

I am facing the following problem, I have a page of products with ajax pagination where users is able to select products in a form, the selected products save their id values in an array, but my problem is when the user goes to page 2 then he go back to page 1 he is able to choose the same product where I need to be the array ids unique, where user is able to select only the product 1 time even if he goes to page 2 or 3 and come back to previous pages
my ajax code:
$(".pageNumber").on("click",function(){
pageID = this.id;
var data_string = 'pageID='+pageID;
$.ajax({
type: "POST",
url: "loadData.php",
data: { "pageId" : pageID, "catid" : catid, "subid" : subid, "filter" : filter, "view" : view_type , "items" : itemArrayList},
cache: false,
success: function (result) {
$(".pageNumber").removeClass("number-page-active");
$("#"+pageID).addClass("number-page-active");
$("#results1").hide();
$("#results").html(result);
console.log(result);
if ($(".number-page-active").attr('id') == 1) {
$('#sub1').attr("style","display:none") ;
}
if ($(".number-page-active").attr('id') != 1) {
$('#sub1').attr("style","display:block") ;
}
if ($(".number-page-active").attr('id') == <?php echo $pageLast ?>) {
$('#add1').attr("style","display:none") ;
}
if ($(".number-page-active").attr('id') != <?php echo $pageLast ?>) {
$('#add1').attr("style","display:block") ;
}
}
});
The list of selected products are saved in array as follow:
$("#quotationSubmit").on("click",function(){
console.log(itemArrayList);
$("#itemListArray").val(itemArrayList);
});
var itemSelected = 0;
itemArrayList = [];
function image(divId) {
if (itemSelected < 0) {
itemSelected = 0;
}
var idDiv = 1;
for (idDiv; idDiv <= 100; idDiv++) {
var divDivId = "" + idDiv;
var divDivId0 = "" + idDiv;
if (divDivId === divId || divDivId0 === divId) {
break;
}
}
if ($("#quotation-form").css("display") === "block") {
if ($("#" + idDiv).hasClass("selected-div") === true || $("#" +
idDiv).hasClass("selected-div")) {
$("#" + idDiv).removeClass("selected-div");
$("#" + idDiv).removeClass("selected-div");
itemSelected--;
index = $.inArray(divId,itemArrayList);
itemArrayList.splice(index,1);
console.log(itemArrayList);
} else {
$("#" + idDiv).addClass("selected-div");
$("#" + idDiv).addClass("selected-div");
itemSelected++;
itemArrayList.push(divId);
console.log(itemArrayList);
}
if (itemSelected === 0) {
document.getElementById("quotationText").innerHTML = "Please Select an item";
} else {
if (itemSelected === 1) {
document.getElementById("quotationText").innerHTML = "You have 1 item Selected";
} else {
document.getElementById("quotationText").innerHTML = "You have " + itemSelected + " items Selected";
}
}
} else {
var imageMe = $("#" + divId).find('img').attr('src');
document.getElementById('image00').src = imageMe;
setTimeout(function () {
$(".modal-for-image").removeClass("left-modal-image");
}, 100);
}
}

passing parameters to a php from javascript

I've done this before but for some reason the parameters are being passed oddly.
I have a javascript function that I've used to pass parameters, I've ran some tests and in the function the variables are correct.
These are just a few snippets of the js that relate to the issue:
var tdes = document.getElementById("taskDescription1").value;
var tnam = document.getElementById("taskName1").value;
var shif = document.getElementById("shift1").value;
var ttyp = document.getElementById("taskType1").value;
var date = document.getElementById("datepicker").value;
var ooc = document.getElementById("ooc1").value;
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
xmlhttp.open("GET","subTask.php?q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true);
I ran a web console and this is what is actually getting passed...
http://***************/****/********/subTask.php?taskName1=test+taskname+works&taskDescription1=test+des&shift1=All&ooc1=Open&taskType1=normal&datepicker=06%2F28%2F2013
I'm not sure what's going on in between the xmlhttp.open and the GET method in php. None of these variables are getting passed.
Why not use jQuery - very straightforward format (I prefer POST...):
$(document).ready(function() {
var tdes = $("#taskDescription1").val();
var tnam = $("#taskName1").val();
var shif = $("#shift1").val();
var ttyp = $("#taskType1").val();
var date = $("#datepicker").val();
var ooc = $("#ooc1").val();
var dateSplit = date.split('/');
var deadlineDate = "";
for( var i = 0; i < dateSplit.length; i++){
deadlineDate = deadlineDate + dateSplit[i];
}
$.ajax({
type: "POST",
url: "subTask.php",
data: "q="+ encodeURIComponent(tdes) + "&w=" + encodeURIComponent(tnam) +"&e=" +encodeURIComponent(shif) + "&y=" + encodeURIComponent(ttyp) + "&b=" + encodeURIComponent(deadlineDate) + "&u=" + encodeURIComponent(ooc),true),
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END document.ready()
Notice how easy the success callback function is to write... anything returned by subTask.php will be available within that function, as seen by the alert() example.
Just remember to include the jQuery library in the <head> tags:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
Also, add this line to the top of your subTask.php file, to see what is happening:
<?php
$q = $_POST["q"];
$w = $_POST["w"];
die("Value of Q is: " .$q. " and value of W is: " .$w);
The values of q= and w= will be returned to you in an alert box so that (at least) you can see what values they contained when received by subTask.php
Following script should help:
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
var ajax = ajaxObj("POST", "subTask.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
console.log( ajax.responseText )
}
}
ajax.send("u="+tdes+"&e="+tnam+ ...... pass all the other 'n' data );

how to get result from mysql and display using jquery when radio button is clicked?

I would like to make a bus seating plan. I have seating plan chart using javascript function.I have two radio button named Bus_1 and Bus_2 queried from databases. When I clicked one of radio button, I would like to get available seats to show on the seating plan. Problem is I can't write how to carry radio value and to show database result on seating plan. Please help me.
<SCRIPT type="text/javascript">
$(function () {
var settings = { rowCssPrefix: 'row-', colCssPrefix: 'col-', seatWidth: 35, seatHeight: 35, seatCss: 'seat', selectedSeatCss: 'selectedSeat', selectingSeatCss: 'selectingSeat' };
var init = function (reservedSeat) {
var str = [], seatNo, className;
var shaSeat = [1,5,9,13,17,21,25,29,33,37,41,'#',2,6,10,14,18,22,26,30,34,38,42,'#','$','$','$','$','$','$','$','$','$','$',43,'#',3,7,11,15,19,23,27,31,35,39,44,'#',4,8,12,16,20,24,28,32,36,40,45];
var spr=0;
var spc=0;
for (i = 0; i<shaSeat.length; i++) {
if(shaSeat[i]=='#') {
spr++;
spc=0;
}
else if(shaSeat[i]=='$') {
spc++;
}
else {
seatNo = shaSeat[i];
className = settings.seatCss + ' ' + settings.rowCssPrefix + spr.toString() + ' ' + settings.colCssPrefix + spc.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) { className += ' ' + settings.selectedSeatCss; }
str.push('<li class="' + className + '"' +'style="top:' + (spr * settings.seatHeight).toString() + 'px;left:' + (spc * settings.seatWidth).toString() + 'px">' +'<a title="' + seatNo + '">' + seatNo + '</a>' +'</li>');
spc++;
}
}
$('#place').html(str.join(''));
}; //case I: Show from starting //init();
//Case II: If already booked
var bookedSeats = [2,3,4,5]; //**I don't know how to get query result in this array.This is problem for me **
init(bookedSeats);
$('.' + settings.seatCss).click(function () {
// ---- kmh-----
var label = $('#busprice');
var sprice = label.attr('pi');
//---- kmh ----
// var sprice= $("form.ss pri");
if ($(this).hasClass(settings.selectedSeatCss)){ alert('This seat is already reserved'); }
else {
$(this).toggleClass(settings.selectingSeatCss);
//--- sha ---
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
var selSeat = document.getElementById("selectedseat");
selSeat.value = str.join(',');
//var amount = document.getElementById("price");
// amount.value = sprice*str.length;
document.getElementById('price').innerHTML = sprice*str.length;
return true;
}
});
$('#btnShow').click(function () {
var str = [];
$.each($('#place li.' + settings.selectedSeatCss + ' a, #place li.'+ settings.selectingSeatCss + ' a'), function (index, value) {
str.push($(this).attr('title'));
});
alert(str.join(','));
})
$('#btnShowNew').click(function () { // selected seat
var str = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) { item = $(this).attr('title'); str.push(item); });
alert(str.join(','));
})
});
</SCRIPT>
You can use the onclick to tell AJAX to get your information and then what to do with it using jQuery.
<input type="radio" name="radio" onclick="ajaxFunction()" />
function ajaxFunction()
{
$.ajax({
type: "POST",
url: "you_script_page.php",
data: "post_data=posted",
success: function(data) {
//YOUR JQUERY HERE
}
});
}
Data is not needed if you are not passing any variables.
I use jQuery's .load() function to grab in an external php page, with the output from the database on it.
//In your jQuery on the main page (better example below):
$('#divtoloadinto').load('ajax.php?bus=1');
// in the ajax.php page
<?php
if($_GET['bus']==1){
// query database here
$sql = "SELECT * FROM bus_seats WHERE bus = 1";
$qry = mysql_query($sql);
while ($row = mysql_fetch_assoc($qry)) {
// output the results in a div with echo
echo $row['seat_name_field'].'<br />';
// NOTE: .load() takes this HTML and loads it into the other page's div.
}
}
Then, just create a jQuery call like this for each time each radio button is clicked.
$('#radio1').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=1');
}
);
$('#radio2').click(
if($('#radio1').is(':checked')){
$('#divtoloadinto').load('ajax.php?bus=2');
}
);

Categories