Mattias
Mattias

Reputation: 161

jquery ajax POST method doesn't execute function

I'm new to JavaScript and AJAX, and am trying to to create a simple web app consisting of a server and a JavaScript/JQuery client. It has an input field and a button. After pushing the button, a POST request consisting of the text in the field should be sent to the server, and the page should be changed to the response from the server. If there is an error, the page should be changed to an error message.

Here's my partial solution:

<!DOCTYPE html>
<html>
    <head>
        <style type="text/css">
        .input {
            width: 600px;
            height: 100px;
        }
        </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#send").click(function(){
                 $.post("http://localhost:8080/Web/", $("#text").val(), function(result, status){
                    $( "#content" ).html(result);
                 });
            });
        });
    </script>
    </head>
<body>
    <div id="content">
        <textarea class="input" id="text" placeholder="Write text to send to server" textarea rows="4" cols="50"></textarea>
        <p>
        <button id ="send">Send request</button>
    </div>
</body>
</html>

This does not change the content of the page to the response from the server (which I've tested works). Putting in an alert except of changing the content of the page also doesn't work. I've read up a bit on AJAX JQuery, but didn't seem to manage to get it right.

Thank you

Upvotes: 0

Views: 656

Answers (1)

tolotra
tolotra

Reputation: 3270

You can read the API Docs

The AJAX post method must have key valued object, e.g:

{ text : $("#text").val() }

or Form Data object in the second parameter.

I hope this helped.

Upvotes: 1

Related Questions