Ajax request in extjs fires success although response is false - ajax

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!');
}

Related

Ajax response is not received before application is loaded in extjs

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');},
});

How can I access the response code in Ajax requests?

As I ask in the title, how can I access the status code of the response in the done callback of an Ajax request?
var isUsernameGood = new Promise(
function(resolve, reject) {
console.log("Starting username check");
$.ajax({
type: "POST",
url: '/username',
contentType:'application/json',
data: JSON.stringify({username: document.getElementById("username").value})
})
.done(function(data, textStatus, xhr){
console.log("done");
console.log(data); console.log(textStatus); console.log (xhr);
resolve(xhr.status);
})
.fail(function(data, textStatus, xhr){
console.log("fail");
console.log(data); console.log(textStatus); console.log (xhr);
reject(xhr.status);
});
}
);
EDIT: The log prints "fail" and then "Object { readyState: 4, getResponseHeader: getResponseHeader(), getAllResponseHeaders: getAllResponseHeaders(), setRequestHeader: setRequestHeader(), overrideMimeType: overrideMimeType(), statusCode: statusCode(), abort: abort(), state: state(), always: always(), catch: catch(), … }", then "error" and "unknown" althought in the Network tab of the inspect feature of the browser I see the request and also the response with its status code.
I'm noticing that in the Object corresponding to printing "data" in fail callback there are these fields:
i.e. it seems strangely that the status code is inside the "state" field rather than statusCode one. Do I have to access it from "state"?
There are several ways to access the response from an ajax call, see for example:
Get Http Status Code from an ajax response with jquery
Hope this helps!

XMLHttpRequest 400 Bad request during AJAX call on second request

I have some weird issue in which during AJAX call in MVC with POST method it will return 400 BAD Request randomly after second / third call on server but in local system it works properly.
I have pass same parameter during each call but randomly it will return 400 error on server.
Below is my AJAX call code:
function RunSimulation() {
ShowProgress();
var url = GetDomainURL() + "/Project/RunSimulation";
var data = $("form").serialize();
var random = Math.random();
alert('multipart/form-data;charset=UTF-8; boundary='+random);
$.ajax({
url: url,
type: 'POST',
data: data,
async: false,
cache: false,
contentType: 'multipart/form-data;charset=UTF-8; boundary='+random,
// timeout: 60000 * 10,
success: function (data) {
alert('sucess');
HideProgress();
},
error: function (jqXHR, textStatus, errorThrown) {
HideProgress();
}
});
}
I have stuck in this issue in last 2 days so please help me if anyone have any idea on this.
Below is my request body
__RequestVerificationToken=n96WSaViL9XKPZZArj0aqnGTxMGts5P5OJxO9-PdgcJUjoB3HKcK3_LPHa4I3IbDDModNpFl6RLxDSrr7eYOmIBOzQS99NSUyF6V9Zl-wtMVRaVPU_KomFXie58t8EjEhNhCHGxcM-9V-bZHC0_8twzFxaEkef6lwOtbhGfIx7E1&TabIndex=5&SubmitIndex=0&Mode=&ProjectHeader.ProjectHeaderId=79&SiteInformation.CalculateAnnualPercentage=False&SiteInformation.IsOSRSizing=True&ProjectHeader.SiteCount=2&hdnUserType=2&hdnUserOSR=True&ProjectHeader.ProjectHeaderId=79&ProjectHeader.Region=1&ProjectHeader.Country=Canada&ProjectHeader.State=AB&ProjectHeader.ProjectName=Test+Project&ProjectHeader.City=&ProjectHeader.ProjectNumber=79&ProjectHeader.DominantLand=2&ProjectHeader.OtherState=&ProjectHeader.ProjectDate=09%2F09%2F2015&ProjectHeader.ProjectDesignBy=vaibhavi+pandya&ProjectHeader.Notes=&ProjectHeader.FirstName=vaibhavi&ProjectHeader.LastName=pandya&ProjectHeader.Email=vpandya%40conteches.com&ProjectHeader.PhoneNumber=878-787-8787&ProjectHeader.Company=ei&ProjectHeader.EORFirstName=&ProjectHeader.EORLastName=&ProjectHeader.EOREmail=&ProjectHeader.EORPhoneNumber=&ProjectHeader.EORCompany=&SiteInformation.RainFallStationName=EDMONTON&SiteInformation.RainFallStation=1&SiteInformation.RainFallStationName=EDMONTON&SiteInformation.RainFallStationState=Alberta&ManageRainFallStation.RainFallStationFilter.State=Alberta&ProjectHeader.Country=Canada&ManageRainFallStation.RainFallStationFilter.SelectedCountry=&ManageRainFallStation.RainFallStationFilter.Location=&SiteInformation.PeakRainfallIntesityCkecked=false&SiteInformation.PeakRainfallIntesityCkeckedValue=0.00&StationState=&SiteInformation.ProjectHeaderId=79&SiteInformation.SiteId=127&SiteInformation.SiteName=Site+1+&SiteInformation.SiteArea=5&SiteInformation.Imperviousness=60.0&SiteInformation.TSSRemoval=80.0&SiteInformation.peakConvey=&SiteInformation.RunOff=&SiteInformation.WQF=&SiteInformation.IsOilPara=False&SiteInformation.OilParaValue=&SiteInformation.Width=447.00&SiteInformation.Slope=2&SiteInformation.ImperviousD=0.518&SiteInformation.PerviousD=5.08&SiteInformation.ImperviousM=0.015&SiteInformation.PerviousM=0.25&SiteInformation.MaxI=61.98&SiteInformation.MinI=10.16&SiteInformation.DecayRate=0.00055&SiteInformation.RegenerationRate=0.01&SiteInformation.DailyEvap=2.54&SiteInformation.Flow=0&SiteInformation.Freq=12&SiteInformation.FilterationWinterMonthsChecked=false&SiteInformation.WinterStartMonth=&SiteInformation.WinterEndMonth=&SiteInformation.InletInvertElev=&SiteInformation.PipeDiameter=&SiteInformation.OutletInvertElev=&SiteInformation.PipeMaterial=&SiteInformation.RimElev=&SiteInformation.IsMultipleInlets=False&SiteInformation.WaterLevelElev=&SiteInformation.IsGrateInlet=False&SiteAttenuationManage.ManageSiteAttenuationList%5B0%5D.Flow=0.00000&SiteAttenuationManage.ManageSiteAttenuationList%5B0%5D.Storage=0.00000&SiteAttenuationManage.ManageSiteAttenuationList%5B0%5D.IsDeleted=False&SiteInformation.UpstreamFlowDiversionValue=0.00000&SiteInformation.ParticleDistribution=5&SiteInformation.IsRainfallOSRAuthorized=False&SiteInformation.IsUserOSRAuthorized=False&SiteInformation.NoNullIsOSRSizing=True&SiteInformation.NoNullIsOSRSizing=true&SiteInformation.NoNullIsOSRSizing=false&SiteInformation.IsFlocc=true&SiteInformation.IsFlocc=false&SiteInformation.Flocc=20&ManageTSSFunction.ManageTSSFunctionList%5B0%5D.Name=Build+Up%2F+Wash-off&ManageTSSFunction.TSSRblValue=1&ManageTSSFunction.ManageTSSFunctionList%5B1%5D.Name=Event+Mean+Concentration+(EMC)&ManageTSSFunction.ManageTSSFunctionList%5B2%5D.Name=Power+Wash-off&ManageTSSFunction.ManageTSSFunctionList%5B3%5D.Name=Power+Wash-off+(Winter+Only)&SiteInformation.BuilUpPower=0.40&SiteInformation.ExpoWashOff=0.20&SiteInformation.TargetEvent=125.00&SiteInformation.AvailabilityA=0.05&SiteInformation.AvailabilityB=0.04&SiteInformation.AvailabilityC=1.10&SiteInformation.PSAvailability=400.00&SiteInformation.PowerWashOffFactor=0.08&SiteInformation.PowerWashExp=1.15&SiteInformation.PWWinterStartMonth=1&SiteInformation.PWWinterEndMonth=1&SiteInformation.EMC=444.00&SiteInformation.WinterSand=&SiteInformation.SandingStartMonth=&SiteInformation.SandingEndMonth=&WinterPSDMappingManage.ManageWinterPSDHeaderList%5B0%5D.ParticleDiameter=0.00&WinterPSDMappingManage.ManageWinterPSDHeaderList%5B0%5D.Percentage=0.00&WinterPSDMappingManage.ManageWinterPSDHeaderList%5B0%5D.SpecialGravity=0.00&WinterPSDMappingManage.ManageWinterPSDHeaderList%5B0%5D.IsDeleted=False&SiteInformation.CalculateAnnualPercentage=false&SiteInformation.RecommendedModel=OSR+4000%0D%0A&SiteInformation.SiteId=127
This was hinted at in comments, but why are you setting Content-Type to use multipart/form-data? You are not sending multipart/form-data, you are sending application/x-www-form-urlencoded data. There is no "multipart" attachment, so no boundary is required.
Try removing altogether the contentType line in your ajax call; the Content-Type will default to application/x-www-form-urlencoded, which is what is needed.
Also, better use async: true otherwise your page will be unresponsive while it blocks waiting for a response to the ajax request - unless that's what you want.
I am not sure that this is the cause of the 400 bad request errors, but at least this removes one possibility.
I have use below code as per your suggestions during AJAX Call
function RunSimulation() {
ShowProgress();
var url = GetDomainURL() + "/Project/RunSimulation";
var data = $("form").serialize();
var random = Math.random();
$.ajax({
url: url,
type: 'POST',
data: data,
async: true,
cache: false,
// timeout: 60000 * 10,
success: function (data) {
alert('sucess');
HideProgress();
},
error: function (jqXHR, textStatus, errorThrown) {
HideProgress();
}
});
}
But still get error as shown below
Bad Request Error

Getting blocked response even if status code 200 is returned

I have MVC web app and I am consuming some WEB API with AJAX calls. I try to login, so I send username and password, to get the needed info (token etc.).
var loginData = {
grant_type: 'password',
username: 'SomeName',
password: 'SomePass'
};
$.ajax({
type: 'POST',
url: '/Token',
contentType: "application/x-www-form-urlencoded; charset='utf-8'",
data: loginData,
success: function (response) { // 200 Status Header
localStorage.setItem('token', response.access_token);
alert('Success!');
},
error: function (response) { // 500 Status Header
alert('Error!');
}
});
The problem is - After the request is send, the server returns the response with all the informations, but it is somehow blocked.
It returns status code - 200 with all the information but the response is blocked/aborted
Session properties (provided by Fiddler)

Alert is coming before response

I have this ajax function which validates the user provided key. but the alert comes before the ajax response and due to which if the user provide a wrong key even can get access
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
var key = $('#downloadkey').val();
var dataString = {KEY:key};
$.ajax({
url: "/mediabox/home/validate_key",
type: 'POST',
data: dataString,
success: function(msg) {
if(msg=="true")
{
alert("do something");
}
else
{
alert("Your download key is either wrong or you didn't provide it.");
return false;
}
}
});
});
});
What makes you believe the alert is coming before the response? The success handler is only invoked after the response has been successfully received client-side.
To confirm, you can edit your success handler to log the response:
success: function(msg) {
console.log(msg);
if(msg=="true")
{
alert("do something");
}
else
{
alert("Your download key is either wrong or you didn't provide it.");
return false;
}
}
Also, if you're using the return false to deny access to the user by blocking the HTML action that, won't work due to the asynchronous nature of AJAX.
The success function is called when the request completes.
success(data, textStatus, jqXHR)Function, Array
A function to be called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event.
The code within the success handler will only execute once the AJAX request is completed. If you are getting an alert before hand then that indicates that the request completed properly.

Resources