Suspend all actions on app launch/init until get ajax response - ajax

I'm trying to find a way to stop any actions until the Ajax request will return any data. Request is calling in Application init() method.
Example:
Ext.define('MyApp.Application', {
...
init: function() {
// SUSPEND APP LOADING
Ext.Ajax.request({
...
success: function() {
// CONTINUE app loading
}
})
}
});
Just i have to prevent any actions of controllers in App until first request will return any answer.
suspendEvents is not a way... or I use it wrong?
Thank you.

We can use async:false ajax option, to wait till ajax request get completed
Try this:
Ext.define('MyApp.Application', {
...
init: function() {
// SUSPEND APP LOADING
Ext.Ajax.request({
...
async: false,
success: function() {
// CONTINUE app loading
}
})
}
});
It will prevent further code, till ajax request complete

Related

ReactJS ExpressJS - Ajax Form

Due to my starting level with React and Node/Express and, above all, time restriction, I'm developing a single page application without database, so I have only static pages.
I've configured react-router to have clear url, using the hash (http://localhost:8080/#/contacts) i avoid also server calls:
let history = createHistory({
queryKey: false
});
I've got the necessity to send mail from my form. To do this I've found nodemailer and I need to invoke it from an ajax call.
Just to do some pratique with React i've configured my ajax call in my componentDidMount function:
openForm() {
$('#contacts-form').on('submit', function(){
$.ajax({
url: '/mail',
type: 'post',
data: { msg: $('#data').val() },
success: function(data){
console.log(data);
},
error: function(){
console.log('err form');
}
});
return false;
});
}
componentDidMount() {
this.openForm();
}
Now, after I've installed body-parser and set my form's action to "/mail", in my server.js I've configured my .post route
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/mail', function(req, res){
res.send('ajax call recived');
});
So now once I try to submit my form, my ajax call fails, in the console, I get this error:
POST http://localhost:8080/mail 404 (Not Found)
err form
It's the first time I'm working with these tools, where I'm doing wrong?

How to stop AJAX calls if there's an error on a field with a keyup trigger

I have this jquery ajax call that is trigger on keyup. It has error handling which (with Firefox for e.g.) is triggered multiples times if the user enters keystrokes fast. Is there a quick way to stop multiple alert windows to be shown?
$('input[name$="_LOC"]').keyup(function(){
if ($(this).val().length >=4){
$.ajax({
type: 'POST',
url: 'red.asp?q='+$(this).val(),
beforeSend: function() {
[...]
},
success: function(data) {
[...]
},
error: function() {
alert("Oops!")
}
});
}
});
Restart a timer each time the onkeyup is triggered, this means the event only happens when the user has finished typing (or, at least, paused for a second or whatever).
Use timer = setTimeout(yourFunction, yourDelay);
To rest the timer user clearInterval(timer) and start the setTimeout again.
var typing = false;
var timer;
$('input[name$="_LOC"]').keyup(function(){
if(typing) {
clearInterval(timer);
}
timer = setTimeout(sendAjax, 500, [this]);
typing=true;
});
function sendAjax(element)
{
if ($(element).val().length >=4){
$.ajax({
type: 'POST',
url: 'red.asp?q='+$(element).val(),
beforeSend: function() {
[...]
},
success: function(data) {
[...]
},
error: function() {
alert("Oops!")
}
});
typing = false;
}
Here's JSFiddle example: http://jsfiddle.net/X8US5/, you'll need your browsers console.log viewer ready to see stuff (otherwise edit the console.logs to be alerts though they interrupt JS so times will be off)
Edit:
IE9 compatible (hack) version http://jsfiddle.net/5ndM5/1/
Tried to find a jQuery alternative but none it seems.
THe overriding the function alternative is good if you don't want the global var, but if you only plan to use this code on one form then the global is acceptable (JS code is usually rife with them by accident anyway)

Ajax request error when changepage

guys. I have a juerymobile multi-page, and I have a button in #page-index, when click it, will send a ajax request to server, and changepage to #page-column, It run will in PC, but when i deploy the multi-page in phonegap, the button click can just run only twice, code is below:
function test()
{
$.mobile.changePage('#page_column');
$.ajax({
url: "http://192.168.168.120:8090/fcmobile/getTest",
dataType: "json"
}).done(function(data) {
alert(data.content);
});
}
I found if I remove $.mobile.changePage('#page_column');, the ajax request can be run well any times. but when I add the changePage code, it only can be run twice, in third time, ajax request can't even be send. Dose anybody know reason?
AJAX is made to be asynchronous, so no need to set async to false to get it working. Use events instead.
For example:
function test () {
$.ajax({
'url': "http://192.168.168.120:8090/fcmobile/getTest",
'dataType': 'json',
'success': function (json_data) {
$(document).trigger('test_json_data_loaded');
console.log(data);
}
});
}
$(document).on('test_json_data_loaded', function () {
$.mobile.changePage('#page_column');
});
When you set async to false, you're basically making it so that every time this AJAX request is made, the user will have to wait until all the data is fully loaded before the application/website can do/execute anything else...not good.

Dojo addOnUnload and xhrGet

I have function to unlock data sets via an API
function unlockData() {
var xhrArgs = {
url: "/api/unlockData",
handleAs: "json",
content: {
account_id: accountId
},
load: function(data) {
if(data) {
alert("Data unlocked");
} else {
alert("Something went wrong.");
}
},
error: function(error) {
alert("error:"+error);
}
}
var deferred = dojo.xhrGet(xhrArgs);
}
which is called onUnload
dojo.addOnUnload(window, "unlockData");
When reloading, this I get this error message:
Error: Unable to load /api/unlockData?account_id=981782 status:0
Can I fire an xhrGet request on unload at all? BTW, the function works fine, if not called on unload.
Since Xhr calls are asynchronous, putting this call during the 'Unload' will fail always because the browser is not in this page anymore.
Anyways, since the addOnUnload is triggered during the window.onbeforeunload, you can put a "timer" loop to check if the AJAX call has success.
I strongly don't recommend this practice. Using an AJAX call during the "window" closing is totally unnecessary, you should consider to use a form instead and call your scripts synchronously

jQuery.ajax() sequential calls

Hey. I need some help with jQuery Ajax calls. In javascript I have to generste ajax calls to the controller, which retrieves a value from the model. I am then checking the value that is returned and making further ajax calls if necessary, say if the value reaches a particular threshold I can stop the ajax calls.
This requires ajax calls that need to be processes one after the other. I tried using async:false, but it freezes up the browser and any jQuery changes i make at the frontend are not reflected. Is there any way around this??
Thanks in advance.
You should make the next ajax call after the first one has finished like this for example:
function getResult(value) {
$.ajax({
url: 'server/url',
data: { value: value },
success: function(data) {
getResult(data.newValue);
}
});
}
I used array of steps and callback function to continue executing where async started. Works perfect for me.
var tasks = [];
for(i=0;i<20;i++){
tasks.push(i); //can be replaced with list of steps, url and so on
}
var current = 0;
function doAjax(callback) {
//check to make sure there are more requests to make
if (current < tasks.length -1 ) {
var uploadURL ="http://localhost/someSequentialToDo";
//and
var myData = tasks[current];
current++;
//make the AJAX request with the given data
$.ajax({
type: 'GET',
url : uploadURL,
data: {index: current},
dataType : 'json',
success : function (serverResponse) {
doAjax(callback);
}
});
}
else
{
callback();
console.log("this is end");
}
}
function sth(){
var datum = Date();
doAjax( function(){
console.log(datum); //displays time when ajax started
console.log(Date()); //when ajax finished
});
}
console.log("start");
sth();
In the success callback function, just make another $.ajax request if necessary. (Setting async: false causes the browser to run the request as the same thread as everything else; that's why it freezes up.)
Use a callback function, there are two: success and error.
From the jQuery ajax page:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// Do processing, call function for next ajax
}
});
A (very) simplified example:
function doAjax() {
// get url and parameters
var myurl = /* somethingsomething */;
$.ajax({
url: myurl,
context: document.body,
success: function(data){
if(data < threshold) {
doAjax();
}
}
});
}
Try using $.when() (available since 1.5) you can have a single callback that triggers once all calls are made, its cleaner and much more elegant. It ends up looking something like this:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
alert( jqXHR.responseText )
});

Resources