简体   繁体   中英

form validaiton on form submit without page reload

I have very simple html form created with one button in it.

<form method="post" id="my_unique_form_id">
      <button type="submit" name="'.$name.'" value="'.get_the_ID().'" class="'.$class.'"></button>
</form>

Then I connected it with AJAX

jQuery(document).ready(function() {
    jQuery('#my_unique_form_id').on('submit', function(event) {
        event.preventDefault();
        jQuery.ajax({
            type: "post",
            url: "",
            data: jQuery('#my_unique_form_id').serialize(),
            success: function() {
                console.log('not reloading the page');
            }
        })
    });
});

So the code above works in a way, that on form submit page does not realod, which is great, but of course I don't get any results I need and nothing is happening.

If I don't use AJAX, everything works perfectly and I get the expected results, but then page is reloading, which I need to avoid. I don't really know how to combine it.

This is php function I am using:

  1. I stored name in a variable (coming from button)

     $name = my_function()? 'remove': 'add';
  2. my_function setup

     function my_function( $post_id = 0, $user_id = 0 ){ if (; $post_id ) { $post_id = get_the_ID(); } if (; $user_id ) { $user_id = get_current_user_id(), } $meta_value = get_data( $user_id ); return array_search( $post_id, $meta_value ) !== false; }

What you need to do is in your jQuery code, pass the data retrieved from the call to the success function like so:

success: function(data){
    //Do something
}

That data variable will then contain whatever PHP has echo'd. If you want to access that data in some meaningful way, it will be easiest if you prepare it as an array in PHP ie like so:

$dataForjQuery = array('status' => 'OK', 'message' => 'validation passed');
echo(json_encode($dataForjQuery));

this way in jQuery you would do:

success: function(data){
    console.log('the status is: ' + data.status); //Will log 'the status is: OK'
    console.log('message from server: ' + data.message); //Will log 'message from server: validation passed'
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM