Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a cross domain ajax call [duplicate]

Tags:

jquery

ajax

php

jsp

I have access to a API which is a JSP file and is in JSON format. I am trying to fetch those data from the JSP page to a PHP script and process them and then store in my MySQL sever.

The JSON string is valid in the JSP page I checked in few JSON Formatter and validator online.

This is my code which I am using to get JSON data from the page but, every time my ajax call fails.

$('#button').click(function(e){
var url = 'http://xxxxx:8080/StudentAPI/index.jsp';
$.ajax({
    url : url,
    dataType : 'json',
    success : function(response) {
        alert('Success');
    },
    error : function(request, textStatus, errorThrown) {
        alert(request+textStatus+errorThrown);
    }
});
e.preventDefault();
})

Please help me and any suggestion to do it in a better way is always welcomed.

like image 373
NewUser Avatar asked Oct 21 '22 10:10

NewUser


1 Answers

You are making a cross domain ajax call. So it wont work if you try it just like a normal ajax call.

One way is like to

  1. to set 'Access-Control-Allow-Origin' to '*' at the server end to which you are making the ajax request.

  2. then make a jquery ajax call with the 'crossDomain' attribute 'true' in the settings variable.

Another way would be to use jsonp

depending on on the server you are using you can find how to add cors in this article.

UPDATE

her is a w3c article which describes how to configure cors in java servlets. See the In Java servlets section.

The point is basically that the server which is giving the ajax response should be having "Access-Control-Allow-Origin" field set to "*" in the response headers.

like image 90
Mithun Satheesh Avatar answered Oct 24 '22 03:10

Mithun Satheesh