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

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.

Related

NODE.js - How to make an AJAX request from the DOMContentLoaded listener

I am trying to send data via an Ajax request from the DOMContentLoaded listener in my global.js
The following code produces error 400 (Bad request), and I'm not clear why. If I submit the same payload using Postman to that Url, I get success.
Global.js
document.addEventListener('DOMContentLoaded', function() {
var obj1 = document.getElementById('myObject');
// A bunch of logic to retrieve data to be sent to the server
// that if successful triggers a callback function
ProcessEvent: function (info){
// Update the database record here
//
alert("Making an AJAX call");
var xcall = $.ajax({
url: "http://127.0.0.1:3000/cashiers/jsonset",
type: 'post',
contentType: 'application/json',
data: obj1.items,
dataType: "json",
success: function(json) {
alert('Success : '+ json.reponse);
},
error: function(res){
alert("Error "+res.status+" with "+res.statusText);
}
}).done(function( msg ){
alert( "Data Saved: " + msg );
});
}
});

ajax http get auto change to http post due to set custom header

i have a php API server with below setting :
and i try to consume the API server by below ajax:
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
//contentType: "text/plain",
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("authorization", "Basic " + oAuthKey);
},
complete: function (xhr, status) {
//
}});
request = $.ajax({
type: "GET",
url: "http://www.example.com/testAPI/users/10004",
async: false,
});
request.done(function (response, textStatus, jqXHR) {
var msg = textStatus;
});
request.fail(function (jqXHR, textStatus, errorThrown) {
var msg = errorThrown;
});
when i watch the activity in Fiddler, the request is using http options instead of http get. i know this is because i am setting xhr.setRequestHeader cause preflight request. Due to the API server required authentication, i have no choice and need to set the customer header.
when i try to run above request inside Fiddler, it manage to return correct json data. But when i run the above java script in my phone gap app, it return error.
*** In fiddler, it will auto use http get, so that is why no error. In my app, it keep using http options.

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

Ajax POST request to ODATA service throws Invalid HTTP status code 501

I have the following code which I wish to use for inserting a record into an entity of an ODATA service.
The post request throws a XMLHttpRequest cannot load Invalid HTTP status code 501.
Apparently GET request works fine. Can anyone suggest a way to find out the problem ? Does my WCF Service has a problem ?
var data = { application_id: 777 , user_id: 'test' };
var data = JSON.stringify(data);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
datatype: 'json',
url: oDataURL + 'application_admins',
data: data,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
account = data.d;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});

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