sguci
sguci

Reputation: 15

Ajax GET request always fails

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

Upvotes: 1

Views: 126

Answers (2)

Badacadabra
Badacadabra

Reputation: 8517

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:

  1. JSONP (JSON with padding)
  2. 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/

Upvotes: 1

Dilip D
Dilip D

Reputation: 565

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>

Upvotes: 2

Related Questions