JQuery and AJAX post to php without reloading page in WordPress

I’m developing a plugin in WordPress and am having difficulty trying to post data to a separate PHP file using Ajax without reloading the page. On the backend, the PHP file is relying on if( isset() ) to execute an SQL query. On the client side, the user should see individual records fadeOut and a message that records were successfully deleted.

UPDATE: The javascript is working so far, once the form button is clicked, the correct div-s fade in and fade out. However, the PHP file is not getting any value posted to it, as tested with a var_dump.

Read More

HTML Code:

<!-- problem: when setting "action" to a url, that page is automatically loaded. I want to stay on the existing page. -->
        <form action='' id='form-delete-assoc' method='post'>
    <input name='remove_all' type='submit' id='remove-all' value='Remove All'></input>
    </form>

JQUERY: (updated with some fixes suggested by answerers)

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        $('tr.assoc_row').show();
        $('#settings-removed-msg').hide();
        $('#new-assoc-msg').hide();
        $('#formdeleteassoc').submit(function(e){
            e.preventDefault();

            $.ajax ({
                type: 'POST',
                url: '<?php echo $cb_t2c_remove_all_url; ?>',
                data: {removeall: 'yes'
                },
                success: function() {
                    $('#settings-removed-msg').fadeIn('fast');
                    $('tr.assoc_row').fadeOut('fast');
                    }
            });
        });

        $('#formsavesettings').submit(function(){
            $('#new-assoc-msg').fadeIn('fast');
            });
    });
</script>

remove_all.php:

<?php
//remove_all.php

global $wpdb;
$prefix = $wpdb->prefix;

$remove_var_dump = $_POST['removeall']; //returning NULL
var_dump($remove_var_dump);

if ( isset( $_POST['removeall'] ) ){
    $wpdb->query("DELETE FROM ".$prefix."cb_tags2cats");
    }

?>

Related posts

Leave a Reply

3 comments

  1. Like the others said, you need to either return false or use preventDefault(). You should also move your calls to fadeOut and fadeIn into the success callback. If you don’t and the request is unsuccessful for some reason, the user may be misled into thinking it was successful.

    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    
    <script type="text/javascript"> 
        $(document).ready(function(){
            $('tr.assoc_row').show();
            $('#settings-removed-msg').hide();
    
            $('#form-delete-assoc').submit(function(e){
    
                // prevent the form from submitting normally
                e.preventDefault();
    
                $.ajax ({
                    type: 'POST',
                    url: '/delete-assoc.php', // Relative paths work fine
                    data: { removeall: 'delete-all' },
                    success: function(){
                      $('tr.assoc_row').fadeOut('slow');
                      $('#settings-removed-msg').fadeIn('slow');
                    }
                });
    
            });
        });
    </script>
    
  2. Your form submit event needs to return false, to stop the form from actually submitting.

     $('#form-delete-assoc').submit(function(){
       ... rest of your code here...
    
       return false;
     }
    
  3. to post data to a separate php page without reloading current (parent or top) page, create a hidden iFrame and use it as the submit target. this type of solution allows posting and retrieving json responses. this snippet uploads a file to a php page.

    <script type="text/javascript">
    function init() {
        document.getElementById('file_upload_form').onsubmit=function() {
            document.getElementById('file_upload_form').target = 'upload_target'; //'upload_target' is the name of the iframe
        }
    }
    window.onload=init;
    </script>
    </head><body>
    <form id="file_upload_form" method="post" enctype="multipart/form-data" action="upload.php">
    <input name="file" id="file" size="27" type="file" /><br />
    <input type="submit" name="action" value="Upload" /><br />
    <iframe id="upload_target" name="upload_target" src="" style="width:0;height:0;border:0px solid #fff;"></iframe>
    </form>
    

    this tutorial explains the process step by step ->
    http://www.openjs.com/articles/ajax/ajax_file_upload/

    follow up on how to parse the response ->
    http://www.openjs.com/articles/ajax/ajax_file_upload/response_data.php