freestar freestar - 6 months ago 25
Ajax Question

javascript - ajax request null data

I am trying to make an ajax request to the server. The request is send successfully, but the parameters are not appropriate in the request body.

Parameters shown in the body with browser's network tool:

{"name":"","message":"","time":1464807897670}


The name
<input>
and the message
<textarea>
fields are empty, although they should not be.

Here's my HTML input fields:

<div id="writePanel">
<p>Your Name</p>
<input id="writeName" type="text">
<p>Message</p>
<textarea id="writeArea"></textarea>
<div id="sendButton">Send</div>
</div>


Here's the JS code:

$(document).ready(function() {

var data = {

name: document.getElementById("writeName").value,
message: document.getElementById("writeArea").value,
time: new Date().getTime()
};

$("#sendButton").click(function () {
$.ajax({
type: "POST",
url: "message.receive",
contentType: "application/json",
data: JSON.stringify(data),
success: function (response) {
// ...
}
})


})
})


What am i missing?

Answer

It looks like you are setting your values at the beginning rather than when the button is pressed. Try setting the values in the data object in the click function before the ajax call:

$("#sendButton").click(function () {

    var data = {    
        name: document.getElementById("writeName").value,
        message: document.getElementById("writeArea").value,
        time: new Date().getTime()
    };

    $.ajax({
        type: "POST",
        url: "message.receive",
            contentType: "application/json",
            data: JSON.stringify(data),
            success: function (response) {
                // ...
            }
    })

})