How to submit a form using PhantomJS - javascript

I'm trying to use phantomJS (what an awesome tool btw!) to submit a form for a page that I have login credentials for, and then output the content of the destination page to stdout. I'm able to access the form and set its values successfully using phantom, but I'm not quite sure what the right syntax is to submit the form and output the content of the subsequent page. What I have so far is:
var page = new WebPage();
var url = phantom.args[0];
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
console.log(page.evaluate(function () {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].elements["email"].value="mylogin#somedomain.example";
arr[i].elements["password"].value="mypassword";
// This part doesn't seem to work. It returns the content
// of the current page, not the content of the page after
// the submit has been executed. Am I correctly instrumenting
// the submit in Phantom?
arr[i].submit();
return document.querySelectorAll('html')[0].outerHTML;
}
}
return "failed :-(";
}));
}
phantom.exit();
}

I figured it out. Basically it's an async issue. You can't just submit and expect to render the subsequent page immediately. You have to wait until the onLoad event for the next page is triggered. My code is below:
var page = new WebPage(), testindex = 0, loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
//Load Login Page
page.open("https://website.example/theformpage/");
},
function() {
//Enter Credentials
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].elements["email"].value="mylogin";
arr[i].elements["password"].value="mypassword";
return;
}
}
});
},
function() {
//Login
page.evaluate(function() {
var arr = document.getElementsByClassName("login-form");
var i;
for (i=0; i < arr.length; i++) {
if (arr[i].getAttribute('method') == "POST") {
arr[i].submit();
return;
}
}
});
},
function() {
// Output content of page to stdout after form has been submitted
page.evaluate(function() {
console.log(document.querySelectorAll('html')[0].outerHTML);
});
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 50);

Also, CasperJS provides a nice high-level interface for navigation in PhantomJS, including clicking on links and filling out forms.
CasperJS
Updated to add July 28, 2015 article comparing PhantomJS and CasperJS.
(Thanks to commenter Mr. M!)

Sending raw POST requests can be sometimes more convenient. Below you can see post.js original example from PhantomJS
// Example using HTTP POST operation
var page = require('webpage').create(),
server = 'http://posttestserver.example/post.php?dump',
data = 'universe=expanding&answer=42';
page.open(server, 'post', data, function (status) {
if (status !== 'success') {
console.log('Unable to post!');
} else {
console.log(page.content);
}
phantom.exit();
});

As it was mentioned above CasperJS is the best tool to fill and send forms.
Simplest possible example of how to fill & submit form using fill() function:
casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
this.fill('form#loginForm', {
'login': 'admin',
'password': '12345678'
}, true);
this.evaluate(function(){
//trigger click event on submit button
document.querySelector('input[type="submit"]').click();
});
});

Related

How do I fire a function immediately after another function is finished?

I have the following code:
<script>
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
window.setInterval(function(){
refreshChat();
}, 2000);
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
}
});
</script>
Right now, the refreshChat function calls an ajax script every 2 seconds. When you have entered a message and press enter, it calls a different ajax script. What I would like it to do, is call both functions at the same time. So the script calls the sendMessage function first and refreshes afterwards.
How can I do this? I have already tried changing it to:
<script>
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();refreshChat();
}
});
</script>
But this only enters the message first, and it only refreshes on the second keypress (enter). I would like to thank everybody beforehand on helping me out.
This is actually an illusion. Both functions are being called, but the chat window is refreshing before the chat message is able to save them.
To fix this, you should refresh the chat window only once the new message has been successfully saved:
function refreshChat() {
// Removed for brevity
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
// Now, this will only be called once the ajax is complete
refreshChat();
});
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
// I removed the refreshChat() call from here and moved it
// into the $.get() callback above ^^
}
});
As you can see, I moved your refreshChat() method to now be called from within the jQuery $.get() callback.
Have you tried using callbacks, that may be what you need?
Here is a link for reference.
http://www.impressivewebs.com/callback-functions-javascript/
MY WORKING AWNSER
Considering for what i asked, i have marked Wes Foster's awnser as correct. What made it work for me is also applying a promises after the get function. This way, the ajax script get's called twice as needed. I hope it will help someone in the future. (Look at me... travelling through time...). You will find my code underneath:
function refreshChat() {
var id = "'.$convers_id.'";
var receiver = "'.$system->getFirstName($second_user->full_name).'";
$.get("'.$system->getDomain().'/ajax/refreshChat.php?id="+id+"&receiver="+receiver, function(data) {
$(".conversation-content").html(data);
});
var scroller = $(".conversation-message-list").getNiceScroll(0);
$(".conversation-message-list").getNiceScroll(0).doScrollTop($(".conversation-content").height(),-1);
}
function sendMessage() {
var user2 = "'.$user2.'";
var message = $("#message");
if(message.val() != "" && message.val() != " ") {
$.get("'.$system->getDomain().'/ajax/sendMessage.php?id="+user2+"&msg="+encodeURIComponent(message.val()), function(data) {
$(".conversation-content").html(data);
message.val("");
refreshChat();
}).done(refreshChat);
}
}
$(document).keypress(function(e) {
if(e.which == 13) {
sendMessage();
}
});

PhantomJS facebook login form not fully submitted

I am trying to login to facebook by phantomJS, it is working fine but when I run it do not submit form.
It opens page fills fields but do not submits. I tried console to see form submit it return undefined first then it submits.
var page = require('webpage').create();
var system = require('system');
var stepIndex = 0;
var loadInProgress = false;
email = system.args[1];
password = system.args[2];
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
page.open("http://www.facebook.com/login.php", function(status) {
page.evaluate(function(email, password) {
document.querySelector("input[name='email']").value = email;
document.querySelector("input[name='pass']").value = password;
document.querySelector("#login_form").submit();
console.log("Login submitted!");
}, email, password);
page.render('output.png');
});
},
function() {
console.log(document.documentElement.innerHTML);
},
function() {
phantom.exit();
}
]
setInterval(function() {
if (!loadInProgress && typeof steps[stepIndex] == "function") {
console.log("step " + (stepIndex + 1));
steps[stepIndex]();
stepIndex++;
}
if (typeof steps[stepIndex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 10000);
You have at least two problems.
Since submitting a form usually incurs some network requests, the result won't be available immediately, but you're assuming that it will be immediately available, because you're immediately rendering a screenshot to see what happened. That screenshot won't show you the page after the submit. It will show you a page during a submit. You need to move the rendering to the next step when the submit result arrived in the browser.
document has no meaning outside of the page context. PhantomJS will nevertheless provide such a dummy object. You can only access the DOM (document and window) inside of page.evaluate().
Try
var steps = [
function() {
page.open("http://www.facebook.com/login.php", function(status) {
page.evaluate(function(email, password) {
document.querySelector("input[name='email']").value = email;
document.querySelector("input[name='pass']").value = password;
document.querySelector("#login_form").submit();
console.log("Login submitted!");
}, email, password);
});
},
function() {
page.render('output.png');
console.log("innerHTML: " + page.evaluate(function(){
return document.documentElement.innerHTML;
}));
console.log("full page: " + page.content);
},
function() {
phantom.exit();
}
]

Wait for a URL to download all the contents of a webpage

I have to download HTML Content of a URL. The problem is that the URL takes some time to load , so I have to wait/ timeout for sometime ( ~10 - 15 secs) before logging the content. To achieve this, I tried 2 approaches, but all of them fail to produce the desired result.
First approach is the use of setTimeOut:
var page = require('webpage').create()
page.open(url, function (status) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit();
} else {
window.setTimeout(function () {
console.log(page.content);
phantom.exit();
}, 10000);
}
});
But setTimeout fails to set the specified timeout. No matter what value I put as Timeout , it times out after a fixed amount of time which is less than the page load time.
The second approach was the use of OnLoadFinished:
var page = new WebPage(), testindex = 0, loadInProgress = false;
page.onConsoleMessage = function(msg) {
console.log(msg)
};
page.onLoadStarted = function() {
loadInProgress = true;
console.log("load started");
};
page.onLoadFinished = function() {
loadInProgress = false;
console.log("load finished");
};
var steps = [
function() {
page.open("url");
},
function() {
console.log(page.content);
}
];
interval = setInterval(function() {
if (!loadInProgress && typeof steps[testindex] == "function") {
console.log("step " + (testindex + 1));
steps[testindex]();
testindex++;
}
if (typeof steps[testindex] != "function") {
console.log("test complete!");
phantom.exit();
}
}, 5000);
In this approach, OnLoadFinished fires before the full page is loaded.
I am new to phantomJS , so the above two solutions are also from stack overflow. Is there something I am missing that is particular to my case ? Is there any other way to achieve the same result? ( I tried Waitfor construct also, but with no success).
Ok, you problem is to load Content after some timeout. If you are looking for DOM element, you have to use known to you WaitFor function. But if you just want to get page content after timeout, it is so much easier. So lets start.
var page = require("webpage").create();
var address = "http://someadress.com/somepath/somearticle";
var timeout = 10*1000;
page.open(address);
function getContent() {
return page.evaluate(function() {
return document.body.innerHTML;
});
}
page.onLoadFinished = function () {
setTimeout(function() {
console.log(getContent());
}, timeout);
}
Note! If you are waiting for large content in HTML body, use setInterval function, to wait for document.body.innerHTML more than you want.

JavaScript RangeError - Maximum call stack size exceeded when using jQuery.post

When using jQuery's .post() function to submit my form data, I'm getting an Uncaught RangeError: Maximum call stack size exceeded.
I know this generally means recursion but I can't see where the recursion is happening.
I've put the post request into a function ( submitRequest() ) so I can submit data from 2 different points in the code. It originally resided inside the submit event and at that point worked perfectly. The error came as soon as I moved it outside.
Any ideas?
JavaScript code (with commented logs so you can see the flow) :
$(document).ready(function() {
var downloadLink = '',
downloadName = '',
details,
detailsSaved = false;
$('.js--download').click(function(event) {
var self = $(this);
event.preventDefault();
downloadLink = self.data('filePath'); // Store clicked download link
downloadName = self.closest('.brochure').find('.brochure__name').html().replace('<br>', ' ');
if (!detailsSaved) {
$('#brochure-section').addClass('hide');
$('#capture-section').removeClass('hide');
$('html, body').animate({
scrollTop: $("#capture-section").offset().top
}, 500);
} else {
submitRequest();
}
return false;
});
$(".submit-btn").click(function(event) {
var antiSpam = $('input[name=url]').val();
if (antiSpam != "") {
outputResultText('Error - Please leave the spam prevention field blank', 'error');
proceed = false;
event.preventDefault();
return false;
}
var name = $('input[name=name]').val(),
company = $('input[name=company]').val(),
email = $('input[name=email]').val(),
phone = $('input[name=phone]').val(),
proceed = true;
if(name==""){
$('input[name=name]').addClass("error");
proceed = false;
}
if(phone==""){
$('input[name=phone]').addClass("error");
proceed = false;
}
if(email==""){
$('input[name=email]').addClass("error");
proceed = false;
}
if(!proceed) {
outputResultText('Please check all required fields', 'error');
event.preventDefault();
return false;
}
event.preventDefault();
if(proceed) {
console.log('About to request'); // Logged out
submitRequest();
}
return false;
});
//reset previously set border colors and hide all message on .keyup()
$("input, textarea").keyup(function() {
$(this).removeClass("error");
$(".form-result").fadeOut(100);
});
function submitRequest () {
console.log('Start submitRequest'); // Logged out
if (!detailsSaved) {
console.log('Details are NOT saved');
post_data = {
'name': name,
'company': company,
'phone': phone,
'email': email,
'brochure': downloadName,
'brochure_url': downloadLink
};
details = post_data;
} else {
console.log('Details are saved');
post_data = details;
post_data['brochure'] = downloadName;
post_data['brochure_url'] = downloadLink;
}
console.log('Posting data'); // Logged out
// CRASH: Uncaught RangeError: Maximum call stack size exceeded
$.post(bcf_local_args['post_url'], post_data, function(response){
console.log('Response received');
if(response.type != 'error') {
if (detailsSaved) {
outputAlert("Thank you for your request to receive our <strong>'"+downloadName+"'</strong> brochure.<br>We'll send you a copy soon to <strong>'"+email+"'</strong>, so please check your inbox.<br>Want it sent to a different email? Simply refresh the page and try again.");
} else {
//reset values in all input fields
$('#brochure-capture-form input').val('');
$('#brochure-capture-form textarea').val('');
$('#capture-section').addClass('hide');
$('#brochure-section').removeClass('hide');
outputAlert("Thank you for your request to receive our <strong>'"+downloadName+"'</strong> brochure.<br>We'll send you a copy soon to <strong>'"+email+"'</strong>, so please check your inbox.");
}
if (!detailsSaved) {
detailsSaved = true;
}
$('html, body').animate({
scrollTop: $(".brochure__alert").offset().top
}, 500);
} else {
outputResultText(response.text, response.type);
}
}, 'json');
}
function outputResultText (text, status) {
var output = '';
if(status == 'error') {
output = '<div class="error">'+text+'</div>';
} else {
output = '<div class="success">'+text+'</div>';
}
$(".form-result").hide().html(output).fadeIn(250);
}
function outputAlert (text) {
var output = '<div>'+text+'</div>';
$('.brochure__alert').hide().removeClass('hide').html(output).slideDown(250);
setTimeout( function() {
$('.brochure__alert').slideUp(250);
}, 6500);
}
// function accessStorage(action, dataKey, dataValue) {
// if(typeof(Storage) === "undefined") {
// // No support for localStorage/sessionStorage.
// return false;
// }
// if (action == 'store') {
// localStorage.setItem(dataKey, dataValue);
// } else if (action == 'retrieve') {
// return localStorage.getItem(dataKey);
// }
// }
});
I don't know if you already found a solution but I was having the "same" problem.
In my code I had this function where I was calling after an upload of images, and I was passing the images name as paramaters along with others parameters required to my POST data.
After some research I found out that browsers has some limitations on passing parameters so the problem wasn't AT $.post but in my function calling.
I don't know the technical term but I was 'overusing the stack parameters'.
So maybe your problem isn't at your $.post either, but something else exceeding the stack.
Hope this helps.
[]'s

jQuery Find and Replace is Hanging up the browser! Data size too big?

With alot of help from #kalley we have found out that If I comment the following two lines out the LAG is gone!
var $tableContents = $table.find('tbody')
var $html = $('<tbody/>').html(data);
But how do I keep the above but cancel out the LAG ?
MORE INFO:
The code below works but the problem is that the $.GET is causing the browser to hang until the ajax request completes. I need (flow control?) or something that will solve this problem without locking/hanging up the browser until ajax completes the GET request.
The biggest LAG/Lockup/Hang is at $.get("updatetable.php", since the others only return 7 or less (number) values and this one ('updatetable.php') returns alot more (200-300kb). I would like to implement some sort of flow control here or make the script wait like 5 secs before firing the update command for tablesort and before showing the toast message so that ajax has time to GET the $.get("updatetable.php"data I just don't understand why does it lockup the browser as it is getting the data? is it trying to fire the other commands and that's whats causing the LAG?
Here are the STEPS
1.
$.get("getlastupdate.php" Will fire every 10 secs or so to check if the date and time are the same the return data looks like this: 20130812092636 the format is: YYYmmddHHmmss.
2.
if the date and time are not the same as the last GET then $.get("getlastupdate2.php" will trigger and this data will be send back and placed into a toast message and dispalyed to the user $().toastmessage('showNoticeToast', Vinfoo);
3.
before or after the above ($.get("getlastupdate2.php") another GET will fire: $.get('updatetable.php' this will GET the updated table info. and replace the old one with the new info. and then update/resort the table
4.
at the end of it all I want to $.get("ajaxcontrol.php" and this will return a 1 or 2 if the user is logged in then it will be a 2 else it's a 1 and it will destroy the session and log the user out.
<script type="text/javascript" src="tablesorter/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="tablesorter/final/jquery.tablesorter.js"></script>
<script type="text/javascript" src="tablesorter/final/jquery.tablesorter.widgets.js"></script>
<script type="text/javascript" src="tablesorter/final/toastmessage/jquery.toastmessage-min.js"></script>
<script type="text/javascript" src="tablesorter/qtip/jquery.qtip.min.js"></script>
<script type="text/javascript">
var comper;
function checkSession() {
return $.get("ajaxcontrol.php", function (DblIn) {
console.log('checking for session');
if (DblIn == 1) {
window.location = 'loggedout.php';
}
}).then(updateTable);
}
function checkComper() {
var SvInfo;
var onResponse = function (comperNow) {
if (comper === undefined) {
comper = comperNow;
} else if (comper !== comperNow) {
var Vinfoo;
comper = comperNow;
// returning this $.get will make delay done until this is done.
return $.get("getlastupdate2.php", function (primaryAddType) {
Vinfoo = primaryAddType;
$().toastmessage('showNoticeToast', Vinfoo);
}).then(checkSession);
}
};
$.get('getlastupdate.php').then(onResponse).done(function () {
tid = setTimeout(checkComper, 2000);
});
}
function updateTable() {
return $.get('updatetable.php', function (data) {
console.log('update table');
var $table = $("table.tablesorter");
var $tableContents = $table.find('tbody')
var $html = $('<tbody/>').html(data);
$tableContents.replaceWith('<tbody>' + data + '</tbody>')
//$tableContents.replaceWith($html)
$table.trigger("update", [true]);
var currentUrl = document.getElementById("frmcontent").contentWindow.location.href;
var urls = ['indexTOM.php', 'index1.php'],
frame = document.getElementById('frmcontent').contentDocument;
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
if (frame.location.href.indexOf(url) !== -1) {
frame.location.reload()
}
}
$('[title!=""]').qtip({});
});
};
$(function () {
var tid = setTimeout(checkComper, 2000);
$("#append").click(function (e) {
// We will assume this is a user action
e.preventDefault();
updateTable();
});
// call the tablesorter plugin
$("table.tablesorter").tablesorter({
theme: 'blue',
// hidden filter input/selects will resize the columns, so try to minimize the change
widthFixed: true,
// initialize zebra striping and filter widgets
widgets: ["saveSort", "zebra", "filter"],
headers: {
8: {
sorter: false,
filter: false
}
},
widgetOptions: {
filter_childRows: false,
filter_columnFilters: true,
filter_cssFilter: 'tablesorter-filter',
filter_filteredRow: 'filtered',
filter_formatter: null,
filter_functions: null,
filter_hideFilters: false, // true, (see note in the options section above)
filter_ignoreCase: true,
filter_liveSearch: true,
filter_reset: 'button.reset',
filter_searchDelay: 300,
filter_serversideFiltering: false,
filter_startsWith: false,
filter_useParsedData: false
}
});
// External search
$('button.search').click(function () {
var filters = [],
col = $(this).data('filter-column'), // zero-based index
txt = $(this).data('filter-text'); // text to add to filter
filters[col] = txt;
$.tablesorter.setFilters($('table.hasFilters'), filters, true); // new v2.9
return false;
});
});
</script>
Maybe instead of using setInterval, you should consider switching to setTimeout. It will give you more control over when the time repeats:
function checkComper() {
var SvInfo;
var onResponse = function (comperNow) {
if (comper === undefined) {
comper = comperNow;
} else if (comper !== comperNow) {
var Vinfoo;
comper = comperNow;
// returning this $.get will make delay done until this is done.
return $.get("getlastupdate2.php", function (primaryAddType) {
Vinfoo = primaryAddType;
$().toastmessage('showNoticeToast', Vinfoo);
}).then(checkSession);
}
};
$.get('getlastupdate.php').then(onResponse).done(function () {
tid = setTimeout(checkComper, 10000);
});
}
var tid = setTimeout(checkComper, 10000);
Then you can keep it async: true
Here's a fiddle showing it working using echo.jsontest.com and some fudging numbers.
Since the click event callback seems to be where the issue is, try doing this and see if it removes the lag (I removed other comments to make it more brief):
function checkSession() {
return $.get("ajaxcontrol.php", function (DblIn) {
console.log('checking for session');
if (DblIn == 1) {
window.location = 'loggedout.php';
}
}).then(updateTable);
}
function updateTable() {
return $.get('updatetable.php', function (data) {
console.log('update table');
var $tableContents = $table.find('tbody')
//var $html = $('<tbody/>').html(data);
//$tableContents.replaceWith($html);
// replaceWith text seems to be much faster:
// http://jsperf.com/jquery-html-vs-replacewith/4
$tableContents.replaceWith('<tbody'> + data + '</tbody>');
//$table.trigger("update", [true]);
var currentUrl = document.getElementById("frmcontent").contentWindow.location.href;
var urls = ['indexTOM.php', 'index1.php'],
frame = document.getElementById('frmcontent').contentDocument;
for (var i = 0; i < urls.length; i++) {
var url = urls[i];
if (frame.location.href.indexOf(url) !== -1) {
frame.location.reload()
}
}
$('[title!=""]').qtip({});
});
};
$("#append").click(function (e) {
// We will assume this is a user action
e.preventDefault();
updateTable();
});
I commented out $table.trigger("update", [true]) since if you sort the table on the server before you return it, you shouldn't need to run that, which I'm almost certain is where the bottleneck is.
It is really hard untangle the mess you have but if what you want is ajax requests every 10 seconds it make sense to separate this logic from business logic over data from server.
Your code would also really benefit from using promises. Consider this example
$(document).ready(function() {
var myData = { }
, ajaxPromise = null
setInterval(callServer, 1000)
function callServer() {
ajaxPromise = updateCall()
.then(controlCall)
.done(handler)
.error(errorHandler)
}
function updateCall() {
return $.get('updateTable.php', function(data) {
myData.update = data
})
}
function controlCall( ) {
return $.get('ajaxControl.php', function(data) {
myData.control = data
})
}
function handler() {
console.dir(myData)
}
function errorHandler(err) {
console.log(err)
console.dir(myData)
}
})

Categories