Asked 7 years ago
22 May 2017
Views 1227
sachin

sachin posted

how to use ajax in Wordpress ?



 function print_state(){
 
 var e = document.getElementById("country");
var strUser = e.options[e.selectedIndex].value;

var data="searchby=" + strUser+"&action=getState";

 jQuery.ajax({
 url:url,
 type: "POST",
 dataType:'html',
 data: data,
 success: function(data)
 {

  jQuery('#state').html(data);

 }
 });
}


above is simple code for getting list of the state from the country .
used jQuery for ajax but how to implement with wordpress ? how to make server side file which respond to ajax request . and how to embed ajax javascript to Wordpress front page ?

jassy

jassy
answered Apr 24 '23 00:00

WordPress provides the ability to use AJAX (Asynchronous JavaScript and XML) to make requests to the server without reloading the entire page. You can follow these steps to use AJAX in WordPress:

1.Add the necessary scripts and dependencies:
To add the necessary scripts and dependencies, you can use th e wp_enqueue_script() function. For example, to add jQuery and a custom script for AJAX requests, you can add the following code to your functions.php file:



function add_scripts() {
  wp_enqueue_script('jquery');

  wp_enqueue_script('custom-ajax', get_template_directory_uri() . '/js/custom-ajax.js', array('jquery'), '1.0', true);

  wp_localize_script('custom-ajax', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}

add_action('wp_enqueue_scripts', 'add_scripts');

This code adds jQuery as a dependency, as well as a custom script for AJAX requests. The wp_localize_script() function is used to pass the AJAX URL to the script.

2.Add a PHP function to handle the AJAX request:
To handle the AJAX request, you can create a PHP function that will perform the necessary actions. You can use the wp_ajax_{action} and wp_ajax_nopriv_{action } hooks to register the function with WordPress. Here's an example:



function my_ajax_function() {
  // Do something with the AJAX request
  $result = array('success' => true, 'message' => 'AJAX request successful.');

  // Send the result back to the browser
  wp_send_json($result);

  // Don't forget to exit
  exit;
}

add_action('wp_ajax_my_ajax_function', 'my_ajax_function');
add_action('wp_ajax_nopriv_my_ajax_function', 'my_ajax_function');

This code defines a PHP function called my_ajax_function to handle the AJAX request. The function performs the necessary actions (such as retrieving data from the database), creates a result array, and sends the result back to the browser using the wp_send_json() function. Note that we use two hooks (wp_ajax_{action} and wp_ajax_nopriv_{action}) to handle logged-in and logged-out users.

3.Add an AJAX request in the custom script:
Finally, you can add an AJAX request in the custom script to make the request to the server. Here's an example:



jQuery(document).ready(function($) {
  $('#my-button').click(function() {
    $.ajax({
      url: ajax_object.ajax_url,
      type: 'POST',
      data: {
        action: 'my_ajax_function'
      },
      success: function(result) {
        console.log(result);
      },
      error: function(error) {
        console.log(error);
      }
    });
  });
});

This code binds a click event to a button with the ID my-button. When the button is clicked, it makes an AJAX request to the server using the $.ajax() function. The action parameter is set to the name of the PHP function that will handle the request. The success and error callbacks are used to handle the server response.

By following these steps, you can use AJAX in WordPress to create dynamic and interactive websites.
Post Answer