• 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)
  • In the enqueuing of the scripts, you have the ‘test_script’ twice.
    Do both scripts depend on jquery? Does one script depend on the other one?

    You should look into using the WP functions for sending AJAX responses. https://developer.wordpress.org/?s=send_json
    You also should have a nonce field and check the user’s capabilities.
    https://developer.wordpress.org/reference/functions/wp_nonce_field/
    https://developer.wordpress.org/reference/functions/current_user_can/

    Your test.js has a ready handler inside a ready handler, then defines the submit handler inside there. The preventDefault is in the ready handler instead of the submit handler, and it refers to e which is not defined. The e should be a parameter to the handler function.
    You also define var data in the submit handler, and again in the post response handler.

    Thread Starter pandglobal

    (@pandglobal)

    In the enqueuing of the scripts, you have the ‘test_script’ twice.

    I was thinking that by having test_script for the test.js and localizing it by test.js and enqueue both script at once.

    or should i have given different handler for test.js, and then use something like this local_test_script for the wp_localize_script(‘local_test_script’,…..?

    Thread Starter pandglobal

    (@pandglobal)

    @joyously

    is it okay to use

    jQuery(document).ready(function($) {
    $(document).ready(function(){
    or use only

    jQuery(document).ready(function($) {

    ????

    Thread Starter pandglobal

    (@pandglobal)

    @joyously

    if i use
    if ( ! current_user_can( ‘manage_options’ ) ) {

    // what will i actually do here, should i enqueue based on user capability, but i want the ajax call available for both logged and not logged in users. why must i check their capability?
    }

    I was thinking that by having test_script for the test.js and localizing it by test.js and enqueue both script at once.

    No, enqueue is separate from localize. You can only localize a script that is already enqueued. You don’t have to enqueue it again afterward.

    You only need one handler for the ready state. But I don’t know that the parameter passed to the ready handler is jQuery.

    WP supports capabilities, and so should the plugin. Even if all you are checking is read capability, it should still be checked, or your plugin doesn’t really support all of WP and what other plugins add to it.
    You didn’t say what your plugin will be doing, but if the user can make changes to data, you must check the capability first. And if you use what the visitor types into the form, you better be sanitizing it before using it or the site will be hacked.

    Thread Starter pandglobal

    (@pandglobal)

    @joyously

    checking capabilities is not needed since the plugin is just for contact form, which is mostly at the frontend for every visitor of the site whether logged in or not.

    Thread Starter pandglobal

    (@pandglobal)

    I really need help in step one and step four, if you can help with better code approach to enqueue and use wp ajax in my plugin, and the a step four that will make a call to the ajax any time a page loads so that i can know if ajax is actually working, before i can then add conditions to it

    checking capabilities is not needed since the plugin is just for contact form

    What is the AJAX needed for then? You can use JS to check for required fields, before submission.

    Thread Starter pandglobal

    (@pandglobal)

    What is the AJAX needed for then

    ajax is needed to do the following.

    1. send the otp code to a server for confirmation and once confirmed it returns true.

    2. then once is true, the main form will be submitted using $(‘#submit_button’).submit()

    so the form am building is an otp modal widow in jquery and is good enough the message values and validation runs in ajax with out reloading the page.

    Is bigger than normal required field js validation, it has to run a php file to get values and then know Whetter to submit the main form or not.

    Thread Starter pandglobal

    (@pandglobal)

    i found my problems, so i tested

    var data = JSON.parse(‘{ “paul”: “my message content” }’);
    alert(data.paul);

    and it worked, but thats just a manually inputted text in the js file.

    So i want to ask if ajaxurl or adminajax in wordpress returns Json or Object?

    and if it returns object how should i declare a variable with it

    The ajaxurl is simply your endpoint to execute your PHP code. What is returned is whatever your code returns. That’s why I said

    You should look into using the WP functions for sending AJAX responses. https://developer.wordpress.org/?s=send_json

    Thread Starter pandglobal

    (@pandglobal)

    The ajaxurl is simply your endpoint to execute your PHP code. What is returned is whatever your code returns. That’s why I said

    I have tested wp_send_json() and is not working, am using the latest version of wordpress and have only woocommerce and contact form 7 installed.

    Is not working, it outputs errors in the console

    
    $response = array('type' => 'match', 'message' => 'my test error message here');
    
    wp_send_json($response)
    

    yet is not working

    You will have to figure out the errors yourself, if you don’t show what you get here.

Viewing 13 replies - 1 through 13 (of 13 total)
  • The topic ‘Ajax call not working for my custom plugin’ is closed to new replies.