XMLHttpRequest 400 Bad request during AJAX call on second request - ajax

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

Related

ajax - GET request keeps using same old cookie on each session

Here is my two ajax requests:
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded ",
url: "https://example.com/j_spring_security_check",
data: { j_username: "mmm#mmmm.com", j_password: "mmmm" },
error: function (request, status, error) {
alert("POST LOG IN REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
$.ajax({
type: "GET",
dataType: "json",
xhrFields: {
withCredentials: true
},
url: "https://mmm.com/rest/xxx/",
success: function(output, status, xhr) {
var flight = output;
alert(flight[0].flight.toAirport.name);
//return flight;
},
error: function (request, status, error) {
alert("GET ALL FLIGHTS REQUEST:\t" + request + "\nSTATUS:\t" + status +
"\nERROR:\t" + error);
}
});
When I run the code and use firebug - the second request keeps using the same old cookie in every new session. What I want to happen is that the second request will use the cookie from my first POST(login) request. I have tried several variations of withCredentials: true/false and crossDomain: true/false on both requests.
When i clear the cookies, the get request will create it's own cookie. Then I refresh the page to let the script run again. The POST request will create a new cookie(as it should), but the get request will re-use the cookie it made before.

JQuery.Ajax POST request to Azure returning bad request

I have mobile services configured on my Azure database and I am trying to send a POST request to update the data. The service keeps returning a bad request and I fear its because of the format of my JQuery.Ajax request. I have tried a number combinations but I can't see what I'm doing wrong. The schema of the request can be found here (http://msdn.microsoft.com/en-us/library/windowsazure/jj677200.aspx), any help would be appreciated.
function RegisterPatient(){
var wsUrl = "https://vervemobile.azure-mobile.net/tables/ref_*****";
var data = {"YearOfBirth":1970,"Sex":"M","ControlGroupMember":false,"OrganisationID":null,"Type":null}
$.ajax({
url:wsUrl,
type: "POST",
data:data,
beforeSend: function (request)
{
request.setRequestHeader("X-ZUMO-APPLICATION", "******");
request.setRequestHeader("Content-Type", "application/json");
},
success: function(data, textStatus, jqXHR)
{
alert(JSON.stringify(data));
},
error: function (jqXHR, textStatus, errorThrown)
{
alert(JSON.stringify(jqXHR));
console.log(JSON.stringify(jqXHR));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
}
});
}
Thanks in Advance,
Bradley
The request requires a json body to be sent, so you have to stringify your data.
...
$.ajax({
url:wsUrl,
type: "POST",
data: JSON.stringify(data),
...

jQuery Ajax Get Doesn't Pass Received Data Into Success Function at Internet Explorer

My question is when I use jQuery ajax get, I am getting data at response body however it doesn't pass into success function. How can I make it work?
I am making an ajax put but it doesn't work at ie9 (works on other browsers) so I changed it like that just for test:
$.ajax({
async : false,
type: 'PUT',
contentType: 'application/json',
url:updateUrl + "?_" + new Date().getTime(),
data: JSON.stringify(model),
cache: false,
dataType: "json",
dataFilter: function(data) {
var resp = eval('(' + data + ')');
return resp;
},
success: function(data, status, xhr) {
alert("success> " + data.property);
alert(typeof data);
r = resultResponse(data);
},
error: function(data, status, xhr) {
alert("error> " + data.responseText);
try {
r = error($.parseJSON(data.responseText));
} catch (err) {
//Handle error
}
}
});
data is alerting as undefined. My put data is sending correctly, my server side works well and send response to client however I get undefined instead of data. After some tests I realized the problem:
When I capture network communication packets at ie 9 response body is what I want. However success function can not handle it. If needed, I can give more information about my server(I could make it work when I write the data to response instead of using jackson json mapper at Java - it was working and the only difference was that was not included ta working version at response headers:
Key Value
Content-Type application/json;charset=UTF8 )
I think that the problem can be handle at client side, I think not with server side.
Any ideas?
EDIT: I tried that style:
$.ajax({url: "/url",
dataType: "text",
success: function(text) {
json = eval("(" + text + ")");
// do something with JSON
}
});
However response header is still:
Key Value
Content-Type application/json;charset=UTF8
The problem was wrong charset. It was UTF( instead of UTF-8).

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

ajax GET call with node.js / express server

I´m trying to write a small ajax live search for node.js. First of all here is my Clientside code:
$('#words').bind('keyup', function(){
getMatchingWords($('#words').val(), function (data){
console.log('recieved data');
console.log(data);
$('#ajaxresults').show();
});
});
function getMatchingWords(value, callback) {
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
type: 'GET',
dataType: 'json',
success: function(data) { if ( callback ) callback(data); },
error : function() { if ( callback ) callback(null); }
});
}
and here ist my serverside route:
app.get('/matchword/:value', function(req, res) {
console.log(req.params.value);
res.writeHead(200, {'content-type': 'text/json' });
res.write( JSON.stringify({ test : 'test'}) );
res.end('\n');
});
it works but i don´t recieve any data. data in the callback function is always null. so what i am doing wrong? thx for the help
Change
$.ajax('http://127.0.0.1:3000/matchword/' + value + '/', {
to
$.ajax('/matchword' + value + '/', {
What's the URL that you're making the $.ajax() request from? If the page containing that client-side JS wasn't also loaded from 127.0.0.1:3000, the error you're seeing is due to the same-origin requirement on AJAX requests.
hey better late than never...
I was looking at your problem because I am also trying to put a simple live search together with an express.js back end.
first of all I put your url into a local variable. As I don't think that was your problem.
Particularly if your express / node log was showing a 200 response. then the url was fine...
It seems your function wasn't returning data (correct ?) if so try this.
var search_url = "..."// your url
function getMatchingWords(value, callback) {
$.ajax(search_url, {
type: 'GET',
dataType: 'json',
success: function (data, textStatus, jqXHR) {
var returned_data = data;
console.log("returned_data ="+returned_data);//comment out or remove this debug after test
callback(returned_data);
},
error: function( req, status, err ) {
console.log( 'something went wrong', status, err );
}
});
}
you might also need to add / modify your headers subject to the set up...
headers : { Authorization : auth },
type: 'GET',
dataType: 'json',
crossDomain:true,
the auth variable being an encoded auth pair somewhere else in your code (if your web service is requires some kind of auth...

Resources