Ajax response is not received before application is loaded in extjs - ajax

I would like to send Ajax request in launch function and based on the response to open either login window or main window.
Application.js
launch: function () {
debugger;
Ext.Ajax.request({
url: 'php/foo.php',
params: {
email: 'test#gg.com',
password: '12345',
},
success: function(response, opts){console.log('OK');},
failure: function(response, opts){console.log('ERROR');},
});
debugger;
console.log('This should be printed after Ajax response (either OK/ERROR)');
debugger;
foo.php
<?php
$login=$_POST['email'];
$pass=$_POST['password'];
$result = array();
echo json_encode(array(
"success" => $pass=="123456",
"data" => $result
));
But, I've noticed the response from the Ajax call is not ready before the function ends (Figure 1)

Ajax requests are asynchronous and in the above code example, the ajax request is submitted to the server and then the program steps to the next line of code (debugger). Any action to be performed upon a successful request needs to be done inside of the success callback function.
Since this is ExtJS, one pattern I have used, is to fire a global event, something like this:
Ext.GlobalEvents.fireEvent('applicationstart')
The main application listens for this event and that in turn opens the main application. These are other ways of doing this though.

You can do it by setting async:false to request to be synchronous, but this is not recommended.
Ex.
Ext.Ajax.request({
async: false,
url: 'php/foo.php',
params: {
email: 'test#gg.com',
password: '12345',
},
success: function(response, opts){console.log('OK');},
failure: function(response, opts){console.log('ERROR');},
});

Related

Ajax request in extjs fires success although response is false

I have an AJAX request like:
Ext.Ajax.request({
url: 'login.php',
scope: me,
params: {
email: 'test#gg.com',
password: '12345',
},
success: function(){console.log('OK');},
failure: function(){console.log('ERROR');},
});
The console.log is 'OK', even though the response is false
The failure callback fires only if an HTTP status returned from the server is different than 200 OK.
Change the status in response or check the value of success parameter just in success callback.
The success callback function has two return arguments, the first is the response from the server. Decoding the response will allow you to check for a successful login, something like this:
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
if (obj.success === true) console.log('success!');
}

jQuery ajax: Want to sequence the code process

I am getting data from php file through ajax. Based on the data I need to do some processing. I have put a few alerts in my code, and from that I realize that the code outside the ajax is being executed before ajax gets the data. I want the code to be done after the data is received from php file.
Code:
$(function () {
var originalData="";
$.ajax({
url: 'data.php',
data: "",
dataType: 'text',
success: function(data)
{
originalData=data;
alert("originalData 1 "+ originalData);
}
});
alert("originalData 2 "+ originalData);
...
Processing code
...
});
The sequence of alerts is:
First : "originalData 2"
Second : "originalData 1"
One option is that I include the Processing code inside the success function, but I cannot do it because later I want to put a logic such that I can have a buffer of data (atleast 4-5 stack deep) because I want user to get new data instantly after processing code for current data, rather than wait for the data to be retrieved through php.
Ajax uses asynchronous processing model, where once the request to server is sent the client will executing the next statements without waiting for the response to comeback. Once the server response either the success or failure callback will get called depending on the status of the response.
You need to put all your processing using the data from the ajax call in the success callback.
ex:
$.ajax({
....
}).done(function(data) {
//To all you post processing here
}).fail(function(){
//Do your error handling here
});
A ajax call doesn't stop the next line execution so you will have to do something like below:
$(function () {
var originalData="";
$.ajax({
url: 'data.php',
data: "",
dataType: 'text',
success: function(data)
{
originalData=data;
alert("originalData 1 "+ originalData);
myFunction();
}
});
function myfunction()
{
alert("originalData 2 "+ originalData);
...
Processing code
...
}
});

prevent redirection on submit to form

I have the following code I am using to submit my form to a processing script. the form gets submitted but I am getting redirected to the response html from the server. I want to stay on the same page and run the callback function inside success:
the response header is sending
location:http://url-I-am-Redirected-to-and-don't-want-to-be.html
I am working with third party and have no control over the server side code I am submitting to.
$('#go').click (function () {
$.ajax ( {
type: 'POST',
data: $('#newsletter form').serialize(),
url: $('#newsletter').attr('action'),
success: function(){
$('#image_container').hide (1000,
);
}
});
}
At the end of the click block add
return false

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.

Returning Json from controller, never a success

I'm successfully posting to my controller with the following code, however, success is never being hit only error. What am I doing wrong?
JS:
$.ajax({
url: '/Home/Subscribe',
type: 'POST',
dataType: 'json',
data: { email: $('#sube').val() },
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
Controller:
[HttpPost]
public JsonResult Subscribe(string email)
{
return Json(new { foo = "bar", baz = "Blech" });
}
In IE, press F12 to open developer tools. Go to Network tab and click on Start Profiler. Send a request to your Subscribe action - in a list below you will see details of sent request and returned status code. Double click on request to see details - you can then see body of your response. If the request failed with a server error, you will see that error in a body of your response.
One wrong thing I see with your code is that you have hardcoded the url:
url: '/Home/Subscribe'
You should never do this. You should always use url helpers when generating urls in an ASP.NET MVC application:
url: '#Url.Action("Subscribe", "Home")'
Also you are saying that the error callback is always hit but you didn't say what you observed in FireBug or Chrome Developer toolbar when you tried to analyze the AJAX request. If you had done this you would have seen the exact cause of failure for the request because you would have seen what request is sent to the server and what response does the server sends back to the client.
The following is my jQuery ajax snippet that works. Your controller looks right. I assume you have verified it is actually getting called by using a breakpoint.
var p = {
email: $('#sube').val()
};
$.ajax({
url: '#Url.Action("Subscribe", "Home")'
type: 'POST',
data: JSON.stringify(p),
dataType: "text json",
contentType: "application/json",
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});

Resources