arash rahimi arash rahimi - 3 months ago 13
PHP Question

How to send form data and display them dynamically with ajax in the same page

I have a form that have a text area field I already store my data in the tables but now I want to show the results in same page with ajax dynamicly its mean that I want to refresh page without reloading



<form action='' method='post''>

<div class="form-group">
<label for="comment"></label>
<textarea class="form-control" rows="5" id="comment" name='message_content' required></textarea>
</div>


<button type='submit' class='btn btn-default' name='send_msg'>
send</button>
</form>




Answer

I am not a strong advocate on using javascript framework, however, ajax is a pain to handle without it, so here is an example using JQuery, but it's possible to do more or less the same thing with any other framework.

The first step is to intercept the submit event, then get the form data, perform an ajax query and display results in a div.

<!DOCTYPE doctype html>
<html>
    <head>
    </head>
    <script src="jquery-3.1.0.min.js">
    </script>
    <script>
        jQuery( document ).ready(function() {
            jQuery('#myForm').submit(function(e){
                e.preventDefault();

                jQuery.ajax({
                    url: e.currentTarget.action,
                    data:{
                        comment: jQuery('#comment').val()
                    }
                }).done(function(data){
                    console.log(data);
                    jQuery('#display-data').append(data);
                });
            });
        });
    </script>
    <body>
        <form id="myForm" action="getData.php" method="post">
            <div class="form-group">
                <label for="comment">
                </label>
                <textarea class="form-control" id="comment" name="message_content" required="" rows="5">
                </textarea>
            </div>
            <button class="btn btn-default" name="send_msg" type="submit">
                send
            </button>
        </form>
        <div id="display-data"></div>
    </body>
</html>

EDIT: From your comment, I gathered you wanted to reload page after submission, you can do it after at the end of your ajax query :

jQuery('#myForm').submit(function(e){
    e.preventDefault();

    jQuery.ajax({
        url: e.currentTarget.action,
        data:{
            comment: jQuery('#comment').val()
        }
    }).done(function(data){
        document.location.reload();
    });
});
Comments