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

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.

Related

Ajax call bug with Chrome new version 73.0.3683.75?

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.

Ajax call to another website

For some reason when I run this simple javascript snippet I get the message "Error! Status = 404 Message = error"
callPHP(1)
function callPHP(args)
{
$.ajax({
url: "http://lectiogroupgenerator.esy.es/index.php",
type: 'post',
data: { "json" : JSON.stringify(args) },
dataType: "json",
success: function (data)
{
if (data)
{
alert(data);
return data;
}
else
{
alert("Data is empty");
}
},
error: function (xhr)
{
alert('Error! Status = ' + xhr.status + " Message = " + xhr.statusText);
}
});
return false;
}
My PHP file is just:
<?php
?>
I'm guessing 404 implicates that the php could not be found, but it does exist and I have no clue why it can't find it maybe it has something to do with me making a google chrome extension?
It might be because of the CORS issue. http://lectiogroupgenerator.esy.es/index.php doesn't allow cross origin HTTP requests.
If that's not the case try explicitly defining the website in the permissions in the manifest file to allow requests in and out to that website.
The problem was caused by the Same-origin policy, it was solved when I got an SSL certificate for my website.

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