How to submit data using AJAX and POST Method

How can I post the following form using Ajax. When submitting the form that page refreshes and I want to avoid that.

<form method="post" action="" > 
    <div class="rp-donation-block checkout_donation" >
        <p class="message"><strong><?php echo $this->get_setting('message'); ?></strong></p>
        <div class="input text">
            <input type="text" value="<?php echo $amount; ?>" class="input-text text-donation" name="donation-amount">
            <input type="submit" value="<?php echo $this->get_setting('btn_lable'); ?>" class="button" name="donate-btn">
        </div>
    </div>
</form>

I tried both of these with no luck.

<form method="post" action="" onSubmit="return false">
<form method="post" action="" action= "<?php echo $_SERVER['PHP_SELF']; ?>">

Related posts

3 comments

  1. I suppose your form element has id of form as <form id="form"...

    <script>
    // Attach a submit handler to the form
    $( "#form" ).submit(function( event ) {
    
    // Stop form from submitting normally
    event.preventDefault();
    
    // Get some values from elements on the page:
    var $form = $( this ),
    donate_amount = $form.find( "input[name='donation-amount']" ).val(),
    url = $form.attr( "action" );
    
    // Send the data using post
    var posting = $.post( url, { amount: donate_amount } );
    
    // Put the results in message div
      posting.done(function( data ) {
        var message_returned = $( data ).find( "#message" ); //hope your are returning message, also you can return other things like message type and create message on frontend as accordingly
        $( ".message" ).empty().append( message_returned ); //adding returned message to your message div
      });
    });
    </script>
    
  2. A form is not mandatory to post using Ajax. You can write an Ajax request using just a button click as well.

    $(function () {
        $('#buttonId').on('click', function (e) {
            $.ajax({
                type: "POST",
                cache: false,
                url: <url_name>, //some php file where you may hit the database and want to modify content
                data:{'post1': <post1value>,'post2': <post2value>},
                datatype: "JSON", // can be html or text as well
                success: function (data) {
                    var actualData = $.parseJSON(data); // if in case of JSON
                }
            });
        });
    });
    

    If you want to invoke only on form submission you can write your Ajax like so.

    $('#formId').on('submit', function (e) {
    });
    

    On the other side use :

    $post_1 = $_POST['post1'];
    

    To Get post1 value.

  3. The button you are using to trigger the event that causes the submit of the form via ajax post should not be of type submit! Else this will always fail.

Comments are closed.