Forms with ajax, trigger ajax on form submit.
-
I want to make filter with checkboxes in WordPress. What I firstly want to achieve is to test it and send variable with ajax on checkbox click in the form.
Here is the form with check boxes:
<div id="test-btn" data-id="test">test</div> <form method="post" id="filter"> <input type="checkbox" name="f" value="1" onchange="this.form.submit()" <?php if ($face =='1') {echo 'checked';}?> <input type="checkbox" name="t" value="1" onchange="this.form.submit()" <?php if ($twitter=='1') {echo 'checked';}?> <input type="hidden" value="myfilter"> </form>
Here is the javascript:
jQuery(document).ready( function(){ jQuery('#content').on('submit', '#filter', function(e) { e.preventDefault(); var test = jQuery('#test-btn').data( 'id' ); jQuery.ajax({ url : rml_obj.ajax_url, type : 'post', data : { action : 'test_function', security : rml_obj.check_nonce, test_data : test }, success : function( response ) { alert (test); jQuery('#result').html(response); } }); }); });
Here is the function in functions.php:
function test_function() { check_ajax_referer( 'rml-nonce', 'security' ); $test_data = $_POST['test_data']; echo $test_data; die(); } add_action('wp_ajax_test_function', 'test_function'); add_action('wp_ajax_nopriv_test_function', 'test_function');
For now I’m just trying to test it. So when user clicks on checkbox in form that ajax is called. But I’m stuck. If I add this line to form action
action="<?php echo site_url() ?>/wp-admin/admin-ajax.php"
, then on submit I’m stuck on ajax url: admin-ajax.php. If I remove action line from form then page simple reloads.When I’m using click on element, instead of form submit I’m succeeding. But I need to make it work on form submit so I can implement filtering by clicking on various checkboxes.
If anybody can tell me what I’m doing wrong, I will build on this and actually send checkbox values from the form and execute query in function for filtering the data.
The page I need help with: [log in to see the link]
- The topic ‘Forms with ajax, trigger ajax on form submit.’ is closed to new replies.