• I am new to wordpress development and am attempting to understand using AJAX. My understanding is that I can use AJAX to send variable information on the client side (form input fields, etc.) to the server side where they can be extracted via $_POST and used in server side functions. Hopefully that ‘big picture’ is correct.
    I’ve created a simple plugin to learn how to accomplish this. The plugin creates a simple form with one checkbox and one input field. I want to take the value of the input field, send it to the server via AJAX and then manipulate it via php on the server and echo the result back to the client.

    I believe I need to add something similar to the following in the JS file to send the input field value to the server, but I am really not sure what some of the parameters are supposed to be.

    	
    var $jq = jQuery.noConflict();
    var g_name = document.getElementById("ajax_guest_name").value; // so far so good!
    $jq.ajax({
    	url : ajax_test.ajax_url, // I'm not sure what exactly belongs here
    	type : 'post',
    	data : {
    		ajax_guest_name : 'g_name', // I believe this fills the ajax data array with the input field value
    	},
    	success : function() {
    		alert("AJAX Success???");  // I'm not sure what exactly belongs here
    	}
    }); // End of AJAX function
    

    Then I believe I need to add something similar to the following in the plugin php file, but am very unclear as to what is required:

    add_action( 'wp_ajax_my_ajax_test', 'my_ajax_callback' );
    
    function my_ajax_callback() {
    	if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { 
    
    	die();
    	}
    	else {
    
    	exit();
    	}
    }
    

    Any help would be appreciated.
    Thanks

Viewing 8 replies - 1 through 8 (of 8 total)
  • Hi @gshell,

    Hope you are doing well.

    Two quick clarifications:
    – When using ajax in WordPress, you always need to send an ‘action’ parameter so that WordPress knows which callback to invoke to handle the request.
    In the code add_action( 'wp_ajax_my_ajax_test', 'my_ajax_callback' ); the action name would be ‘my_ajax_test’.
    So in JS side you need to add 'action': 'my_ajax_test' to the data object.

    success is one of many arguments for the ajax call. There you define the handler/callback for when the server responds successfully. It always receives a response argument containing the repsonse data.

    That said, I recommend to go to the official docs for a comprehensive list of parameters https://api.jquery.com/jquery.ajax/

    And also check some simple example to play with https://wptheming.com/2013/07/simple-ajax-example/

    Hope this helps. Take care!

    Thread Starter gshell

    (@gshell)

    Hi @sjaure,
    Thank you. That helped very much. Particularly the simple example.

    I’ve modified the JS file as follows:

    var $jq = jQuery.noConflict();
    var g_name = document.getElementById("ajax_guest_name").value;
    $jq.ajax({
    	url : ajax_test.ajax_url,
    	type : 'post',
    	data : {
    		'action': 'my-ajax-test',
    		'ajax_guest_name' : g_name
    	},
    	success:function(data) {
    		// This outputs the result of the ajax request
    		console.log(data);
    	},
    	error: function(errorThrown){
    		console.log(errorThrown);
    	}
    }); // End of AJAX function
    

    A couple of questions:
    1 – What does the URL name ajax_test.ajax_url mean? Reading the documentation states that wordpress ‘gives us a unified file to use – wp-admin/admin-ajax.php’ which is included in the localize script command.
    2 – I believe I have the type and the data array correct now
    3 – what is the ‘console.log’ and how do I view/display it?

    The my-ajax-test.php file has the following immediately below the HTML form creation.

    <?php
    add_action( 'wp_ajax_my-ajax-test', 'my_ajax_callback' );
    
    function my_ajax_callback() {
    	$guest_name = $_POST[ajax_guest_name];
    	echo $guest_name;
    	die();
    }
    

    Note in the add_action line, I used dashes instead of underlines as I did in the my-ajax-test.php file. I’m not sure if they were supposed to match or not.

    No errors when clicking the Register button, but no results echoed either.

    Pleased to help ??

    1- An AJAX call is basically an asynchronous request from JS to an URL. In this case, the target URL is your WordPress site. That line is telling AJAX what is the URL to use. And WP built in AJAX url is always https://your-site-url/wp-admin/admin-ajax.php
    If you are curious, you can take a look at that file and you will see that it parses the ‘action’ parameter and based on it will call the corresponding registered handler.
    Now, you could hardcode that URL like this:
    url : 'https://your-site-url/wp-admin/admin-ajax.php',
    but that would work only for that specific site.
    So, the right way to do it is to dinamically define this URL as a JS variable that lives in the global scope.
    In your example, it is asumed that you have something like this in your PHP code when you enqueue your script:

    wp_localize_script( 'my-script-handler', 'ajax_test', array(
    		'ajax_url' => admin_url( 'admin-ajax.php' )
    	));

    This is defining an object called ‘ajax_test’ that contains the property ‘ajax_url’.

    2- It looks correct, yes.

    3- conole.log is a JS method to output data in the browser or JS interpreter console. Every browser has its own way to open the console. Here you have how to use the console in chrome https://developers.google.com/web/tools/chrome-devtools/console/
    Along with the console, you have many other ‘dev tools’ available in the browser. One that is very useful when debugging AJAX, is the ‘Network’ panel. there you can see the request dispatched by JS and the responses. You also have a JS debuger. If you are familiar with debugging, there you can put a breakpoint in JS code and check what’s going on. That should help you to spot the missing details to get this working.

    Let me know if you need furhter assistance.

    Have a great day!

    Thread Starter gshell

    (@gshell)

    @sjaure,
    Thank you for the great response. It has been very helpful. It is difficult for me to diagnose something like the ajax exchange as I can’t tell whether the problem is with the ajax data being sent to the server or the response coming back. Your response has helped me out in that regard. Thank you very much.

    By looking https://your-site-url/wp-admin/admin-ajax.php I was able to see that nothing changed when the submit button was clicked, even though I included a jquery alert in the JS file that let me know that it had been clicked. I am now reviewing information console.log to see if I can determine why. (Network panel F12 key on Edge Browser). I will let you know what I learn. Thanks for the help.

    Glad to hear it.
    Keep me posted ??

    Thread Starter gshell

    (@gshell)

    @sjaure
    From the console I see the following immediately after loading the page with my input form:

    HTML1300: Navigation occurred.
    _test2 (1,1)
     JQMIGRATE: Migrate is installed, version 1.4.1
     TEC Debug: Tribe Events JS init, Init Timer started from tribe-events.js.
    
     User agent reported as: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134
    
     Live ajax returned its state as: "false

    I suspect the last line is an issue.
    Further down I have the following error message:

     HTTP400: BAD REQUEST - The request could not be processed by the server due to invalid syntax.
    (XHR)POST - https://localhost:81/wordpress/wp-admin/admin-ajax.php

    I can successfully display localhost:81/wordpress/wp-admin/admin-ajax.php in a browser page. It contains a single digit ‘0’. The php code exists in the htdocs/wp-admin folder. The last line of which is:
    wp_die( ‘0’ );
    Clearly where the 0 comes from.

    I believe I have properly enqueued the script file with the following in the main plugin php file:

    add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
    function ajax_test_enqueue_scripts() {
    	wp_enqueue_script( 'my-script-handler', plugins_url( '/my-ajax-test.js', __FILE__ ), array('jquery'), '1.0', true );
    
    	wp_localize_script( 'my-script-handler', 'ajax_test', array(
    		'ajax_url' => admin_url( 'admin-ajax.php' )
    	));
    }
    

    The ajax code in the JS file looks like this:

    $jq.ajax({
    	url : ajax_test.ajax_url,
    	type : 'post',
    	data : {
    		'action': 'my-ajax-test',
    		'ajax_guest_name' : g_name
    	},
    	success:function(data) {
    		// This outputs the result of the ajax request
    		console.log(data);
    	},
    	error: function(errorThrown){
    		console.log(errorThrown);
    	}
    }); // End of AJAX function
    

    Any suggestions as to where I should go from here?
    Thanks

    Hi @gshell,

    Hard to say what is wrong.

    Please make sure g_name has a valid value.

    Also, change this:

    data : {
     'action': 'my-ajax-test',
     'ajax_guest_name' : g_name
    },

    into this:

    data : {
     action: 'my-ajax-test',
     ajax_guest_name : g_name
    },

    In the browser dev tools, under the tab ‘Network’ you should be able to sniff the ajax request. There you can see if the parameters are being sent correctly.

    BTW, if you visit localhost:81/wordpress/wp-admin/admin-ajax.php in your browser you will allways get a ‘0’ because you are not sending the ‘action’ parameter, therfore wordpress doesn’t find a handler for the request and returns 0 by default.
    Try localhost:81/wordpress/wp-admin/admin-ajax.php?action=my-ajax-test and it should hit your handler.

    Cheers!

    Thread Starter gshell

    (@gshell)

    Hi sjaure,
    I haven’t had much time to work on this as I have been traveling. I have changed the names of a lot of the functions and variables so that I have a better handle on what value is changing when I make a change. I have patterned the revised code after the simple example you suggested at https://wptheming.com/2013/07/simple-ajax-example/. The previous syntax error is resolved, but I now have a new error that I can not resolve.

    One error I had was that the callback function was buried inside the main php function. I have separated them to resolve. The my-ajax-test.php file now looks like:

    add_action( 'wp_enqueue_scripts', 'ajax_test_enqueue_scripts' );
    function ajax_test_enqueue_scripts() {
    	wp_enqueue_script( 'my-script-handler', plugins_url( '/my-ajax-test.js', __FILE__ ), array('jquery'), '1.0', true );
    	wp_localize_script( 'my-script-handler', 'ajax_test', array(
    		'ajax_url' => admin_url( 'admin-ajax.php' )
    	));
    }
    function my_ajax_test() {
    
    	echo "<p>Hello World!</p>";
    	
    /****************************
    * Create Input Form
    ****************************/
    ?>
    	<form action="">
    	<input type="text" id="ajax_fruit">
    	<p>Enter Fruit Name</p>
    	<br><br>
    	<input type="button" id="ajax_submit" value="Enter">
    	</form> 
    <?php	
    
    };
    add_action( 'wp_ajax_my_ajax_callback', 'my_ajax_callback' );
    
    function my_ajax_callback() {
    	$fruit = $_POST[fruit];
    	
    	if ( isset($_POST) ) {
    	echo "<p> $_POST SET! </p>";
    	echo "<p> Submitted Fruit is {$fruit} </p>";
    
    	// Let's take the data that was sent and do something with it
    	if ( $fruit == 'Banana' ) {
    		$fruit = 'Orange';
    	}
    	echo $fruit;	
    	} else {
    	echo "<p> $_POST NOT SET! </p>";
    	};
    	
    	die();
    };
    
    add_shortcode('My-AJAX-Test', 'my_ajax_test');

    The JS file is below. Note the comments at the various alert stages that work and the error shown in the Console at the AJAX call (‘fruit’ is not defined). I am not sure which fruit is being referred to, but hard coding it to fruit : ‘Banana’ makes that error go away, but obviously the data is no longer coming from the input field.
    When hardcoded as ‘Banana’, Console has no errors and data properly displays echo’s from my_ajax_callback (<p> Array SET! </p><p> Submitted Fruit is Banana </p>Orange).

    var $jq = jQuery.noConflict();
    $jq(document).ready(function(){	
    /* Send guest name to server via AJAX */
    
    	$jq("#ajax_submit").click(function(){
    	alert("Submit Button was clicked");
    	
    /* Send guest name to server via AJAX */
    
    	var fruit = document.getElementById("ajax_fruit").value;
    	alert("Submitted Fruit is " + fruit); // alert is correct to this point
    
    });
    
    $jq.ajax({                 // error in console:  SCRIPT5009: SCRIPT5009: 'fruit' is not defined
    	url : ajax_test.ajax_url,
    	type : 'post',
    	data : {
    		action: 'my_ajax_callback',
    		fruit : fruit
    	},
    	success:function(data) {
    		// This outputs the result of the ajax request
    		console.log(data);
    	},
    	error: function(errorThrown){
    		console.log(errorThrown);
    	}
    }); // End of AJAX function
    
    }); // End of Main Document Ready Function
    

    I’m not entirely sure how to grab the information from the callback function and use it in the my_ajax_test function yet, but would like to just deal with one error at a time.

    Thank you so much for all of your help and your patience is dealing with a complete novice.

Viewing 8 replies - 1 through 8 (of 8 total)
  • The topic ‘Assistance Learning AJAX’ is closed to new replies.