0
votes

I'm trying to fire a cors ajax request with jQuery towards a different port in the same machine, below is my code (my application is running on an appache server on port 80):

JS:

$(function(){
    jQuery.support.cors = true;
    $.ajax({
        type: "POST",
        url: "http://127.0.0.1:8080/sys_monitor/ccn",
        dataType: "text",
        contentType: "text/plain",
        data : {a: '11'},
        success : function(res){
            alert(res);
            $('#stage').html(res);
        },
        error : function(jqXHR, text, exception){
            if (jqXHR.status === 0) {
                alert ('Not connected.\nPlease verify your network connection.');
            } else if (jqXHR.status == 404) {
                alert ('The requested page not found. [404]');
            } else if (jqXHR.status == 500) {
                alert ('Internal Server Error [500].');
            } else if (exception === 'parsererror') {
                alert ('Requested JSON parse failed.');
            } else if (exception === 'timeout') {
                alert ('Time out error.');
            } else if (exception === 'abort') {
                alert ('Ajax request aborted.');
            } else {
                alert ('Uncaught Error.\n' + jqXHR.responseText);
            }
        }
    });
        });

Servlet ("post" is written to the console) running on tomcat (eclipse) on port 8080:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.getWriter().write("hello there");
    System.out.println("post");
}

using firebug I can see the request (with response code 200) and content length 11 (empty result tab), but the error function is being executed with XHR status 0

(side question1: why is firebug displaying "xml" as type ?):

(side question2: why isn't there an OPTIONS request before the POST ?):

firebug

I also tried with RESTClient plugin for firefox, and I'm getting the wanted result:

RESTClient plugin

all help/tips is welcome

1
so, did you actually enable CORS? - David Fregoli
how do we do that ? I thought this line jQuery.support.cors = true; would do it - Rima
Are you getting the same behavior when running on Chrome, the XHR object need to read the HTTP status response in order to return the proper (status's) code. I doubt this happens when you are on local machine - elsadek
thanks @DavidFregoli, it's very embarrassing, I already visited that site but didn't pay attention to it :p ; the line response.addHeader("Access-Control-Allow-Origin", "*"); in the doPost method will solve the issue. please make this as an answer so that I accept it. PS: any ideas about the side questions ? - Rima

1 Answers

-3
votes

Check this question XmlHttp Request status 0, localhost issues (javascript, ajax, php) help,

it looks like a browser issue dealing with localhost