Submit the form using jQuery and add it to the page

Hey!
I have this code for the form:


<form class="myform" name="myform" method="POST" action="post.php">
<textarea id="mytextarea" name="mytextarea"></textarea>
<button>Share</button>
</form>

I also have this code for the page:

<Preview> <Code> <div class = "content"> <div class = "message"> This message </div> <div class = "info"> Posted on 10/10/10 </div> </DIV> <div class = "content"> <div class = "message"> This is another message </div> <div class = "info"> Posted on 10/9/10 </div> </DIV> Code>

Can I submit a form using jQuery instead of reloading the whole page? Can I get a form response and put the answer at the top of the first <div class="content">?
Note. I have several forms with the same class.
Many thanks!

+3
source share
3 answers

Yes, submitting forms using jQuery is pretty simple.

There is a simple function for sending data using AJAX and is easily attached to the values โ€‹โ€‹of the form:

$.post(url, $('#myform').serialize(), function(data) { 
    $('#content').prepend(data);
})

$.post- an easy way. If you need to check for errors and something else, you should check $ .ajax (http://api.jquery.com/jQuery.ajax).

+1
source

jQuery, , : http://api.jquery.com/submit/

, :

$('[name=mytextarea]').val()`
0

, , , , AJAX:

$('.myform').submit(function(e){
    var data = $(this).serialize();
    e.preventDefault();

    $.ajax({
        url: this.action,
        type: 'POST',
        success: function(data) {
            $('#content').prepend(data);
        },
        error: function() {
            alert('oops, something went wrong');
        }
    );
});
0

Source: https://habr.com/ru/post/1772334/


All Articles