I am using an 'infinite scroll' script that keeps sending requests to the database even when there are no more records. When that happens, it reloads the last set on the page. I would like for the function to stop running when it reaches the last record on the database. I'm new to JS so this is a bit difficult for me to troubleshoot, also, I'm not using jQuery. I am doing most of the work in the PHP script.
I've been reading a lot of posts in here about 'infinite scroll' and I am unable to get how other people check the limits in JS.
JavaScript
function loadPosts(){
var target = document.getElementById('PostsContainer');
var contentHeight = target.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if(y >= contentHeight){
var xhr = ajaxObj("POST", "loadContent.php");
xhr.onload = function(){
target.innerHTML += xhr.responseText;
}
xhr.send("action=loadMore");
}
}
window.onscroll = loadPosts;
PHP
$sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC LIMIT 2" //Original content on page
$totalPosts = 12; (query to DB)
$max = 1;
$current = 2; //Start on record after initial content
while($current < $totalPosts){
$sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC
LIMIT $current, $max";
$result = $db_link->query($sql);
$posts_list += ... //Collect the data from DB
$current++;
}
echo $posts_list;
No matter how many times I keep scrolling the new content keeps loading even after I run out of records in the DB. Output keeps repeating every single time I get to the bottom of the page. In this case I have 7 posts in the DB I start with 7, 6... then I keep getting posts 5-1.
So in this case what you can do,
just add one parameter in json, from php or server side which will tell, is data present or not, based on that, you can stop calling loadPosts function
so basically Algorithm be like,
...php
while($current < $totalPosts){
......................
......................
if($current >= $totalPosts)
{
$getNext = False;
}
else
{
$getNext = True;
}
}
...javasrcipt
function loadPosts(){
if(!getNext)
return false;
else
{
......................
......................
}
}
window.onscroll = loadPosts;
Hope this strategy will help you
I have a scenario where user uploads multiple files using HTML5 DnD and file API, sends data to the server using xmlhttprequest . To feedback users about file status my code creates prograss bar elements dynamically using javascript for each file.
below is my code which does that
for(var i=0;i< files.length;i++)
{
var row = tbl.insertRow(i);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
arr[i]=i;
cell1.innerHTML=files[i].name;
cell2.innerHTML=(Math.round(files[i].size/1024)==0?(files[i].size>0?1:0):(Math.round(files[i].size/1024)))+" KB";
cell3.innerHTML=" "+"<progress id=progress"+i+" max=100></progress>";
var theForm=document.forms["DocumentForm"];
var theDupe="progress"+i;
xhr[i]=new XMLHttpRequest(); // this is an array, bcoz of multiple files
xhr[i].upload.addEventListener("progress", function(evt ){ var theForm=document.forms["DocumentForm"]; var bar=document.getElementById(theDupe); if (evt.lengthComputable) { var currentValue=bar.value; var percentComplete = Math.round(evt.loaded * 100 / evt.total); bar.value=currentValue+parseInt(percentComplete); } }, false);
xhr[i].open('POST',url);
xhr[i].send(data);
right now only one progress bar gets updated, how can i update multiple progress bar the same time ?
I have quite a script that adds items into a table. I need to pull information from a MySQL database based on the UPC that is passed through the JavaScript.
I tried: document.write("<?php echo '375'; ?>"); just to see if it would work, and once the script got to that line, the page refreshed and displayed a blank white page.
The full JavaScript is below:
//setup before functions
var field = document.getElementById("UPC");
var typingTimer; //timer identifier
var doneTypingInterval = 1000; //time in ms, 1 seconds
//on keyup, start the countdown
$('#UPC').keyup(function(){
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#UPC').keydown(function(){
clearTimeout(typingTimer);
});
function doneTyping () {
//user is "finished typing," do something
if (field.value.length != 0) {
document.getElementById("noScan").className="hidden";
document.getElementById("checkout").className="";
document.getElementById("void").className="";
var upc=document.getElementById("UPC").value;
var price = document.write("<?php echo '375'; ?>");
var weight = parseInt(document.getElementById("weight").value);
var table=document.getElementById("ScannedItems");
var total = weight * price;
var row=table.insertRow(-1);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
var cell4=row.insertCell(3);
var cell5=row.insertCell(4);
var cell6=row.insertCell(5);
cell1.innerHTML=upc;
cell2.innerHTML="Example Description";
cell3.innerHTML = "$" + price.toFixed(2);
cell4.innerHTML = weight + " lbs";
cell5.innerHTML = "$" + total.toFixed(2);
cell5.setAttribute('data-total', total); // caches the total into data
cell6.innerHTML="<a class='add'><span class='glyphicon glyphicon-plus' style='padding-right:15px;'></span></a><a class='delete'><span class='glyphicon glyphicon-minus'></span></a>";
field.value ='';
var total = cell5.getAttribute('data-total');
var salesTax = Math.round(((total / 100) * 8.25)*100)/100;
var totalAmount = (total*1) + (salesTax * 1);
document.getElementById('displaysubtotal').innerHTML="$" + (Math.floor(total * 100) / 100).toFixed(2);
document.getElementById('displaytax').innerHTML="$" + salesTax;
document.getElementById('displaytotal').innerHTML="$" + totalAmount;
}
}
// Duplicate a scanned item
var $table = $('#ScannedItems');
$('#ScannedItems').on('click', '.add', function () {
var $tr = $(this).closest('tr').clone();
$table.append($tr);
});
// Remove a line item
var $table = $('#ScannedItems');
$('#ScannedItems').on('click', '.delete', function () {
var $tr = $(this).closest('tr').remove();
});
I must figure out how to get information from my database for this project or it is going to fail.
Javascript executes on the client side, PHP executes on the server side. So PHP is done executing before JS starts.
So in order to fetch new data, you'll need to initiate a call to your server. You can do this by either refreshing the page with the results you need or by creating an AJAX call.
To make it more clear, take a closer look at the example you gave. View the source code in your browser. It will come out as document.write("375");. That's because PHP echo'ed the string '375' into your JS code on the server side before sending the page to the browser (which is where the JS code executes).
PHP can generate JS code, but JS cannot generate PHP code (in the usual sense).
PHP is executed on the server before serving generate HTML to a clients browser. Any PHP code inserted by the javascript on the client will not run.
If you want to have code inserted dynamically from PHP, you might investigate how to use AJAX calls to run a separate PHP server-side script and insert the returned content.
You can perfectly use php inside javascript, because php executes before javascript reachs the browser. So the browser receives the page with the php result executed which builds the javascript sentence... the browser doesnt know that the javascript sentence was writen by you or by the php server.
document.write("<?php echo '375'; ?>");
try changing it to...
document.write("<?php echo("375"); ?>");
the "" are first seen by php server so the above should work.
or just in case you can escape the "
I also have this piece of code fully functional:
frameDoc.document.write sentence
<?php
echo("frameDoc.document.write(\"");
require('secciones/seccion_head2.html');
echo("\");");
?>
frameDoc.document.write sentence
BUT!!! inside the required html you cant use more than one line!!!!
Solution:
I used setTimeout(ajaxcall,timeoutmillis) instead of making all ajax calls instantly.
The images were updated perfectly. No problem.
Never send multiple ajax request in a loop without giving browser some time to breathe.
:)
I am uploading multiple images to Google App Engine using javascript. I am sending images
one by one to the server and receiving responses from server one by one. The response
contains thumbnail link of the loaded image. I want to be able to display those thumbnails as they come one by one. The problem is that for example if I have 100 images the images are not displayed until 100th response is received from the server. Till then the page behaves as if it is loading something but images are not visible. All the images show up after the Ajax call is complete though.
Update: I have found not so elegant workaround. If you create image placeholders with
some dummy image and change the img src later during ajax load, it works. Not very elegant solution but if you add 1 pixel invisible image the effect will be more or less the same.
Here is the code.
this.handlephotoupload = function(input) {
var uploadedfiles = input.files;
var toolarge = "";
var maxsize = 10240000;
var counter = 1;
var downloadcounter = 0;
var rownumber = 0;
var images=new Array();
var arraycount=0;
var totalimagecount=0;
$("#phototable").append("<tr><td><div id=loading>Loading images please wait......</div></td></tr>");
for(var i = 0; i < uploadedfiles.length; i++) {
if(uploadedfiles[i].size > maxsize) {
toolarge += uploadedfiles[i].name + "\n";
totalimagecount+=1;
} else {
var filedata = new FormData();
filedata.append("uploadimage", uploadedfiles[i]);
$("#loading").show();
$.ajax({
url : 'photodownloader',
data : filedata,
cache : false,
contentType : false,
processData : false,
type : 'POST',
success : function(receiveddata) {
var imagedata = JSON.parse(receiveddata);
var data = imagedata['imageinfo'];
var imagelink = data['imagelink'];
var thumbnaillink = data['thumbnailLink'];
var imageID = data['uniqueID'];
var imagename = data['imagename'];
if(downloadcounter % 3 == 0) {
rownumber += 1;
var row = $('<tr id=thumbnailsrow' + rownumber + '></tr>');
$("#phototable").append(row);
} else {
var row = $("#thumbnailsrow" + rownumber);
}
//images[arraycount++]'<td><a href=' + imagelink + '><img src=' + thumbnaillink + '/></a></td>')
var curid="imgload"+downloadcounter;
//$("#loadimg").append("<div id="+curid+"></div>");
//$("#loadimg").append("<img src="+thumbnaillink+"></img>");
//$("#"+curid).hide();
//$("#"+curid).load(thumbnaillink);
$(row).append('<td align=center><a href=' + imagelink + '><img src=' + thumbnaillink + '/></a></td>');
//$("#"+curid).remove();
downloadcounter+=1;
totalimagecount+=1;
if(totalimagecount==uploadedfiles.length){
$("#loading").hide();
}
}
});
}
}
if(toolarge != "") {
alert("These images were not uploaded due to size limit of 1MB\n" + toolarge);
}
}
If you want separate responses, you have to make separate requests.
Don't asynchronously fire 100 requests at once though, just fire X and hold a counter that you check with a timer. Each time you receive a response you decrease that counter and each time the timer hits you can simply fire X - counter requests. That way you only have X simultaneous requests at a time...
I'm pretty new to javascript, and therein probably lies my problem. I'm trying to track AdWords conversions that occur within a widget on our site. The user fills in a form and the result from the widget is published in the same div without a page refresh. The issue I'm having is when I try to appendChild (or append in jQuery) both script elements in Google's code (shown below) the page gets 302 redirected to a blank Google page (or at least that's what it looks like through FireBug).
I'm able to provide a callback method for the results of the form, and that's where I'm trying to insert the AdWords tracking code. For reference, this is the code provided by Google:
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 993834405;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "bSpUCOP9iAIQpevy2QM";
/* ]]> */
</script>
<script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/993834405/?label=bSpUCOP9iAIQpevy2QM&guid=ON&script=0"/>
</div>
</noscript>
Pretty standard stuff. So, what I'm trying to do is insert this into the results page using the callback method (which is provided). Frankly, I'm redirected no matter when I try to insert this code using js or jQuery (either on original page load or in the callback) so maybe the callback bit is irrelevant, but it's why I'm not just pasting it into the page's code.
I've tried a number of different ways to do this, but here's what I currently have (excuse the sloppiness. Just trying to hack my way through this at the moment!):
function matchResultsCallback(data){
var scriptTag = document.createElement('script');
scriptTag.type = "text/javascript";
scriptTag.text = scriptTag.text + "/* <![CDATA[ */\n";
scriptTag.text = scriptTag.text + "var google_conversion_id \= 993834405\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_language \= \"en\"\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_format \= \"3\"\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_color \= \"ffffff\"\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_label \= \"bSpUCOP9iAIQpevy2QM\"\;\n";
scriptTag.text = scriptTag.text + "/* ]]> */\n";
$('body').append(scriptTag);
$('body').append("<script type\=\"text\/javascript\" src\=\"http://www.googleadservices.com/pagead/conversion.js\" />");
//I have also tried this bit above using the same method as 'scriptTag' with no luck, this is just the most recent iteration.
var scriptTag2 = document.createElement('noscript');
var imgTag = document.createElement('img');
imgTag.height = 1;
imgTag.width = 1;
imgTag.border = 0;
imgTag.src = "http://www.googleadservices.com/pagead/conversion/993834405/?label=bSpUCOP9iAIQpevy2QM&guid=ON&script=0";
$('body').append(scriptTag2);
$('noscript').append(imgTag);
}
The really odd thing is that when I only insert one of the script tags (it doesn't matter which one), it doesn't redirect. It only redirects when I try to insert both of them.
I've also tried putting the first script tag into the original page code (as it's not making any calls anywhere, it's just setting variables) and just inserting the conversions.js file and it still does the redirect.
If it's relevant I'm using Firefox 3.6.13, and have tried the included code with both jQuery 1.3 and 1.5 (after realizing we were using v1.3).
I know I'm missing something! Any suggestions?
Nowadays it is convenient to use the Asynchronous Tag at http://www.googleadservices.com/pagead/conversion_async.js that exposes the window.google_trackConversion function.
This function can be used at any time. For example after submitting a form, like in your case.
See https://developers.google.com/adwords-remarketing-tag/asynchronous/
Update 2018
Situation changed and it seems that you have more options now with the gtag.js: https://developers.google.com/adwords-remarketing-tag/
If you're using jQuery in your pages, why don't you use the getScript method of the same to poll the conversion tracking script after setting the required variables?
This is what I usually do, once I've received a success response from my AJAX calls.
var google_conversion_id = <Your ID Here>;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "<Your Label here>";
var google_conversion_value = 0;
if (100) {
google_conversion_value = <Your value here if any>;
}
$jQ.getScript( "http://www.googleadservices.com/pagead/conversion.js" );
This works just fine for me. If you want a more detailed example:
$.ajax({
async: true,
type: "POST",
dataType: "json",
url: <Your URL>,
data: _data,
success: function( json ) {
// Do something
// ...
// Track conversion
var google_conversion_id = <Your ID Here>;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "<Your Label here>";
var google_conversion_value = 0;
if (100) {
google_conversion_value = <Your value here if any>;
}
$.getScript( "http://www.googleadservices.com/pagead/conversion.js" );
} // success
});
If you use other libraries such as Mootools or Prototype, I'm sure they have similar in-built methods. This AFAIK is one of the cleanest approaches.
this simple code worked for me (the $.getScript version didn't).
var image = new Image(1,1);
image.src = 'http://www.googleadservices.com/pagead/conversion/' + id + '/?label=' + label + ' &guid=ON&script=0';
// This takes care of it for jQuery. Code can be easily adapted for other javascript libraries:
function googleTrackingPixel() {
// set google variables as globals
window.google_conversion_id = 1117861175
window.google_conversion_language = "en"
window.google_conversion_format = "3"
window.google_conversion_color = "ffffff"
window.google_conversion_label = "Ll49CJnRpgUQ9-at5QM"
window.google_conversion_value = 0
var oldDocWrite = document.write // save old doc write
document.write = function(node){ // change doc write to be friendlier, temporary
$("body").append(node)
}
$.getScript("http://www.googleadservices.com/pagead/conversion.js", function() {
setTimeout(function() { // let the above script run, then replace doc.write
document.write = oldDocWrite
}, 100)
})
}
// and you would call it in your script on the event like so:
$("button").click( function() {
googleTrackingPixel()
})
In your Adwords account - if you change the conversion tracking event to "Click" instead of "Page Load" it will provide you with code that creates a function. It creates a snippet like this:
<!-- Google Code for Developer Contact Form Conversion Page
In your html page, add the snippet and call
goog_report_conversion when someone clicks on the
chosen link or button. -->
<script type="text/javascript">
/* <![CDATA[ */
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = <Your ID Here>;
w.google_conversion_label = "<Your value here if any>";
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
window.google_is_call = true;
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
/* ]]> */
</script>
<script type="text/javascript"
src="//www.googleadservices.com/pagead/conversion_async.js">
</script>
Then in your code you just call:
goog_report_conversion();
Or for a link or image click:
click here
After trying everything the link Funka provided (http://articles.adamwrobel.com/2010/12/23/trigger-adwords-conversion-on-javascript-event) was what worked for me. Like he said it's scary to overwrite document.write, but
It seems like this is what you have to do unless you can load the script before the page load.
Since the script uses document.write so it needs to be re-written
document.write = function(node){ // exactly what document.write should of been doing..
$("body").append(node);
}
window.google_tag_params = {
prodid: pageId,
pagetype: pageTypes[pageType] || "",
value: "234324342"
};
window.google_conversion_id = 2324849237;
window.google_conversion_label = "u38234j32423j432kj4";
window.google_custom_params = window.google_tag_params;
window.google_remarketing_only = true;
$.getScript("http://www.googleadservices.com/pagead/conversion.js")
.done(function() {
// script is loaded.
});
See https://gist.github.com/c7a316972128250d278c
As you have seen, the google conversion tag only calls on a redraw. I had to make sure it was called when a part of a page was redrawn. (Due to some bad website design that I could not fix at the moment.) So I wrote a function to call from an onClick event.
Essentially, all you have to do is to call doConversion();
Here is what we ended up with:
// gothelp from from http://www.ewanheming.com/2012/01/web-analytics/website-tracking/adwords-page-event-conversion-tracking
var Goal = function(id, label, value, url) {
this.id = id;
this.label = label;
this.value = value;
this.url = url;
};
function trackAdWordsConversion(goal, callback) {
// Create an image
var img = document.createElement("img");
// An optional callback function to run follow up processed after the conversion has been tracked
if(callback && typeof callback === "function") {
img.onload = callback;
}
// Construct the tracking beacon using the goal parameters
var trackingUrl = "http://www.googleadservices.com/pagead/conversion/"+goal.id;
trackingUrl += "/?random="+new Date().getMilliseconds();
trackingUrl += "&value="+goal.value;
trackingUrl += "&label="+goal.label;
trackingUrl += "&guid=ON&script=0&url="+encodeURI(goal.url);
img.src = trackingUrl;
// Add the image to the page
document.body.appendChild(img);
// Don't display the image
img.style = "display: none;";
}
function linkClick(link, goal) {
try {
// A function to redirect the user after the conversion event has been sent
var linkClickCallback = function() {
window.location = link.href;
};
// Track the conversion
trackAdWordsConversion(goal, linkClickCallback);
// Don't keep the user waiting too long in case there are problems
setTimeout(linkClickCallback, 1000);
// Stop the default link click
return false;
} catch(err) {
// Ensure the user is still redirected if there's an unexpected error in the code
return true;
}
}
function doConversion() {
var g = new Goal(YOUR CODE,YOUR_COOKIE,0.0,location.href);
return linkClick(this,g);
}
I tried all the ways to manually include conversion.js, it all loaded the script, but didn't further execute what we needed inside the script, there's a simple solution.
Just put your conversion code in a separate HTML, and load it in an iframe.
I found code to do that at http://www.benjaminkim.com/ that seemed to work well.
function ppcconversion() {
var iframe = document.createElement('iframe');
iframe.style.width = '0px';
iframe.style.height = '0px';
document.body.appendChild(iframe);
iframe.src = '/track.html'; // put URL to tracking code here.
};
then just call ppcconversion() wherever in the JS you like to record it.
All I do is return the code (or in our case, an image) along with the "success" message in the callback.
When a contact form is submitted, or a registration form filled out and submitted, we post to a php script using jQuery, then output a "thank-you" message to a div:
"$first_name, Thanks for requesting more information. A representative will contact you shortly."
... followed by the 1x1 gif Google provides.
Here's the jQuery:
$.post('script.php',{'first_name':first_name,'last_name':last_name,'email':email,'phone1':phone1,'password':password,},function(data){
var result=data.split("|");
if(result[0] ==='success'){
$('#return').html(result[1] + $result[2]);
And the php...
echo 'success|'.$first_name.', Thanks for requesting more information.
A representative will contact you shortly.|<img height="1" width="1" alt="" src="http://www.googleadservices.com/pagead/conversion/xxxxxxxx/imp.gif?value=0&label=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&script=0"/>';
You might need to throw in a "document.location.reload();" if it isn't being picked up by google
For anyone still looking for a good solution to this, Google supports AJAX Conversions natively now through their Google Analytics API.
You can do it by making a event API call in Google Analytics. What you do is setup an Analytics event, tie it to a goal, then import that goal into AdWords as a conversion. It's a bit of a lengthy process but it's a clean solution.
Check out This Page for a tutorial
This works for me:
window.google_trackConversion({
google_conversion_id: 000000000,
conversion_label : "xxxxxxxxxxxx",
google_remarketing_only: false,
onload_callback : function(){
//do something :)
}
});