How to send ajax request from WordPress using POST method

Ajax is a way to get, post, update, and delete data without refreshing the page. WordPress ajax is different as compared to the normal ajax in PHP. The WordPress ajax, URL is the same for all ajax requests but there is one param action and it is unique for every request. Also, the action param can define which function call on an ajax request.

Step 1: template file

Following code for the template file code. In this code, we have created a form with name and age fields and we will post this form data using ajax. Also, after posting data we will get data posted in ajax response and print it on the same page. Using form ID sendAjaxFormId we will post this form and after the ajax response display data using IDs responseName responseAge .

<form id="sendAjaxFormId">
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" id="name" placeholder="Enter name">
</div>
<div class="form-group">
<label>Age</label>
<input type="text" class="form-control" id="age" placeholder="Enter age">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<p>Entered Name: <span id="responseName"></span></p>
<p>Entered Age: <span id="responseAge"></span></p>

Step 2: custom.js file

In the custom.js file, we have JQuery code to send Ajax request to the function.php file and return back the response in the same file. Some information about Ajax params:

formData => used to send/post data.

url => to set Ajax request URL (it’s common for all ajax requests).

type => Ajax request method (it can get, post, delete, etc)

dataType => Ajax request and response data type.

data => data param contains action, posted data two params. Action should be unique for every request.

success => if the request is successfully processed, then get a response in success function/param.

error => if the request does not process successfully or occurred error during this then the error can catch in the error function.

jQuery(document).ready(function() {
    jQuery('#sendAjaxFormId').submit(function(ev) {
        ev.preventDefault();
        var formData = {
            name: jQuery('#name').val(),
            age: jQuery('#age').val()
        }
        
        jQuery.ajax({
            url: ajaxObject.ajaxUrl,
            type: "post",
            dataType: "json",
            data: {
                action: 'form_post_data',
                data: formData
            },
            success: function(response) {
                console.log(response);
                jQuery('#responseName').html(response.data.name);
                jQuery('#responseAge').html(response.data.age);
            },
            error: function(error) {
                console.log(error);
            }
        });
    });    
});

Step 3: function.php

In this file, we have done two things. First, handle ajax request and second localize PHP variables to pass in JS file.

wp_enqueue_scripts hook is used to enqueue the JS file. wp_localize_script is used to pass params to custom.js file. So, we passed the Ajax URL in the following code.

wp_ajax_form_post_data is a combined hook. wp_ajax_ is common for all requests and form_post_data is an action that is passed from the custom.js file. wp_ajax_nopriv_ hook allows running requests by unauthenticated or any user. So, you can miss or remove this from your code.

In the handleFormPostData method, we checked and return the same posted data in JSON format. Because we set dataType JSON while sending Ajax from the JS file.

add_action('wp_enqueue_scripts', 'myScriptEnqueue');

function myScriptEnqueue() {
    wp_enqueue_script('custom-js', get_stylesheet_directory_uri() . '/js/custom.js', array('jquery'));
    wp_localize_script(
        'custom-js',
        'ajaxObject',
        array('ajaxUrl' => admin_url('admin-ajax.php'))
    );
}

add_action('wp_ajax_form_post_data', 'handleFormPostData');
add_action('wp_ajax_nopriv_form_post_data', 'handleFormPostData');

function handleFormPostData() {
    $response = array();
    $response['message'] = "Error";
    $response['data'] = [];

    if (isset($_POST['data']) && !empty($_POST['data'])) { 
        $response['message'] = "Success";       
        $response['data'] = $_POST['data'];
    }
        
    echo json_encode($response);
    wp_die();
}

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.

How to install WordPress

WordPress is an easy job to install and run. It takes just 5 minutes to install and run the basic setup of your website. WordPress gives you lots of prebuild features like you can set any pre-build theme, or plugin as per your requirements. Also, there are some ways to customize WordPress as well.

WordPress recommends itself to run PHP 7.4 at least. PHP 7.4 supported WordPress version 5.3 to 6.1 (latest). You can check the supported version list on the official documentation of WordPress.  PHP Compatibility and WordPress Versions

The following steps are for localhost in case you are installing it on the server then use server name in place of localhost to manually install WordPress.

Step 1:

Download WordPress from its official website Download WordPress, if you have not already downloaded it. Extract the zip file and place it PHP code run directory. In the htdocs directory (Folder), if you are using xampp in windows. In Linux OS you may find the html directory.

Note: You can rename the extracted file whatever you want. I renamed it with wordpress-6.1.1

Step 2:

Go to PhpMyAdmin and add the new database for your website. I created the same name database as the directory name of unzip files wordpress-6.1.1 . After that hit the URL http://localhost/wordpress-6.1.1/ and you will see the install screen in the browser window.

Note: Above install URL may be different in your case. So, use http://localhost/{YOUR DIRECTORY NAME}/ it to run the installation.

Step 3:

Now, You will see different languages, you can select any language whatever you want to install for the website. English is a global language and most people know about English in the World. So, I am selecting English and clicked on the continue button.

Step 4:

Now, you will the welcome screen with some information. You just need to click on Lets Go the button.

Note: If for any reason this automatic file creation does not work, do not worry. All this does is fill in the database information to a configuration file. You may also simply open wp-config-sample.php in a text editor, fill in your information, and save it as wp-config.php.

Step 5:

Add your database connection details. You can choose a different prefix name, i.e. dbt_ or may proceed with the default prefix name wp_

After filling in the database details click on submit button. You will see the following screen. Click on the Run the installation button.

Step 6:

After this, you will see the information needed screen you just add some information for the site i.e. site name, admin login details, email, etc., and click on the Install WordPress button.

Note: Search engine visibility options for SEO purposes. So, if you are on localhost then check it because nobody wants to index our local system sites. But if you are installing it on the server then leave it unchecked.

Step 7:

After this, you will see the success screen, click on the login button and you will see the wp-admin login page. Just log in with the details that you added in step 6 and you will see the admin dashboard, where you can manage all the things.

 

Hope this blog is helpful to you. If you have any queries or feedback please comment to me.