0

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?

2
  • Is this the only JS running? could something else be clearing the values first? Do you have other elements with the same ID on the page? Commented Jun 1, 2016 at 19:21
  • Totally missed it, @zack.lore nailed it Commented Jun 1, 2016 at 19:24

1 Answer 1

2

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) {
                // ...
            }
    })

})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.