Search code examples
jqueryajaxjspobjectobject-to-string

Ajax result print [object HTMLInputElement]


I want to receive data using ajax. But when use this code, result prints [object HTMLInputElement]. Can I change object to string?

Here's My code in JSP what use ajax.

$('select#product').change(function() {

        var param = "code=" + $('#product').val();

        $.ajax({
            url : 'add_products/add_products.jsp',
            contentType : "application/x-www-form-urlencoded; charset=UTF-8",
            data : param,
            type : 'POST',
            dataType : 'text',
            success : function(data, textStatus, jqXHR){
                $('#color').val(color);
                $('#price').val(price);
            }
        });
    });
...
<td>
    <input type="text" id="color" class="form-control" name="color"  />
</td>
<td>
    <input type="text" id="price" class="form-control" name="price" value="0"  />
</td>

And This is add_products.jsp what receive the upper jsp.

product_code = request.getParameter("code");

try {
    query = "select * from new_product where product_code='"+product_code+"'";
    rs = stmt.executeQuery(query);
    while (rs.next()) {
        size = rs.getString("sizes");
        color = rs.getString("color");
        price = rs.getString("price_cny");

        out.println(color);
        out.println(price);

    }
} catch (SQLException e) {
    out.println(e);
} finally {
}

Thanks.


Solution

  • Change your server code to this...

    product_code = request.getParameter("code");
    
    try {
        query = "select * from new_product where product_code='"+product_code+"'";
        rs = stmt.executeQuery(query);
        while (rs.next()) {
            size = rs.getString("sizes");
            color = rs.getString("color");
            price = rs.getString("price_cny");
    
            out.println(color+"_"+price);                //concatenate 2 values
    
        }
    } catch (SQLException e) {
        out.println(e);
    } finally {
    }
    

    And your client code to this...

    $('select#product').change(function() {
    
            var param = "code=" + $('#product').val();
    
            $.ajax({
                url : 'add_products/add_products.jsp',
                contentType : "application/x-www-form-urlencoded; charset=UTF-8",
                data : param,
                type : 'POST',
                dataType : 'text',
                success : function(data, textStatus, jqXHR){
                    var values = data.split("_");       //get your 2 values seperated
                    $('#color').val(values[0]);
                    $('#price').val(values[1]);
                }
            });
        });