I am abit confused with idea of asynchronous and synchronous ajax calls.Is it possible to make one ajax call asynchrononously followed with a synchronous call??
Here's my scenerio,
I am trying to make a real time progress bar to show no of data inserted where postdata() inserts data into table while getprocess() function returns the current no of data inserted to show in a progress bar.
Reference:: making progress bar
function getprogress(data){
console.log(data);
$.ajax({
method: 'POST',
url: '<?php echo base_url()?>setting/processoffline/getprogressdata',
data:{ table:data },
dataType: 'json',
async: false,
success: function(val) {
var off=parseFloat(Number(val.dataoffline),10);
var on=parseFloat(Number(val.dataonline),10);
var percent=Math.round((off/on)*100);
// $('#'+data+'success').addClass('hidden');
console.log('offline- '+off);
console.log('online- '+on);
$('#'+data+'progressbar').css('width',percent+"%");
$('#'+data+'progressbar').html(percent+"%" + off+' out of '+on );
if(percent=='100'){
console.log(percent);
// $('#'+data+'progressbox').addClass('hidden');
$('#'+data+'success').removeClass('hidden');
$('.download').removeAttr('disabled','disabled');
// clearTimeout();
}
console.log(postComplete);
if (!postComplete)
setTimeout( function() { getprogress(data); }, 1500);
} ,
error: function() {
if (!postComplete){
setTimeout( function() { getprogress(data); }, 1500);
}
}
});
}
function postdata(data)
{
// if(!data)
$.ajax({
method: 'POST',
url: '<?php echo base_url()?>setting/processoffline/processdata',
data:{ master_table:data },
dataType: 'html',
success: function() {
postComplete = true;
},
error: function() {
postComplete = true;
}
});
}
Now here's how I call these functions for use
$(this).parent('td').parent('tr').siblings('tr').children('td').find('input:checked').each(function(){
data=$(this).attr('id');
postdata(data);
$('#'+data+'success').addClass('hidden');
$('#'+data+'progressbox').removeClass('hidden');
i++;
getprogress(data);
if(!postComplete)
setTimeout( function() { getprogress(data);}, 2);
Here postdata() function is called multiple times in loop asynchronously my case is that since loop can be for unlimited number, that can start lot of parallel processes that can hang up my system so .I need to start next loop for postdata() only when the earlier process is over.Function postdata() makes ajax call for php function that requires a lot of time.So my technique is to define postdata() function asynchronously so that I can call getprogress() function parallely but (don't know if possible) I want to call getprocess ajax call synchronously so that loop will wait until value returned from getprogress is over.In this way I can start a new process in ajax call only when earlier process is over.
I want to know if it is possible or not and if not how can i manage this issue.Sorry for bad english and If unclear please comment and I am stuck to this for 3-4 days.
Thanks in advance
Related
Here is my code for loading data
$(document).ready(function() {
$.get('get-answers.php', {
project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
}, function(data) {
$('#dispaly-answers').append(data);
});
});
This code retrieves data from database and working fine. But problem here is that if I add new data on the database, this data doesn't show up without page refresh.
So I don’t want to refresh the page to get the data. It should be displayed once new data added to database.
Any suggestions on this issue?
P.S : I also tried .ajax(), didn’t work.
Here is my $.ajax() request
$(document).ready(function() {
$.ajax( {
type: "GET",
url: "get-answers.php",
data: { project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
},
cache: false,
success: function(data) {
$('#dispaly-answers').append(data);
},// success
})// ajax
});
Does the same as $.get()
If your goal is to refresh the page data without refreshing the page, you can put your code in an interval timer and let it auto refresh every x seconds, like below.
setInterval(getAnswer(), 1000);
note: setInterval fires again and again until you clear it, while setTimeout only fires once.
The Ajax-Function get only called once: In the moment the document is ready (fully loaded). You have to use setTimeout to create a timer, which calls the function every minute or whatever you want. Like this:
function getData() {
setTimeout(function(){
$.get('get-answers.php', {
project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
}, function(data) {
$('#dispaly-answers').append(data);
getData();
});
}, 3000);
}
Here is my final approach
$(document).ready(function() {
setInterval(function(){
$.ajax( {
type: "GET",
url: "get-answers.php",
data: { project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
},
cache: false,
success: function(data) {
$('#dispaly-answers').html(data);
},// success
})// ajax
}, 1000);
});
Without creating and calling function getData(), this code working fine. Also I have changed .append(data) to .html(data).
But still I'm not happy with my code because it is constantly retrieving data from database that makes data server busy.
Whatever I wanted to tasks has to be done and it is done.
Try this you just need to replace this file retrieve_query.php and this id query-div with yours.
setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$('#query-div').html(this.responseText);
}
};
xmlhttp.open("GET","retrieve_query.php",true);
xmlhttp.send();
},1000);
I'm new to Javascript and Mootools and I was wondering if someone can help me learn by solving a problem that I currently have.
index.php has a form, which submit to it self and initiate this code
if($_POST['subbutton']=='Run')
{
$data=$object->do_compare();
}
I would like to know, how can I do a mootool ajax function, that will send the post['run]'
to a php script file ( data.call.php ) where the object reside and have it run.
however, I don't want any respond from data.class.php, as that object writes it's results to a txt file (data.txt)
the 2nd part,
would be an ajax function (that also run at the same time as the first ajax function) and reads a php file, every 5 seconds and bring the data back to index.php
so the squence of operations will be
index.php
form get clicked and start 2 ajax functions.
the first one, only submit the POST['run'] to a php script.
the second function, will go to another php file and get a respond from it every 5 seconds.
I didn't test the below, so use at your own risk. But that's pretty much the gist of it.
_form.addEvent('submit', function(event) {
// your first call
new Request.JSON({
url: "your-first-rpc",
data: {
subbutton: "Run"
},
onSuccess: function(response) {
// handle response here.
}
}).post();
// your second call which runs every 5 secs.
(function() {
new Request.JSON({
url: "your-second-rpc",
data: {
subbutton: "Run"
},
onSuccess: function(response) {
// handle response here.
}
}).post();
}).periodical(5000);
});
<script type="text/javascript">
window.addEvent('domready', function() {
$('dbform').addEvent('submit', function(e)
{
new Event(e).stop();
var intervalId =setInterval(function(){
var Ajax2 = new Request(
{
url: '/tools/getdata.php',
method: 'post',
data: 'read=true',
onComplete: function(response)
{
$('21').set('text', response);
}
}
).send();},1000);
var postString = 'subbutton=' + $('subbutton').value;
var Ajax = new Request({
url: '/tools/getdata.php',
method: 'post',
data: postString,
onRequest: function()
{
$('message').set('text', 'loading...');
},
onComplete: function(response)
{
$('message').set('text','completed');
clearInterval(intervalId);
},
onFailure: function() {
$('message').set('text', 'ajax failed');
}
}).send();
});
});
</script>
I'm having trouble with lag and script execution.
I have the following code:
$(function(){
$("#results").html("Loading work order queue...");
setInterval("showWorkOrders();", 15000)
});
function showWorkOrders()
{
$.ajax({
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
}
});
}
My backend PHP (only an example):
$SQL = MySQL_query("SELECT * FROM table")
while($data = MySQL_fetch_array($SQL))
{
//// OUTPUTS A TABLE WITH INFORMATION
}
Now, this whole thing executes however with a lot of lag (takes very long to load) and sometimes creates an script error because it took too long to load. If I extend the refresh interval, things start getting better (the lag remains) and I don't get the execution error. I need to have a short interval for what I need, but I cannot figure out an efficient way of doing so. Any suggestions on how to improve this?
Also, after a while of being on the page that has the refresher, the browser becomes extremely slow to the point where it locks...
I would solve it using setTimeout instead:
$(function(){
$("#results").html("Loading work order queue...");
showWorkOrders();
});
function showWorkOrders()
{
$.ajax({
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
setTimeout("showWorkOrders();", 5000)
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
setTimeout("showWorkOrders();", 5000)
}
});
}
This would mean that it waits 5s before doing a new ajax request, the previous one can take however long it wants. Still waits 5s before it tries again.
Try this. Start next request only after response from server.
$(function(){
$("#results").html("Loading work order queue...");
showWorkOrders();
});
function showWorkOrders()
{
$.ajax({
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 15000);
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 15000)
}
});
}
Instead of Ajax on interval, I'd suggest next Ajax after completion.
Since the ajax request takes an indeterminate amount of time to complete, I would suggest that you trigger the next ajax request when the first one completes using setTimeout() and so on like this so that you never have multiple ajax requests going at once and so each subsequent ajax call starts a known time from when the previous one completed.
You probably want to troubleshoot why your server is taking so long to respond to the request, but you can also extend the timeout for the ajax call if your server sometimes takes a long time to respond:
function showWorkOrders()
{
$.ajax({
timeout: 15000,
url: '/ajax/job_queue_ajax.php',
type: 'POST',
cache: false,
data: 'update=true',
success: function(data)
{
$("#results").html(data);
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 5000);
},
error: function()
{
a = new customModal('ajax');
$("#results").html("<font class='msgDivError'>"+a.ajaxError+"</font>");
$('span#ref_msg').html('');
setTimeout(showWorkOrders, 5000);
}
});
}
$(function(){
$("#results").html("Loading work order queue...");
showWorkOrders();
});
This question already exists:
How to change from ajax polling to long polling [duplicate]
Closed 9 years ago.
This is my ajax code so please can anyone tell me how can i change this code to long polling ?
Here is my code :-
var chat = {}
chat.fetchMessages = function () {
$.ajax({
url: 'ajax/ajax/chat.php',
type: 'POST',
data: { method: 'fetch' },
success: function(data) {
$('#chats').html(data);
}
});
}
chat.interval = setInterval(chat.fetchMessages, 1000);
You have to put the next call of fetchMessage in the callback of the previous one :
var chat = {}
chat.fetchMessages = function () {
$.ajax({
url: 'ajax/ajax/chat.php',
type: 'POST',
data: { method: 'fetch' },
success: function(data) {
$('#chats').html(data);
chat.fetchMessages(); // let's do it again
}
});
}
chat.fetchMessages(); // first call
The above code seems to work fine but this will call function immediately as a result of this it would increase the traffic and possibly for continuous long polling memory usage by the browser will increase . Try to use settimeout to keep some duration between calls made , would be good if you clear cache too . Other option would be comet or signaR .
I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.