-2

I am looking for a basic jQuery function to submit a form without refreshing the page. I had this once but I can't find it, all I can find is the long boring and complicated ones you have to update to add an input field into the form.

From what i remember the code includes the URL of the process file, the form id and the #results id.

Kyslik
  • 8,217
  • 5
  • 54
  • 87

2 Answers2

1

you can use Ajax form submit as follow;

<form id="formId" action="url" method="post">

</form>

 <script type="text/javascript">
    var form = $('#formId');
    form .submit(function () {
    $.ajax({
        type: "POST",
        url: "url",// url which you want to post
        data: formData,
        success: function (data) {
            alert('success');
        },
        error: function(jqXHR, textStatus, errorMessage) {
            alert(errorMessage); // Optional
        }
    });
});
</script>
Madura Harshana
  • 1,299
  • 8
  • 25
  • 40
1
    <?php
        $message = '';
        if( isset( $_GET['name'] ) ) {
            if( empty( $_GET['name'] ) ) $message = 'Name is required';
            else $message = 'Form submitted successfully.';
        }
    ?>
    <form id="ajax-form">
        <input name="name" type="text">
        <input type="submit">
        <div id="message"> <?php echo $message; ?> </div>
    </form>

    <script>
        $( '#ajax-form' ).submit( function( e ) {
            e.preventDefault();
            var query = $(this).serialize();
            $(this).find('#message').load( window.location.href + '?' + query + ' #ajax-form #message' );
        });
    </script>
Prakash GPz
  • 1,675
  • 4
  • 16
  • 27