Neel
Neel

Reputation: 2100

request.getParameter() returns null when used against AJAX call

I am invoking a jsp using an AJAX call:

        var httpRequest = null;
        if (window.XMLHttpRequest) {
            httpRequest = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        if (!httpRequest) {
            console.error('Cannot create an XML HTTP instance');
            return false;
        }
        httpRequest.onreadystatechange = function() {
            try {
                if(httpRequest.readyState === 4) {
                    ...
                }
            } catch(e) {
                args.error(e);
            }
        };
        httpRequest.open(args.method, args.path, args.sync);
        httpRequest.setRequestHeader(...);
        var q = '', first = true;
        for(var key in args.params) {
            if(params.hasOwnProperty(key)) {
                if(first) {
                    first = false;
                } else {
                    q += '&';
                }
                q += encodeURIComponent(key) + '=' + encodeURIComponent(args.params[key]);
            }
        }
        httpRequest.send(q);

for this request, I am passing the query params as:

{
    from: 'xyz',
    to: 'abc'
}

The query being built is also correct:

from=xyz&to=abc

On my JSP however, when I do request.getParameter("from"), I get null. How should I fix this?

Upvotes: 1

Views: 1804

Answers (1)

Neel
Neel

Reputation: 2100

Found the solution:

Missing header: httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

This is necessary for post requests.

Upvotes: 1

Related Questions