2 Mootools AJAX function at the same time? - php

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>

Related

Making asynchronous and synchronous calls parallely in ajax

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

how to load data without page refresh using ajax

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);

two ajax functions at the same time? not working

I have a simple AJAX script that suppose to to call a PHP file and get data back.
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)
{
$('results').set('html', 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();
});
});
The file that it is submitting too is.
$object= new compare();
if(isset($_POST['subbutton'])=='Run')
{
// This take about 5 minutes to complete
$run=$object->do_compare();
}
if(isset($_POST['read'])=='true')
{
/// in the mean time, the first ajax function is suppose to return data from here..while
// the do_compare() function finish.
// the problem is that it only return it once the do_compare() finish
///
echo 'read==true';
}
the script is working fine, expect, that when the Ajax request check the file every one second, it doesn't return any thing from $_POST['read'], till $run=$object->do_compare(); has finished.
why does it do that? what What I am trying to accomplish is that one Ajax function get data from do_compare function and the other ajax function also independently get that from the getdata.php file.
The problem is in line:
if(isset($_POST['subbutton'])=='Run')
isset returns boolean true or false so if $_POST['subbutton'] is set than it returns true and due to the weak type system of php true == 'Run' because 'Run' evaluates to true. Use
if(isset($_POST['subbutton']) && $_POST['subbutton'] === 'Run')
and
if(isset($_POST['read']) && $_POST['read'] === 'true')
Are you using session in the PHP AJAX handlers? If so, your session file is probably blocked.
Second: Javascript is internally single threaded in the browser (see google for more information).

Issue with using a value in JQuery/Javascript

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.

jQuery constantly ping for Ajax responce

How can I use jQuery to constantly run a PHP script and get the response every second and also to send small bits of data on mouse down to the same script?
Do I really have to add some random extension just to get such a simple timer to work?
To iterate is human, to recurse divine.
-L. Peter Deutsch
var req = function () {
$.ajax({
url : 'http://example.com/yourscript.php',
complete : function () {
req();
}
});
};
req();
In case it's not obvious, the above will make a new request as soon as the previous one completes, forever. You could also set a 1 second delay between requests as follows:
var req = function () {
$.ajax({
url : 'http://example.com/yourscript.php',
complete : function () {
setTimeout(function () {
req();
}, 1000);
}
});
};
req();
function doAjax(data){
$.ajax({
type: "POST",
data: data,
url: 'http://example.com/yourscript.php',
});
}
// Set interval
setInterval('doAjax()',1000);
// Set event handler
$(document).mousedown(function(){
doAjax({key: 'value'});
});
You could replace $(document) with an actual element if you don't want to capture clicks on the whole page.
You can do a lot more with the ajax function if you are looking for callbacks etc:
http://docs.jquery.com/Ajax/jQuery.ajax
//All pings you need:
ping.pushCallback(function() { YourCallback(); });
$.data(document.body, 'data_ping', ping);
//------------------------------------------------------
//Script
$.ping = function(url, options) {
this.url = url;
this.options = $.extend({
delay: 2000,
dataType: 'json',
timeout: 10000,
data: {},
callbacks: []
}, options);
this.queue();
};
$.ping.prototype = {
queue: function() { var self = this;
setTimeout(function() {
self.send();
}, self.options.delay);
},
send: function() { var self = this;
$.ajax(self.url, {
success: function(data) {
for (var i in self.options.callbacks) {
self.options.callbacks[i](data);
}
},
complete: function() {
self.queue();
},
dataType: self.options.dataType,
data: self.options.data,
type: "GET",
cache: false,
timeout: self.options.timeout
});
},
setData: function(key, value) {
this.options.data[key] = value;
},
pushCallback: function(callback) {
this.options.callbacks.push(callback);
}
};
You can put the code for pinging the server in a function, then do something like this:
setInterval('ping()',1000); //this will ping 1000 milliseconds or 1 second
You don't have to add some random extension. There are native javascript functions setInterval and setTimeout for doing stuff on set intervals. You would probably want to do something like
function ajaxPing() {
...
}
setInterval("ajaxPing()", 1000);
$(element).mousedown(ajaxPing);
On the other hand, if you really want to do the pinging every second, it would probably be sufficient to just store your data in variables on mousedown and submit it on next ping (that will happen in less than a second).

Categories