How to display a progress bar during an ajax request (jquery/php) - javascript

I have an ajax request, whereby I am installing a magento shop automatically, and when the process is done, it would redirect the user to the newly created shop. Here are my codes:
function postSuccessFormData() {
var targetUrl = '/index.php/install/wizard/successPost';
jQuery('.form-button').addClass('loading');
setInterval(installStatus(),4000);
jQuery.ajax({
url: targetUrl,
global: false,
type: 'POST',
data: ({
finish: 1,
password_key: jQuery('#password_key').val()
}),
async: true,
dataType: 'json',
error: function() {
alert("An error has occurred. Please try again.");
},
success: function(data) {
window.location.href = '/';
}
});
function installStatus() {
var installerUpdatesUrl = '/index.php/install/wizard/installerStatus';
//showProgressBar();
jQuery.ajax({
url: installerUpdatesUrl,
// global: false,
type: 'GET',
async: true,
dataType: 'json',
error: function (data) {
// alert(data.result);
},
success: function (data) {
handle data.result
var dataKeys = Object.keys(data);
var lastElementKey = dataKeys[dataKeys.length - 1];
var lastMessage = data[lastElementKey]['message'];
if(data[lastElementKey]['progress'] == '') {
updateProgressBar(data[dataKeys[dataKeys.length - 2]]['progress'],100);
}
setting message
jQuery("#message").html(lastMessage);
if (data[lastElementKey]['state'] == 'Failure') {
var stepStr = lastElementKey.split('_');
var stepString = stepStr[0].toUpperCase() + ' ' + stepStr[1] + ':';
alert(stepString + "\n" + data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
return false;
} else if (data[lastElementKey]['state'] == 'Finish') {
alert(data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
//window.location.href = '/';
} else {
// installStatus();
}
},
complete: function () {
installStatus();
jQuery('.form-button').removeClass('loading');
}
});
}
The way this is done:
After every 4 seconds the function installStatus is run, which will output the current progress in JSON format. My problem is, this function needs to be executed simultaneously with the function post().
This is not happening, the installStatus is only run after the first function has been completed.
What is wrong?

You are executing installStatus when you define it. So this:
setInterval(installStatus(),4000);
needs to be
setInterval(installStatus, 4000);

The new XMLHttpRequest has a nice progress event you can listen to show the user the upload progress.
Here's the spec with a nice demo: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress

Initially you should call installStatus() only once and then inside the method inside ajax success you should update the procent in the progress bar and call it recursively the same method. On the server side you can save the current procent in a cookie and with every recursive call you can update the cookie and return the procent.

Related

How do I prevent reset the select box after ajax post action?

I want to make the option I selected fix to after AJAX POST.
Currently I am doing the work manually.
I put the value at OnChange in the HiddenField,
and after doing AJAX POST, re-insert the value selected in "ddlUserCont".
<select id="ddlUserCont" onchange="ddlUserCont_Onchange(this);"></select>
function ddlUserCont_Onchange(obj) {
document.getElementById("<%=hidSelddlUserCont.ClientID %>").value = obj.value;
}
-> After AJAX POST action..
function btnTest_Click() {
// ... Some logic
$.ajax({
type: "POST",
cache: false,
url: "../../WebServices/WebService.asmx/GetTest",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
OnSuccess_GetTest(data, sTestVal);
},
error: function (request, status, error) {
console.log("code:" + request.status + "\n" + "message:" + request.responseText + "\n" + "error:" + error);
}
});
}
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value;
document.getElementById("ddlUserCont_" + sSelPageName).selected = "true";
}
Do I use UpdatePanel ?
Why is it getting reset? is the page reloading? or is some other script resetting it?
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value; // get the value from the hidden field
document.getElementById("ddlUserCont).value = sSelPageName; // set it on the select options element
}
Just make sure that select has an option child element with value=<sSelPageName> at the time.

Multiple AJAX calls and show div on finish

I have a JS script doing multiple AJAX requests. First I'm requesting a product by ID and then I'm requesting every single variant of this product. I can't do any form of backend coding since the environment I'm working in is closed.
My requests works fine, but right now I'm appending every single variant to a div, and my client don't really like this, so I was thinking is it possible to load all data into a variable and then fade in the parent div of all variants at the very end?
My script looks like this:
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
variants.find('.variant').fadeIn(300);
}
});
});
}
});
Some fast and dirty solution, but idea and concept of solution is clear. It is bad solution, but works for you in your case when you have no access to backend code.
var all_load_interval;
var is_all_data_ready = false;
var all_data_count = 0;
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
var data_count = $(data).find('Combinations Combination').length;
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
// make div with class variant hidden
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
// count every variant
all_data_count += 1
if (all_data_count == data_count) {
// when all data got and created, lets trigger our interval - all_load_interval
is_all_data_ready = true;
}
}
});
});
}
all_load_interval = setInterval(function() {
// Check does all data load every second
if (is_all_data_ready) {
// show all div.variant
variants.find('.variant').fadeIn(300);
clearInterval(all_load_interval);
}
}, 1000);
});

How to call setinterval function in another function is not working

I want to display Updated records count when Ajax process is going on. When i click on start process button updateRecords()function will execute and it will update records status from open to waiting status one by one in database.So at the same time i want display the waiting records count .For this when user click on strat process button i want to call displayWaitingRecords() using setinterval.
I am calling that function like this from updateRecords()
clear_Process = setInterval(function(){displayWaitingRecords()},200);
But displayWaitingRecords() will not call until updateRecords() process completes.But my requirement is displayWaitingRecords() also will execute simaltaniously with updateRecords().
Function to display updated record count
function displayWaitingRecords()
{
jQuery.ajax({
type: 'GET',
crossDomain:true,
async: false,
url: "/curlRRQCount.php",
success: function(count){
if(count)
{
jQuery("#processed_poids_div").html("Processed Order ids:"+count) ;
}
}
});
}
Function when i click on start process button
var clear_Process = "";
function updateRecords()
{
clear_Process = setInterval(function(){displayWaitingRecords()},200);
var str = jQuery("#rrq_form :input[value!='']").serialize();
jQuery.ajax({
async: false,
type: 'POST',
data : str,
url: "/updaterecord_status.php",
success: function(valid_result)
{
if(jQuery.trim(valid_result) == 'Success')
{
jQuery("#rrq_load_img").hide();
jQuery("#rrq_orders_status").html("some success message");
}
}
});
}
Where i am doing wrong? Any help would be greatly appreciated.
You have set async: false. So the ajax call will process synchronized. Set it to false or leave it out (because true is default):
var clear_Process = "";
function updateRecords()
{
clear_Process = setInterval(function(){displayWaitingRecords()},200);
var str = jQuery("#rrq_form :input[value!='']").serialize();
jQuery.ajax({
async: true,
type: 'POST',
data : str,
url: "/updaterecord_status.php",
success: function(valid_result)
{
if(jQuery.trim(valid_result) == 'Success')
{
jQuery("#rrq_load_img").hide();
jQuery("#rrq_orders_status").html("some success message");
}
}
});
}
If you leave it out you have the same result:
function displayWaitingRecords()
{
jQuery.ajax({
type: 'GET',
crossDomain:true,
url: "/curlRRQCount.php",
success: function(count){
if(count)
{
jQuery("#processed_poids_div").html("Processed Order ids:"+count) ;
}
}
});
}

Variable not accesable in ajax response

I'm having troubles using a global variable in my ajax response.
LastDate is a variable defined in the page I loaded into my second page. (function load_table)
I am able to acces the variable before the ajax call, but I can't seem to acces it in my ajax succes. because it gives undefined. <==== in code
my code:
var dia_date = {};
$(window).load(function()
{
DP("eerste keer")
load_table();
} );
function load_table()
{
DP('load_table');
$.ajax({
type: "POST",
url: "/diagnose_hoofdpagina/table_diagnose/" + DosierID,
success: function (data) {
$("#diagnoses_zelf").html('');
$("#diagnoses_zelf").append(data).trigger('create');
//initialize_table();
update_table();
},
error: function(){
alert('error');
}
});
return false;
}
function update_table()
{
if(LastDate > Datum)
{
alert("LasteDate" + LasteDate);
}
else
{
alert("Datum" + Datum);
}
alert('gast .... ' + LastDate); // <========== this is promted on the screen so there is no problem
$.ajax({
type: "POST",
url: "/refresh_diagnose/" + DosierID,
dataType: "json",
data : JSON.stringify(dia_date),
success: function (data) {
var DataDate = new Date(data.Year, data.Month, data.Day, data.Hour, data.Minute, data.Second);
alert('lastdate :'+ LastDate + 'date.date :' + DataDate);
//<============ BUT HERE HE GIVES LastDate AS UNDEFINED
},
error: function(data){
alert(data);
}
});
return false;
}
I can't see what I'm doing wrong. Can annyone help me plaese ? Thanks in advance.
You can try making a function.
var lastDate = #;
function getLastDate(){return lastDate;}
ajax.blablabla.success :{getLastDate();}

How do you stop a user from repeatedly clicking a jQuery AJAX call?

I have a web-page with the following script
Javascript
function LinkClicked() {
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
}
});
}
How do I stop the user from repeatedly clicking whilst the query is running? The call is from a cell in a grid and can't easily be disabled. Ideally, I'd like a way of doing it in the script without disabling the link on the DOM.
Here I clicked five times, and you can see five AJAX requests are sent. The page should disable the same call being repeatedly invoked whilst it is already running.
Thanks in advance.
You could have an external variable tracking the state
var linkEnabled = true;
function LinkClicked() {
if(!linkEnabled){
return;
}
linkEnabled = false;
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
linkEnabled =true;
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
linkEnabled = true;
}
});
}
This also has the advantage that you can choose to enable other effects of this function if you want, and only prevent the repeat ajax calls.
(Note that ideally you would want to stick the external variable in a closure or a namespace rather than making it a global).
Disable a button when user clicks it, and set disabled to false when you get response from ajax.
Declare a variable outside of the function with an initial value of false:
var pending = false;
When you make the request, you'd do:
if (pending == true) {return;}
pending = true;
This makes it stop if you're already running, and when the request is done:
pending = false;
Now even without a button, the request won't fire multiple times.
As a side note, your data doesn't need to be a string. You can just do:
data: {stage: stage, stop: stop, nDays: nDays}
you can just check use this
var ajax_stat = false
function doing_ajax(){
if(ajax_stat) return;
ajax_stat = true;
var xmlRequest = $.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
ajax_stat = false;
}
});
}
Use below code. it will not make multiple ajax calls.
function LinkClicked() {
if($(window).data("ajaxRUnning")){
return;
}
$(window).data("ajaxRUnning",true);
var stage = this.id;
var stop = $('#ContentPlaceHolderMenu_txtDate').val();
var nDays = $('#ContentPlaceHolderMenu_txtNumberOfDays').val();
$("[id$='spinner']").show();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: "...",
data: "{stage:'" + stage + "',stop:'" + stop + "',nDays:'" + nDays + "'}",
success: function (data) {
$("[id$='spinner']").hide();
PlotData(data.d);
$(window).data("ajaxRUnning",false);
},
error: function () {
$("[id$='spinner']").hide();
alert("An error occured posting to the server");
$(window).data("ajaxRUnning",false);
}
});
}

Categories