Senor_Wilson
Senor_Wilson

Reputation: 47

Ajax GET request is null when successful

I'm fairly new to JS, and I've run into an issue when trying to send a GET request to my server via ajax call. The server is receiving the request and is executing the get properly, and the ajax call does succeed(executes succeed function), but the response is null. The GET works without issues when tested in Postman.

Ajax Call:

url = "http://localhost:8080/EmployeeLookup/SearchServlet?search=test"
$.ajax({
    url: url,
    type: 'GET',
    success: display,
    error: function(xhr,status,error){ alert(status); },
}); 

The request is being sent to the same server that this page is served, so there isn't any issue with Access-Control-Allow-Origin.

Any help would be appreciated.

Thanks in advance.

Edit:

display function: Just testing if it is null for now. Testing with === also returns true.

function display(json) { 
    if(json == null) { 
        $("#text").replaceWith(json); 
    } else { 
        $("#text").replaceWith("Response was null. "); 
    }
}

The JSON that is sent back looks something like:

{
     "seachResult": "someresult" 
}

Upvotes: 0

Views: 3417

Answers (1)

Kevin B
Kevin B

Reputation: 95031

You should always specify your dataType so that jQuery will consistently parse it properly.

// the http portion is not needed for same-domain requests
var url = "/EmployeeLookup/SearchServlet?search=test"
$.ajax({
    url: url,
    type: 'GET',
    dataType: 'json',
    success: display,
    error: function(xhr,status,error){ alert(status); },
}); 

function display(json) {
    console.log(json);
}

Testing if data was returned is going to take more than testing if it is null, it will NEVER be null if you're using jQuery 1.9+ and the json dataType.

Upvotes: 2

Related Questions