How to properly showing progressbar with ajax php and mysql - php

I am trying to query a large data from the database and I wish to display a progress bar. The code below returns data info from the server but the progress bar just jumps to 100% while the Ajax is still querying data.
I guess the proper way is to fake the progress bar timer or possibly make a timely ajax call eg per seconds to update the progress bar. Can someone help me out with my issue? Thanks
Below is the working code so far
<html>
<head>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
function pf(event) {
if (event.lengthComputable) {
var percentComplete = Math.round((event.loaded/event.total)*100);
$(".progressbar").width(percentComplete + '%');
$(".progressbar").html('<span>' + percentComplete +' %</span>')
$(".progressbar").html('<span> ' + percentComplete +'% Completed</span>')
}
};
$("#sForm").on('submit',(function(e) {
e.preventDefault();
$('.progressbar').css('width', '0');
$.ajax({
url: "qdata.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", pf, false);
return xhr;
},
success: function(data)
{
if(data.trim() == "good"){
alert('completed now');
}
},
error: function()
{
}
});
}));
});
</script>
</head>
<body>
<div class="progressbar"></div>
<form id="sForm" action="qdata.php" method="post">
<div id="resultdata"></div>
<input type="submit" value="Submit now" />
</form>
</body>
</html>
qdata.php
// This is just sample db
//dbconfig.php
$result = $db->prepare('SELECT fullname FROM users');
$result->execute(array());
$count = $result->rowCount();
while ($row = $result->fetch()) {
$name=htmlentities($row['fullname'], ENT_QUOTES, "UTF-8");
}
echo 'good';

you can show percentage of progress in xhr as
xhr: function () {
//upload Progress
var xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//update progressbar
console.log('percent', percent);
$('.progressbar').css("width", percent + '%');
}, true);
}
return xhr;
},

Related

Passing a HTML variable to PHP File

I have the following in my HTML file:
<div class="panel-body panel-refine">
<span id="price-left" class="price-left pull-left" data-currency="€">500</span>
<span id="price-right" class="price-right pull-right" data-currency="€">5000</span>
<div class="clearfix"></div>
The variable price-left and 'price-right' comes from a JavaScript slider.
$(document).ready(function(){
var slider2 = document.getElementById('sliderRefine');
noUiSlider.create(slider2, {
start: [2000, 3000],
connect: true,
range: {
'min': [30],
'max': [5000]
}
});
var limitFieldMin = document.getElementById('price-left');
var limitFieldMax = document.getElementById('price-right');
var xhr;
slider2.noUiSlider.on('update', function( values, handle ){
if (handle){
limitFieldMax.innerHTML= $('#price-right').data('currency') + Math.round(values[handle]);
document.getElementById("hoogsteprijs").innerHTML = Math.round(values[handle]);
} else {
limitFieldMin.innerHTML= $('#price-left').data('currency') + Math.round(values[handle]);
document.getElementById("laagsteprijs").innerHTML = Math.round(values[handle]);
}
// Abort the previous asynchronous ajax call in case it hasn't finished loading
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: 'search.php',
type: 'GET',
data:{
minPrice: document.getElementById("laagsteprijs").innerHTML,
maxPrice: document.getElementById("hoogsteprijs").innerHTML
},
success:function(response){
// do something with response from search.php
}
});
});
});
I like to pass "laagsteprijs" and "hoogsteprijs" to a search.php file that I call in a HTML file with the folowing:
<iframe width="100%" height="720" src="search.php?q=category%3AFietsen&page=1&sort=priceAsc&minPrice="laagsteprijs"&maxPrice="hoogsteprijs"" style="border:none;"></iframe>
Use jQuery $.ajax function to pass data to your search.php script for every slider update:
var xhr;
slider2.noUiSlider.on('update', function( values, handle ){
if (handle){
limitFieldMax.innerHTML= $('#price-right').data('currency') + Math.round(values[handle]);
document.getElementById("hoogsteprijs").innerHTML = Math.round(values[handle]);
} else {
limitFieldMin.innerHTML= $('#price-left').data('currency') + Math.round(values[handle]);
document.getElementById("laagsteprijs").innerHTML = Math.round(values[handle]);
}
// Abort the previous asynchronous ajax call in case it hasn't finished loading
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: 'search.php',
type: 'GET',
data:{
minPrice: document.getElementById("laagsteprijs").innerHTML,
maxPrice: document.getElementById("hoogsteprijs").innerHTML
},
success:function(response){
// do something with response from search.php
}
});
});

PHP Streaming and jQuery

What is the best way to display or deal with a large result on success while waiting for PHPto render that result. I would like to use jQuery to submit a form, have PHP process it, and give output/feedback to users while they wait (either in a div or an iframe...in the example below I use an iframe).
I have the backbone of the xhr version that I found online, but I was wondering if there is a better way (I am aware that there is jquery mixed into this:
function submitForm(){
$('#report_iframe').attr('src','/tests/stream_ajax/blank_iframe.php');
$("#report_modal").modal({backdrop: "static"});
count=1;
xhr = new XMLHttpRequest();
xhr.open("GET", "/folder/ajax_result.php", true);
xhr.onprogress = function(e) {
count = count +1;
$( "#report_iframe" ).contents().find( "#content_loader" ).text('this is jquery count' + count);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
//console.log("Complete = " + xhr.responseText);
// alert("complete");
document.getElementById("report_iframe").srcdoc=xhr.responseText;
}
}
xhr.send();
};
Any help appreciated. Thanks.
J Doyle
Anyway you are using JQuery. Why don't you use JQuery ajax ?
$.ajax({
cache: false,
async: true,
type: "GET",
url: '/folder/ajax_result.php',
beforeSend:function()
{
count = count +1;
},
success:function(response)
{
document.getElementById("report_iframe").srcdoc=response;
}
});
I agree with #Nandan, you should use JQuery Ajax, now for the part of the progress feedback you should add an EventListener for the xhr object and display it in your frame, it would be something like this:
$.ajax({
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Download progress
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var count = evt.loaded / evt.total;
$("#content_loader").html('this is jquery count ' + count*100);
}
}, false);
return xhr;
},
type: 'GET',
url: "/folder/ajax_result.php",
data: {},
success: function(data){
//Do something
}
});
For a better explanation and more information:
Click here
Or here
UPDATE:
You could also try something like this, it works well for download progress
$.ajax({
type: 'GET',
url: "/folder/ajax_result.php",
data: {},
xhrFields: {
onprogress: function (e) {
if (e.lengthComputable) {
$("#content_loader").text("this is jquery count " + e.loaded / e.total * 100 + "%");
}
}
},
success: function(data){
//Do something
}
});

Show progress on Jquery ajax call for sending multiple email

I'm using ajax to send a single email to all my clients (example before christmas).
Here's the ajax script
$(function () {
$("#mktg_submit").on("click",function( event ) {
event.preventDefault();
console.log($("#mktg").serialize());
$("#mktg_esito").empty();
$("#mktg_esito").append("<img src='images/loading.gif' alt=loading title=loading />");
$.ajax({
type : 'POST',
url : 'json/mktg.php',
data : $("#mktg").serialize(),
dataType : 'json',
encode : true
})
.done(function(data) {
$( "#mktg_esito" ).empty();
console.log(data);
if ((data)["success"]===false) {
$( "#mktg_esito" ).append("<div class='alert alert-danger'>"+(data)["errors"]+"</div>");
} else {
$("#mktg_esito").append("<div class='alert alert-success' id='mktg_mess'><strong>Ben fatto!</strong> Email inviate correttamente.</div>");
$.each((data)["email"], function( i, val ) {
$( "#mktg_esito" ).append("<p>Email inviata a: <b>"+val+"</b></p>");
});
}
$("#mktg_mess").show().delay(1000).fadeOut();
});
});
});
Whith this I only see the loading image when the script was launched and I see the result only when all finish. When I send 1.000 email I can't see the progress of the work, can anyone help me to use the best way to see the progress of the sending?
Use the xhr object and attach an event listener to the progress event. See the reference
Add a div progress to your html
<div class="progress"></div>
<style>
.progress {
width: 0;
height: 4px;
background: black;
transition: width .3s linear;
}
</style>
Then change your ajax request with something like this :
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
$('.progress').css({
width: percentComplete * 100 + '%'
});
if (percentComplete === 1) {
$('.progress').fadeOut();
}
}
}, false);
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
console.log(percentComplete);
$('.progress').css({
width: percentComplete * 100 + '%'
});
}
}, false);
return xhr;
},
type: 'POST',
url: "your-url",
data: data,
success: function (data) {}
});

My chat website(php+ajax) makes my browser stuck

This is the script I use for various purposes like scrolling, getting the data from php etc:
<script>
$(document).ready(function(){
$("#full_chat").animate({ scrollTop: $('#full_chat')[0].scrollHeight+1000}, 1500);
setInterval(function refreshPage() {
var user=$("#head").text();
$.post("retrieve.php",{ user:user }, function(data,status){
if($.trim(data)!="0"){
$("#full_chat").append("<span class='you'>"+data+"</span>");
$('#full_chat').emoticonize();
window.onblur = function () {
$('#full_chat').bind("DOMSubtreeModified",function(){
$.titleAlert("New Message!", {
requireBlur:true,
stopOnFocus:true,
//duration:10000,
//interval:500
});
});
}
}
}); }, 1500);
$("#form").on('submit',function (e) {
e.preventDefault();
var user=$("#head").text();
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
var txt= $("#chat_input").val();
$.post("chat.php",{ txt:txt,user:user,time:time },function(data,status){
if(data=="OFFLINE"){
$("#full_chat").append("User not available right now<br>");
}else{
$("#full_chat").append("("+time+") ").append("<span class='me'>"+"Me: "+txt+"</span><br>").emoticonize({delay: 1,animate:false});
}
});
$("#full_chat").animate({ scrollTop: $('#full_chat')[0].scrollHeight+1000}, 1500);
$('#chat_input').val('');
});
});
</script>
This is the PHP code I use to get the chats from database:
<?php
session_start();
$other_user=$_POST['user'];
$flag=$_POST['flag'];
include_once('db.php');
$uname=$_SESSION['username'];
//date_default_timezone_set('Asia/Kolkata');
$q="select message,sender,time from chat where username='$uname' and delivered=0 and sender='$other_user' order by time ASC";
$qe = mysqli_query($con,$q);
$q1="UPDATE chat SET delivered=1 WHERE username='$uname' and sender='$other_user'" ;
$qe1 = mysqli_query($con,$q1);
if($r=mysqli_fetch_array($qe)) {
echo "(".$r['2'].") ". $r['1'].": ".$r['0']."<br>";
}else {
echo "0";
}
mysqli_close($con);
?>
What may be the reason for the problem? Is it the page refresh that happens every 1.5 seconds or something else?
This is just to give you an idea, it is not tested.
<script>
$(document).ready(function() {
var user = $("#head").text();
var postTimeout = 0;
var refreshPage = function(postInterval, postData) {
$.post("retrieve.php", postData, function(data, status) {
if (!postTimeout) {
postTimeout = setTimeout(function() {
refreshPage(postInterval, postData);
postTimeout = 0;
}, postInterval);
}
if ($.trim(data) != "0") {
$("#full_chat").append("<span class='you'>" + data + "</span>");
$('#full_chat').emoticonize();
window.onblur = function() {
$('#full_chat').bind("DOMSubtreeModified", function() {
$.titleAlert("New Message!", {
requireBlur: true,
stopOnFocus: true,
//duration:10000,
//interval:500
});
});
}
}
});
}
$("#full_chat").animate({
scrollTop: $('#full_chat')[0].scrollHeight + 1000
}, 1500);
refreshPage(1500, {user: user});
$("#form").on('submit', function(e) {
e.preventDefault();
var user = $("#head").text();
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
var txt = $("#chat_input").val();
$.post("chat.php", {
txt: txt,
user: user,
time: time
}, function(data, status) {
if (data == "OFFLINE") {
$("#full_chat").append("User not available right now<br>");
} else {
$("#full_chat").append("(" + time + ") ").append("<span class='me'>" + "Me: " + txt + "</span><br>").emoticonize({
delay: 1,
animate: false
});
}
});
$("#full_chat").animate({
scrollTop: $('#full_chat')[0].scrollHeight + 1000
}, 1500);
$('#chat_input').val('');
});
});
</script>

What would i use as a get request in jquery/ajax to set parameters

i am new to Jquery/Ajax and i am trying to have the source url for the json change based on the url parameters i setup, i have working version in PHP, but i don't know how to write it in JQuery
This is my PHP Code (what i am currently using
$id = urlencode($_GET['id']);
$page = urlencode($_GET['results']);
$url = "https://gdata.youtube.com/feeds/api/playlists/$id?alt=jsonc&v=2&max-results=25&&start-index={$results}";
This code grabs the id and includes it to alter the url of the source file used in the script
so how would i make this code act in the same way?
$(document).ready(function() {
startindex = 1;
loadmore = 20;
addMore(startindex, loadmore);
$('#addmore').on('click',function(e) {
e.preventDefault();
addMore($('#list li').length, 20);
});
});
function addMore(startindex,loadmore) {
src = "https://gdata.youtube.com/feeds/api/playlists/ID_WOULD_GO_HERE?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
$.ajax({
dataType: "jsonp",
url: src,
success: function(data, textStatus, jqXHR) {
if (data.feed && data.feed.entry) {
var $list = $('#list');
$.each(data.feed.entry, function(i, e) {
$list.append('<li class="video"><img src="'+ e.media$group.media$thumbnail[0].url +'" width="250"></img><br>' + e.title.$t + '<P>' + e.author[0].name.$t + ' | '+ e.yt$statistics.viewCount +' Views</span></li>');
});
}
}
});
}
Please help, Thanks!
Please try this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="list"></div>
<script>
$(document).ready(function() {
startindex = 1;
loadmore = 20;
id = urlVar("id");
if (id!="") {
addMore(id, startindex, loadmore);
}
$('#addmore').on('click',function(e) {
e.preventDefault();
addMore(id, $('#list li').size(), 20);
});
});
function urlVar(varName) {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars[varName]?vars[varName]:"";
}
function addMore(id, startindex,loadmore) {
src = "https://gdata.youtube.com/feeds/api/playlists/"+ id +"?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
$.ajax({
dataType: "jsonp",
url: src,
success: function(data, textStatus, jqXHR) {
console.log(data);
if (data.feed && data.feed.entry) {
var $list = $('#list');
$.each(data.feed.entry, function(i, e) {
$list.append('<li class="video"><img src="'+ e.media$group.media$thumbnail[0].url +'" width="250"></img><br>' + e.title.$t + '<P>' + e.author[0].name.$t + ' | '+ e.yt$statistics.viewCount +' Views</span></li>');
});
}
}
});
}
</script>
To test: this_script.php?id=RD029cW4vF6U2Dc
Potentially you could also get PHP to put the variable into the URL before hand.
Example:
src = "https://gdata.youtube.com/feeds/api/playlists/<?php echo $_GET['id'];?>?alt=json&max-results=" + loadmore + "&start-index=" + startindex;

Categories