Jake
Jake

Reputation: 225

getParameters keeps returning null

So, I'm having trouble retrieving information from my the client-side jsp. The javascript executes, and the alert prints, however query becomes null in the java servlet, and null is then written to the logger. I can't seem to figure out why the query is now null.

HTML:

<div id="query">
    <div id="querybar">
        <form onsubmit="query();return false;" method="get">
        <input type="text" id="querytext" placeholder="Run a query" name="querytext">
        </form>
        <div id="queryimg-container">
            <img src="styles/magnifyingglass.png" id="queryimg" alt="" />
        </div>
    </div>
</div>

JS:

function query() {
    $.get('QueryHelper', function(data) {
        alert("Somesortofalert");
    });
}

Java Servlet:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String query = request.getParameter("querytext");
    response.setContentType("text/plain");
    @SuppressWarnings("resource")
    PrintWriter writer = response.getWriter();
    sLogger.info(query);
}

Can anyone see anything wrong? I'm super stumped here.

Upvotes: 0

Views: 232

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123423

It'll be null because no parameter by that name is being sent with the Ajax request.

Despite being started by an onsubmit event, $.get() doesn't have any automatic knowledge of the <form>. It's up to you to gather or specify any parameters to be included with the request using the data parameter.

$.get('QueryHelper', { querytext: 'foo bar' }, function (res) {
    // ...
});

Provided you have a reference to the <form> or its inputs, you can use .serialize() to prepare the fields' names and values as data.

<form onsubmit="query(this); return false;" method="get">
<!--                  ^^^^                            -->
function query(form) {
    //         ^^^^

    $.get('QueryHelper', $(form).serialize(), function (res) {
        //               ^^^^^^^^^^^^^^^^^^^

        // ...
    });
}

Upvotes: 1

Related Questions