Ajax call not working for my custom plugin
-
I need help in getting ajax to work in my custom wordpress plugins
These are the steps i followed
step one
// STEP ONE: // I added the jquery script and localized it in my plugin base file function add_js() { wp_enqueue_script( 'front_script', plugins_url('assets/js/frontend.js', __FILE__), array( 'jquery' ) ); wp_enqueue_script( 'test_script', plugins_url('assets/js/test.js', __FILE__), array( 'jquery' ) ); wp_localize_script( 'test_script', 'myobject', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))); wp_enqueue_script('test_script'); } add_action( 'wp_enqueue_scripts', 'add_js' ); // STEP TWO: // I created a php validation form - test.php add_action( 'wp_ajax_validatetest', 'validatetest' ); add_action( 'wp_ajax_nopriv_validatetest', 'validatetest' ); function validatetest(){ if(isset($_POST['submit_testpost'])){ $value = !empty($_POST['testpost']) ? $_POST['testpost'] : ''; if(empty($value)){ $reply = array('paul' => 'test-error', 'message' => 'can not be empty'); print_r(json_encode($reply, true)); } elseif($value != 'money'){ $reply = array('paul' => 'test-error', 'message' => 'Make more money'); print_r(json_encode($reply)); } else{ $reply = array('paul' => 'test-success', 'message' => 'Your money has been paid into your account'); print_r(json_encode($reply, true)); } } } // STEP THREE // I ADDED THE HTML IN test.php function formy(){ $value = !empty($_POST['testpost']) ? $_POST['testpost'] : ''; $milk = '<div class="testdiv"><form action="" method="post"> <input type="text" name="testpost" value="'.$value.'"> <input type="submit" name="submit_testpost" value="Submit" class="submit_testpost"></form></div> '; echo $milk; } // STEP FOUR // I ADDED THE JQUERY SCRIPT - in assets/js/test.js jQuery(document).ready(function($) { $(document).ready(function() { $('.submit_testpost').on("click", function(){ var data = { 'action': 'validatetest' }; jQuery.post(myobject.ajaxurl, data, function(response) { var data = jQuery.parseJSON(response); if(data.paul == 'test-success'){ alert(data.paul); }else{ alert('wait guy'); } }); }); e.preventDefault(); }); });
But for some unknown reason it seems not to be working, the alert or both success or error is not showing, as if the call was not made
What am i doing wrong, and secondly the page reloads once the submit button is clicked but i want to stop the page from reloading
I only want it to exit on success but echo error message on failure but not reload page, which was what i thought preventDefault does.
Viewing 13 replies - 1 through 13 (of 13 total)
Viewing 13 replies - 1 through 13 (of 13 total)
- The topic ‘Ajax call not working for my custom plugin’ is closed to new replies.