How to use ajax in WordPress?

/
/
/
578 Views

In this article, you will learn how to use Ajax in WordPress.

Ajax has rapidly become a well-liked web technology, you’ll find it used on most websites. The key feature of Ajax is it can manage database operations without reloading the page. 

This suggests you’ll fetch data from the database and display it on the front-end without having to refresh the page.

how to use ajax in wordpress
how to use ajax in wordpress

If you are not using a JavaScript framework or library like Angular, React, or Vue then you will need Ajax to implement real-time functionality.

Using Ajax in WordPress is quite different from using it in Php or any other framework. Generally, we create a URL or route to perform Ajax but in WordPress it is different.

You need to create an action than using the admin-ajax.php you can call that action. You can create the action like the below code.

<?php

//ajax function 
function my_ajax_request_function() 
{
  //your stuff will goes here
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    echo json_encode(array('success' => true));
    exit();
}
add_action( 'wp_ajax_my_action_name', 'my_ajax_request_function' );     //for admin
// If called from admin panel
add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_request_function' );    //for non login user

You can use the above code inside your functions.php file. If you are creating a theme or plugin then use the above code in the theme or plugin directory to implement functionality to use Ajax in WordPress.

You need to register function with two hooks, first for login users and another for non-login users.

You will need to use wp_ajax_ as the prefix then you can use your_action_name for login users.

For non-login users, you will have to use wp_ajax_nopriv_ as a prefix then your_action_name.

To call the ajax function from your main file, you can use the below code.

jQuery.ajax({
  url : "<?php echo admin_url('admin-ajax.php'); ?>",
  data : {
  action : 'my_action_name',
  name : name,
  phone : phone
  },
  method : 'POST', //Post method
  success : function( response )
  { 
     res = JSON.parse(response);
     console.log(res);
  },
  error : function(error){ console.log(error) }
});

You can use the above code to call your ajax function.

Once a time, I also struggled to use ajax in WordPress. So I thought to create an article to other developers know about this situation. Now you should know how to use ajax in WordPress.

If you want to know more about WordPress then follow our other articles like how to create a dynamic widget in WordPress?

If your want a WordPress website then visit 91 Websquare.

Leave a Comment

Your email address will not be published. Required fields are marked *

This div height required for enabling the sticky sidebar