Firefox
Firefox

Reputation: 951

Ajax call from Greasemonkey to a Servlet: response failure

Though I've programming experience, am completely new to GS, JS, or anything related to UI.

Scenario: Making an AJAX call from Greasemonkey script to a Servlet

Greasemonkey/JS Code:

function getResultsData(query){
alert("Getting the Data");
$.ajax( 
    {
    cache: false,   
    data: {"q":query},      
    dataType:"text",
    url: "http://myserver.com:8000/search?",
    success: processData        
    }); //end of $.ajax }

function processData(data){
alert("Got the data");
var myResultDiv = document.getElementById("searchRes");
myResultDiv.innerHTML = data; }

Servlet Code:

        System.out.println("-----------This is an AJAX call------------------");
        //Commented the original logic
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write("Text from Servlet");

Problem:

Can someone please help.

NOTE Website on which greasemonkey runs, and my server belong to same domain, i.e.

Greasemonkey website: wwww.example.com

My server: www.myserver.example.com

Upvotes: 1

Views: 541

Answers (1)

Firefox
Firefox

Reputation: 951

Thanks to @mattedgod. His comment triggered me to research more and I found the answer.

Add the following snippet to make it work.

response.setHeader("Access-Control-Allow-Origin", "*");

Surprisingly, it doesn't work if I explicitly specify my own server's full http address in the header. I yet to find out why.

Upvotes: 2

Related Questions