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.
Been trying to follow a tutorial:
https://www.udemy.com/json-ajax-data-transfer-to-mysql-database-using-php/
There is a video in section 4: lecture 20
script.js
var output = document.getElementById('output');
output.innerHTML = "";
function submitData(fdata){
var xhttp = new XMLHttpRequest();
xhttp.onload = function(){ console.log(xhttp.responseText);
jData();}
xhttp.open(fdata.method,fdata.action,true);
xhttp.send(new FormData(fdata));
//console.log(fdata.method);
return false;
}
function jData(){
var ajaxhttp = new XMLHttpRequest();
var url ="json.php";
ajaxhttp.open("GET", url, true);
ajaxhttp.setRequestHeader("content-type","application/json");
ajaxhttp.onreadystatechange = function(){
if(ajaxhttp.readyState == 4 && ajaxhttp.status == 200){
var jcontent = JSON.parse(ajaxhttp.responseText);
for (var myObj in jcontent){
output.innerHTML += '<div>' + jcontent[myObj].firstName + ' ' + jcontent[myObj].lastName +
' ' + jcontent[myObj].age + '</div>';
}
console.log(jcontent);
}
}
ajaxhttp.send();
}
I'm not so sure how I am suppose to put the other codes here since it requires a sql command but if ever someone could look at this code. The code is suppose to display the data and every time I insert a new data. It's suppose to display the new data at the bottom however the code does it displays all the data over and over again.
Can someone explain why this is happening?
I am creating a form where the user selects check boxes of "services" that they might be interested in, then the form gets emailed to me. The problem is weather a box is checked or not, all of the results are being filled in. How do I properly do this?
There are about 25, but here is just a few:
$services = array();
if($_POST['master_planning']) {$services[] = "Master planning";}
if($_POST['snow_plowing']) {$services[] = "Snow plowing";}
if($_POST['fine_gardening']) {$services[] = "Fine Gardening";}
if($_POST['deer_protection']) {$services[] = "Deer Protection";}
$interested = implode(", ", $services);
I know it is a very basic thing, but I can't seem to solve it on my own
HTML is like:
<li><label for="planting"><input type="checkbox" name="planting" id="planting" value="x" /> Planting</label></li>
Ok, I figured (I think) out why all the values are returning true, even if the checkboxes arent clicked, now how do I solve it....
I guess I should of mentioned that this is page 2 of the form (process.php), the actual form is index.php, and I am using an ajax script to pass values.
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var name = $('input[name=name]');
var phone = $('input[name=phone]');
var email = $('input[name=email]');
var master_plan = $('input[name=master_plan]');
var front_foundation = $('input[name=front_foundation]');
var backyard_plan = $('input[name=backyard_plan]');
var specialty_garden = $('input[name=specialty_garden]');
var lawn_cutting = $('input[name=lawn_cutting]');
var lawn_plant_health_care = $('input[name=lawn_plant_health_care]');
var organic_property_care = $('input[name=organic_property_care]');
var seasonal_clean_ups = $('input[name=seasonal_clean_ups]');
var pruning = $('input[name=pruning]');
var fine_gardening = $('input[name=fine_gardening]');
var deer_protection = $('input[name=deer_protection]');
var snow_plowing = $('input[name=snow_plowing]');
var planting = $('input[name=planting]');
var walk = $('input[name=walk]');
var terrace = $('input[name=terrace]');
var wall = $('input[name=wall]');
var outdoor_kitchen = $('input[name=outdoor_kitchen]');
var fireplace = $('input[name=fireplace]');
var driveway = $('input[name=driveway]');
var fencing = $('input[name=fencing]');
var pergola = $('input[name=pergola]');
var swimming_pool = $('input[name=swimming_pool]');
var irrigation = $('input[name=irrigation]');
var lighting = $('input[name=lighting]');
var grading_drainage = $('input[name=grading_drainage]');
var newsletter = $('input[name=newsletter]');
var comments = $('textarea[name=comments]');
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
var data =
'name=' + name.val() +
'&phone=' + phone.val() +
'&email=' + email.val() +
'&master_plan=' + master_plan.val()+
'&front_foundation=' + front_foundation.val()+
'&backyard_plan=' + backyard_plan.val()+
'&specialty_garden=' + specialty_garden.val()+
'&lawn_cutting=' + lawn_cutting.val()+
'&lawn_plant_health_care=' + lawn_plant_health_care.val()+
'&organic_property_care=' + organic_property_care.val()+
'&seasional_clean_ups=' + seasional_clean_ups.val()+
'&pruning=' + pruning.val()+
'&fine_gardening=' + fine_gardening.val()+
'&deer_protection=' + deer_protection.val()+
'&snow_plowing=' + snow_plowing.val()+
'&planting=' + planting.val()+
'&walk=' + walk.val()+
'&terrace=' + terrace.val()+
'&wall=' + wall.val()+
'&outdoor_kitchen=' + outdoor_kitchen.val()+
'&fireplace=' + fireplace.val()+
'&driveway=' + driveway.val()+
'&fencing=' + fencing.val()+
'&pergola=' + pergola.val()+
'&swimming_pool=' + swimming_pool.val()+
'&irrigation=' + irrigation.val()+
'&lighting=' + lighting.val()+
'&grading_drainage=' + grading_drainage.val()+
'&newsletter=' + newsletter.val() +
'&comments=' + encodeURIComponent(comments.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
if (html==1) {
$('.form').fadeOut('slow');
$('.done').fadeIn('slow');
} else alert('Sorry, unexpected error. Please try again later.');
}
});
return false;
});
});
</script>
Could this be why every result is displaying?
The check you have is incorrect. Lets assume you have this HTML code for the checkbox inside your form:
<input type="checkbox" name="master_planning" value="yes" />
Then on your PHP you want do the check like this:
if(isset($_POST['master_planning']) && $_POST['master_planning'] == 'yes'){
array_push($services, "Master planning"];
}
The function array_push adds the given element or elements at the end of the array, so that would be an easy way to "dynamically" populates an array.
below is my code for uploading files using XMLHttpRequest send method
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
xhr.onreadystatechange = function()
{
if(xhr.status == 200 && xhr.readyState == 4){
on_upload_complete( filename,id,xhr);
}
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr.open("POST", queryString, true);
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(file);
}
With the above function i wait for on_upload_complete to get called and then pass the second file object and one by one i am uploading. Can someone suggest how can i make it upload simultaneously i tried doing this below as
var xhr = Array();
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
xhr[filename] = new XMLHttpRequest();
xhr[filename].upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
xhr[filename].onreadystatechange = function()
{
if(xhr[filename].status == 200 && xhr[filename].readyState == 4){
on_upload_complete( filename,id,xhr);
}
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr[filename].open("POST", queryString, true);
xhr[filename].setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr[filename].setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr[filename].setRequestHeader("Content-Type", "application/octet-stream");
xhr[filename].send(file);
}
by doing this i xhr[filename] inside onreadystatechange is undefined because of loop and i want to keep track of every file upload progress and finish it . But as you can see the problem is only keeping track of onreadystatechange with a unique id and i am stuck here. Please can anyone throw light , suggestions and recommendations help is appreciated. thanks
You have deal with Javascript Closure. onreadystatechange see filename,id,xhr of the lastest invoke of send_file_to_server function. To change this rewrite your function like this:
var xhr = Array();
function send_file_to_server(file,id)
{
console.log('send_file_to_server id received = ' + id);
var filename = file.name;
var container_name = $("#gs-file-upload-container").find(':selected').text();
xhr[filename] = new XMLHttpRequest();
xhr[filename].upload.onprogress = function(e)
{
console.log(' bytes loaded = '+e.loaded + ' remaining = ' + e.total);
}
(function(localFilename, localId, localXhr){
localXhr[localFilename].onreadystatechange = function(){
if(localXhr[localFilename].status == 200 && localXhr[localFilename].readyState == 4){
on_upload_complete(localFilename, localId, localXhr);
}
}
})( filename,id,xhr)
var queryString = 'http://upload_files?filename='+filename+'&cname='+container_name;
xhr[filename].open("POST", queryString, true);
xhr[filename].setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr[filename].setRequestHeader("X-File-Name", encodeURIComponent(filename));
xhr[filename].setRequestHeader("Content-Type", "application/octet-stream");
xhr[filename].send(file);
}
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');
}
);