Ajax call bug with Chrome new version 73.0.3683.75? - ajax

My code was working fine before the Chrome update.
I make an ajax call to my server. My server receives the call, returns JSON to the client, but the answer is always empty. When I look in Fiddler I get an answer from the server.
I try with JQuery, and I also try with an xmlhttp call. Always the same result
Did new CORS policy rules apply...?
There is my xmlHTTP call
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
var theUrl = "URL";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send('{ "args" :{ "Obj":"my obj"}}');
xmlhttp.onreadystatechange = function(state,xhh,aaa){
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
alert(xmlhttp.responseText);
}
}
The ajax call is similar
$.ajax({
url: "URL",
data: '{ "args" :{ "Obj":"my obj"}}',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
async: false,
error: function (xhr, ajaxOptions, thrownError) {
if (that.Fail != null) {
that.Fail();
}
},
success : function(data){
alert(data);
}
})

I had the same problem after upgrade to Chrome 73. Thanks to #wOxxOm
This is the workaround until now:
Go to chrome://flags
Disabled the Enable network service
UPDATE:
This is not a bug, according to this announcement: https://www.chromium.org/Home/chromium-security/extension-content-script-fetches
You will need to put the Cross-Origin Fetches to the background script instead of the content script.

Related

Cannot connect to local Rest Service with AJAX (Status: 0)

I currently try to connect to a local Rest service with AJAX. However it seems as if I can't get any connection. The Rest Service runs under http://localhost:8080/LernApp/
For Testing I tried to connect to http://localhost:8080/LernApp/user/ which returns a JSON (GET).
I tested this link inside my Browser (works fine and displays the JSON) and with Postman (also works fine and gets the Answer with a status code of 200 (OK)).
However if I try to connect to it with AJAX, it fails (status code 0).
My first try was this:
var xhttp = typeof XMLHttpRequest != 'undefined' ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhttp.open('GET','http://localhost:8080/LernApp/user/',true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() {
var data;
if(xhttp.readyState==4) {
if(xhttp.status==200) {
alert("OK");
} else if(xhttp.status==404) {
alert("404");
} else {
alert("ERROR CODE: " + xhttp.status);
}
}
}
xhttp.send();
The next thing I tried was this:
$.ajax({
type: 'GET',
url: 'http://localhost:8080/LernApp/user/',
dataType: 'json',
async: true,
success: function(result) {
alert(result.message);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status + ' ' + jqXHR.responseText);
}
});
And the last thing I tried was this:
$.ajax({
type: "GET",
url: 'http://localhost:8080/LernApp/user/',
headers: {
Accept : "application/json"
}
})
.done(function (data, textStatus, jqXHR) {
alert(data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert("STATUS: " + jqXHR.status);
});
None of these seem to work. Every function returns the status code 0.
Does anyone have any idea what is happening here? Like I've said: Browser and Postman can connect to the url without and problems and retrieve the correct data.
Thanks for your help.
I finally found the solution. I should have mentioned more about my server (but since the server did well in the Browser and in Postman, I assumed that the problem would be on the client side).
Well... it was of course a server problem. The server is running on Apache Tomcat 9 with an embedded H2 database and JAX-RS (for REST Service).
If anyone else faces my problem: the solution is called CORS. If you are having the same problem, first google CORS, so that you know what it is and then you can make all of the needed settings inside the web.xml and/or context.xml of your Tomcat Project.

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.

CORS POST Request is not working in FireFox 21.0 version - It gives HTTP 405 error

Below code is in my website:
function validateRequest() {
var $form = $('form');
if ($form.valid()) {
$.support.cors = true;
var lnkey = $('#txtloan').val();
var psw = $('#txtpsw').val();
var loanServiceUrl = #Html.Raw(Json.Encode(ConfigurationManager.AppSettings["LoanServiceURL"]));
var msg = {"loan": lnkey, "psw": psw};
$.ajax({
cache: false,
async: true,
type: "POST",
url: loanServiceUrl + "ValidateRequest",
data: JSON.stringify(msg),
contentType: "application/json; charset=utf-8",
dataType: "json", //jsonp?
success: function (response) {
$(response).each(function(i, item) {
if (item.Validated.toString().toUpperCase() == 'TRUE') {
// When validation passed
$('#divResult').load('#Url.Action("GetLoanInfo", "Validate")');
$("#btnClearStatus").show();
$('#btnGetStatus').hide();
}
});
},
error: function (errormsg) {
alert("ERROR! \n" + JSON.stringify(errormsg));
}
});
}
}
I have set following setting in IIS where my service is deployed.
When I make a POST call from website, I see two calls (probably one is pre-flight call for CORS) in fiddler. This is working fine in chrome and Safari but not in Firefox. I get HTTP 405 error. I am using Firefox 21.0.
Below is the snap shot from fiddler when service is called from firefox.

codeigniter ajax internet explorer

the following code works fine in FF, opera and chrome but fails in IE
function get_modelo(modelo) {
var selState = modelo;
alert (selState);
console.log(selState);
$.ajax({
url: "site/ajax_call", //The url where the server req would we made.
async: false,
type: "POST", //The type which you want to use: GET/POST
data: "state="+selState, //The variables which are going.
dataType: "HTML", //Return data type (what we expect).
//This is the function which will be called if ajax call is successful.
success: function(data) {
//data is the html of the page where the request is made.
$('#city').html(data);
}
})
}
Can't understand the problem.
console.log in IE doesn't work or causes problems.
See here:
What happened to console.log in IE8?
and here:
Testing for console.log statements in IE
and here:
http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
or just google search IE console log
Everything else in your code looks like it would work fine.
Try this. Below will work in IE8 :P
$.ajax({
url: "site/ajax_call", //The url where the server req would we made.
async: false,
type: "POST", //The type which you want to use: GET/POST
data: { state: selState }, //The variables which are going.
dataType: "html", //Return data type (what we expect).
//This is the function which will be called if ajax call is successful.
success: function(data) {
var newDiv = $('<div></div>');
newDiv.html(data);
newDiv.appendTo("#city");
}
});

Rewrite jQuery Ajax call in AngularJS

Is there an AngularJS equivalent call to this jQuery ajax POST, with contentType and setRequestHeader?
$.ajax({
url: "http://localhost/songs",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
},
success: function(data){
console.log(data);
}
});
You'll probably want to use the $http or $resource service. In the $http doc you can see the section on Setting HTTP Headers to set the SOAPAction and the default content type will be set to json already (though you should be able to override that as well).
This might get you started and I'd be interested to see other answers for a better way because this seems limited.
var module = angular.module('myApp', []);
module.config(function ($httpProvider) {
$httpProvider.defaults.headers.post['SOAPAction'] = 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems';
});
function myController($http) {
var data = { 'value1': 1, 'value2': 2 };
$http.post('/songs', data).success(function (data) {
console.log(data);
});
}
Based on this thread I don't believe you can set the headers differently for each call but it looks like a change might be coming to the $resource service that will allow it.
Update: Must have missed it in the documentation but you can most definitely set different actions per call using $http per this post like this:
var data = { 'value1': 1, 'value2': 2 };
$http.post('/songs', data, {headers: {'SOAPActions': 'http://schemas.microsoft.com/sharepoint/soap/UpdateListItems'}})
.success(function (data) {
console.log(data);
});

Resources