Ajax GET request always fails - javascript

I'm trying to connect to a server and get a Json that contains an id that I need.
The request fails every time. I'm new to javascript and can't figure out what the problem can be.
$(document).ready(function(){
$.ajax({
type: "GET",
url: 'http://www.dais.unive.it/~cosmo/esercitazione3/captcha.php?getIdentifier',
timeout: 2000
}).done(function(data){
var obj = JSON.parse(data);
var session_id = obj.id;
$("#test").append("Session id: "+ session_id + "<br/>");
}).fail(function(){
alert("Error");
});
});

Please use the below code , just add jsonp datatype
$(document).ready(function(){
$.ajax({
url: 'http://www.dais.unive.it/~cosmo/esercitazione3/captcha.php?getIdentifier',
dataType: 'jsonp',
success: function (response) {
console.log(response.id);
var session_id=response.id;
},
error: function (jqXHR, exception) {
console.log("FAILURE");
},
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Your problem here is that you are not authorized to get data from this server due to the same-origin policy implemented in all web browsers.
Here you have two solutions:
JSONP (JSON with padding)
CORS (Cross-Origin Resource Sharing)
Since you try to access a URL from the website of your university, I guess you are not the system administrator. Thus, you cannot use CORS which is based on HTTP headers that require some configuration on the server-side.
However, you should be able to use JSONP. With jQuery, this is very easy: https://learn.jquery.com/ajax/working-with-jsonp/

Related

PhoneGap - Sending JSON encoding data error

I am using Phonegap to connect to a server to authenticate a user. The server expects the data to be Json encoded, and I will get the response back from the server.
var serviceURL = "http://appdev/PEPS-CS-Services/";
The serviceURL (APPDEV) is hosted on our network within the office.
var loginData = {
'strUniqueID' : '123',
'UserName' : 'User123',
'Password' : 'Password123'
};
I have checked the login credentials and they are fine. When I try the following:
$.ajax({
type: "POST",
url: serviceURL + "services/AuthenticationServices/authenticateUser",
data: loginData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
},
failure: function(errMsg) {
alert(errMsg);
}
});
I get the Access-Control-Allow-Origin error in my console.
XMLHttpRequest cannot load http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost' is therefore not allowed access.
I had a look around, and I was suggested to use Jsonp as the dataType in the ajax request, which does give me back the response I was looking for. However, it isn't alerted out as it should be, the console shows the url with the parameters used in the loginData variable, as below
Resource interpreted as Script but transferred with MIME type application/xml:
http://appdev/PEPS-CS-Services/services/AuthenticationServices/authenticateUser?callback=jQuery164017807046906091273_1396515434941&strUniqueID=123&UserName=Mark&Password=Password1&_=1396515434963"
When I open the link in a browser i get the correct response, as below
<ns:authenticateUserResponse xmlns:ns="http://services">
<ns:return>SESSION ID HERE</ns:return>
</ns:authenticateUserResponse>
However, I also get the Uncaught SyntaxError: Unexpected token < error below it.
I have tried to change to data: loginData to data: {'data':$.toJSON(loginData)}, but still the same error.
My questions are the following:
Am I sending the data over correctly? Why does the jQuery164017807046906091273_1396515434941 get added to the URL before the parameters?
And why am I getting the Uncaught SyntaxError too?
Is this because the server is sending back the incorrect format of the data? It is currently sending back XML
Any help would be greatly appreciated, thanks
This is a familiar cross context issue, you are not allowed to request resource from another domain with simple ajax call and expect a result.
Instead, use a jsonp call and regiter a callback function to call when return result:
var success = function(data){
/* parse JSON */
data = $.parseJSON(data);
/* show json parsed data */
alert(data);
};
$.ajax({
url: serviceURL + "services/AuthenticationServices/authenticateUser",
dataType: 'jsonp', //use jsonp data type in order to perform cross domain ajax
crossDomain: true,
data: loginData,
success: success,
error: function(errMsg) {
alert(errMsg);
}
});

$.post (to different domain) not working (node.js / express app on port 8081)

I receive the error POST https://thewebsite.com 400 (Bad Request) when using $.post that way:
$.post("https://website.com/blabla",
{
domain: "infoinfo.com",
room: "someInfo",
application: "someInfo",
ident: "someInfo",
},
function (data,status) {
alert("Data: " + data + "\nStatus: " + status);
});
I tried setting res.header('Access-Control-Allow-Origin', "*"); in my route but that didn't work.
Any ideas on how I could fix this?
Ps.: The server I am posting to is service website (xirsys.com), I am pretty sure they allow external domains already. I'll contact them during the day if I can't find a solution (I am using the jQuery post as they suggested :/
Try to add this to your AJAX call:
contentType: "application/json; charset=utf-8",
dataType: "json"
Another reason maybe because of the same origin policy:
In computing, the same origin policy is an important security concept
for a number of browser-side programming languages, such as
JavaScript. The policy permits scripts running on pages originating
from the same site to access each other's methods and properties with
no specific restrictions, but prevents access to most methods and
properties across pages on different sites.
You can find out more informations about this issue from MDN docs or doing some research on Google about this topic.
You can try to use $.axax() like this:
$.ajax({
type: 'POST',
url: "https://website.com/blabla",
data: {
domain: "infoinfo.com",
room: "someInfo",
application: "someInfo",
ident: "someInfo"
},
dataType: "json",
contentType: "application/json",
success: function (e) {
alert("Data: " + data + "\nStatus: " + status);
}
});
This is due to the Same-origin policy. All the browsers as a security measure would not allow any cross domain requests.
http://en.wikipedia.org/wiki/Same-origin_policy
Like in your case you are posting to thewebsite.com domain from a different domain. A work around is to use the jsonp (the server should support json padding) from the jquery.
Check these sites for more info
http://www.jquery4u.com/json/jsonp-examples/
http://en.wikipedia.org/wiki/JSONP
http://stackoverflow.com/questions/6871021/how-to-enable-cross-domain-request-on-the-server
SAMPLE REQUEST:
$.ajax({
url: "http://yoururl",
type: "POST",
crossDomain: true,
data: JSON.stringify(somejson),
dataType: "json",
success: function (response) {
alert("success");
},
error: function (xhr, status) {
alert("error");
}
});
SAMPLE RESPONSE IN PYTHON:
response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")
return response
The link I was posting to was actually not good. The service I am using updated the link in their API to reflect the right one.

Jquery unable to get the response from WCF REST service

I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
})​;​
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);

jQuery URL Get error on Firefox

Can anyone point out why my JavaScript function is falling into the error function rather than the success function? Firefox on Ubuntu
$(document).ready(function() {
console.log( "Start" );
$.ajax({ type: "GET", dataType: "html", url: "http://slashdot.org",
error: function(request, status) {
console.log("Error");
},
success: function(data) {
console.log("Sucess");
}
});
console.log( "End" );
});
Because of same-origin security restrictions, you cannot issue ajax calls to domains other than the domain of your current web page.
Possible work-arounds depending upon what your actual problem is:
Build a server proxy on your domain that will fetch the web page from the other site for you so you can send the request to your own domain.
Use an iframe to display the content from another domain.
It is very common issue with Cross Domain Policy. If you are using jQuery Ajax then you can use JSONP to do cross domain query. Document at http://api.jquery.com/jQuery.ajax/
$.ajax({ type: "GET", dataType: "json", url: "https://api.instagram.com/v1/tags/stackoverflow/media/recent?client_id=0324ff3396ef4ab49697505678e734f5&callback=?",
error: function(request, status) {
console.log(request, status);
},
success: function(data) {
console.log(data);
}
});

jQuery AJAX Cross Domain with BASIC Authentication

I'm attempting to make use of the Beanstalk (beanstalkapp.com) API by pulling data into a webpage so people can view it without accessing my SVN.
What I'm doing to try and access it is by using an AJAX request through jQuery. The code is below, but I get an error each time, and can't return the data.
<script type="text/javascript">
$(document).ready(function() {
var tok = 'username' + ':' + 'password123';
hash = btoa(tok);
authInfo = "Basic " + hash;
$.ajax({
url: "http://username.beanstalkapp.com/api/changesets.json",
beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", authInfo); },
type: "GET",
async: false,
crossDomain: true,
dataType: "json",
success: function(html){
console.log(html);
},
error: function(html){
console.log('error');
}
});
});
</script>
If I access the URL straight through my browser (http://username.beanstalkapp.com/api/changesets.json) it works just fine and returns the json. However, I cannot get the AJAX to return it. Any help is appreciated. Thanks!
You will need to make proxy for cross-domain ajax requests.
Usual scenario looks like this:
Client send ajax request to server
Your server forwards request to external/remote server
Waiting on response from remote server
Parse and process response from remote server
Send response back to client
If you are using php you can send requests with curl, and it is pretty easy to implement. I have wrote article on this topic recently http://www.svlada.com/proxy-ajax-requests-curl-and-symfony-2/.
you cant get a json from other domain than yours. this is a security issue called same origin policy to get over it use JSONP not JSON.
Check this jsfiddle. The username and password is incorrect. Give the correct username and password and check it once again.

Categories