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
.
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");
}
?>
Like the others said, you need to either
return false
or usepreventDefault()
. You should also move your calls tofadeOut
andfadeIn
into thesuccess
callback. If you don’t and the request is unsuccessful for some reason, the user may be misled into thinking it was successful.Your form submit event needs to return false, to stop the form from actually submitting.
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.
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