CodeIn House

  • Laravel
  • WordPress
  • jQuery
  • Javascript
  • Contact
Home   jQuery   WordPress Ajax Tutorial – How to Insert Data Using Aja ...

WordPress Ajax Tutorial – How to Insert Data Using Ajax in WordPress Theme ?

June 12, 2021 by SNK 6

how to insert data in database using ajax in wordpress theme

In this WordPress ajax tutorial we are going to learn how to insert data using ajax in WordPress theme and insert data using ajax in WordPress.

Ajax simply means sending the data into the database or backed server without having to reload the page so that your visitor will not feel that they are leaving the website or the current page.

lets get started.

What are we going to do ?

  1. Create a form.
  2. Grab all the form data using jQuery and send data over ajax.
  3. Fetch and insert data into database from the WordPress.

Step 1: Creating a form

While submitting the form through ajax request in WordPress, it has its own way to send data over ajax and reach to the function inside your theme. And that is achieved through the URL admin_url('admin-ajax.php'); that is provided by WordPress to reach the admin part of the website securely.

If you want to read more about it, you can refer to the documentation of Ajax provided by WordPress. Paste this code wherever you want your form to be displayed. Like index.php / single.php / page.php  or even sidebar.php. You can even keep these codes if you have some external page Template referred by the page.

Creating a form
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div class="container">
<h1>WordPress AJAX Insert Post Demo</h1>
<form id="enquiry_email_form" action="#" method="POST" data-url="<?php echo admin_url('admin-ajax.php'); ?>" enctype="multipart/form-data">
<div class="form-group">
<label for="">Enter Title</label>
<input type="text" class="form-control" name="post_title" id="post_title" placeholder="Enter Title" />
</div>
<div class="form-group">
<label for="">Enter Description</label>
<textarea name="post_description" id="post_description" cols="30" rows="10" class="form-control" placeholder="Enter Post Description"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary"><i class="glyphicon glyphicon-pencil"></i> Submit</button>
</div>
</form>
</div>

 

Step 2: Grabbing all the form data using jQuery and Sending to Server Via Ajax Request

I am using jQuery to achieve my result. You can also do this with the help of vanilla JavaScript if you want. Also take a note at the action variable inside the data object inside in the $.ajax() function.

We are going to use that function inside the WordPress ajax function.

Grabbing the form values and sending data over ajax
JavaScript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$("#enquiry_email_form").on("submit", function (event) {
            event.preventDefault();
 
            var form= $(this);
            var ajaxurl = form.data("url");
            var detail_info = {
                post_title: form.find("#post_title").val(),
                post_description: form.find("#post_description").val()
            }
 
            if(detail_info.post_title === "" || detail_info.post_description === "") {
                alert("Fields cannot be blank");
                return;
            }
 
            $.ajax({
 
                url: ajaxurl,
                type: 'POST',
                data: {
                    post_details : detail_info,
                    action: 'save_post_details_form' // this is going to be used inside wordpress functions.php
                },
                error: function(error) {
                    alert("Insert Failed" + error);
                },
                success: function(response) {
                    alert("Insert Success" + response);
                }
            });
        })

Now once you click submit data is sent over to the ajax and we need to grab the values inside our theme functions.php using ajax function of WordPress.

 

Step 3 : Fetch and Insert Data into Database from the WordPress

let’s write WordPress ajax function to grab the data and insert into database.

WordPress Ajax function
PHP
1
2
//Saving Ajax Data
add_action('wp_ajax_nopriv_save_post_details_form','save_enquiry_form_action');

If you have just noticed the ajax function of WordPress the first argument inside the add_action function there is  wp_ajax_nopriv_save_post_details_form

This string consists two main parts which is nopriv and save_post_details_form.

If you use nopriv in the code that means ajax will fail if the user is logged in. If the user is not logged in then only the ajax trigger works.

While the other save_post_details_form is the action that we have wrote on our JavaScript code inside the $.ajax() inside the data object. It should be matched properly else the function won’t work.

The second argument inside the add_action function is the name of function that we are going to use to grab the data and do what ever we want and lastly, return action true or false depending in our result and display to the user in the front end.

Lets write one.

WordPress Grabbing Value and Sending With Ajax
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function save_enquiry_form_action() {
 
    $post_title = $_POST['post_details']['post_title'];
    $post_description = $_POST['post_details']['post_description'];
$args = [
'post_title'=> $post_title,
'post_content'=>$post_description,
'post_status'=> 'publish',
'post_type'=>'post',
'post_date'=> get_the_date()
];
 
$is_post_inserted = wp_insert_post($args);
 
if($is_post_inserted) {
return "success";
} else {
return "failed";
}
}

If you want to customize the message and display the different output and if , else condition will do the trick inside the ajax and you can make our outcome message more descriptive.

This is it for the WordPress ajax form submit example. If you have any problem, you can contact us via contact form or mention them in comments.

SHARE ON
Buffer

Enjoyed this article?

Like us on

jQuery WordPress wordpress ajax form submit example wordpress custom ajax

Avatar for SNK

About SNK

Hello Welcome to my Blog. I develop Websites Using Laravel Framwork & WordPress. Get Latest updates on Facebook | Twitter

6 Responses...

  1. Avatar for SNKKumar Muthaiah says

    May 31, 2021 at 11:05 am

    Where to put the files ? That you missed? I always see articles in online with missing information so that user need to delay his or her work!

    Reply
    • Avatar for SNKSNK says

      June 5, 2021 at 4:15 pm

      Put it inside wp-content/themes/yourtheme/functions.php. It is the common knowledge that you require to know some of the things before using the CMS platform. All the things inside the theme file go through functions.php. Please read the documentation first at least before using any CMS.

      Reply
  2. Avatar for SNKkumar muthaiah says

    May 31, 2021 at 11:11 am

    I need complete steps to do add/update/delete/view from a table in word press page. I use elementor plugin. I’m a wordpress beginner. I need to make sure the elementor ui is there too, i don’t want my own custom ui.

    Reply
    • Avatar for SNKSNK says

      June 5, 2021 at 4:13 pm

      I haven’t created tutorials on all insert add update delete view in WordPress. That will be a good idea. I will work on it.

      Reply
  3. Avatar for SNKWaldek says

    June 18, 2021 at 2:52 pm

    It’s weird:
    $is_post_inserted = wp_insert_post($args);
    The wp_insert_post method returns an error or on success the ID of the created post. Maybe it’s better to do something like this (I think aloud – pseudocode):
    $is_post_inserted = is_numeric(wp_insert_post($args)) ? true : false;

    Reply
    • Avatar for SNKSNK says

      June 19, 2021 at 1:36 am

      No it isn’t. I really haven’t noticed on other languages but if you insert the data into database using wp_insert_post($args) it will return either 0 or 1. So, in php if you check if(0) it is always false and either is true. However, the one you suggested is the better approach which is used nowadays.

      Reply

Leave a Reply Cancel reply

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

Get Connected !! With Us

TOP POSTS

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

TUTORIALS TILL DATE

  • September 2022 (6)
  • June 2021 (7)
  • October 2020 (5)
  • September 2020 (6)
  • September 2018 (14)
  • August 2018 (3)
  • July 2018 (4)
  • March 2018 (8)
  • February 2018 (5)
  • January 2018 (1)
  • December 2017 (2)
  • August 2017 (8)
  • May 2017 (1)
  • April 2017 (1)
  • March 2017 (4)
  • February 2017 (3)
  • January 2017 (4)

CATEGORIES

  • Angular (2)
  • CSS3 (3)
  • D3 (3)
  • HTML5 (7)
  • JAVA (11)
  • Javascript (20)
  • jQuery (8)
  • Laravel (35)
  • Others (3)
  • PHP (11)
  • Spring (2)
  • WordPress (10)

Top Categories

  • Angular
  • CSS3
  • D3
  • HTML5
  • JAVA
  • Javascript
  • jQuery
  • Laravel
  • Others
  • PHP
  • Spring
  • WordPress

Get in Touch

DMCA.com Protection Status

Recent Articles

  • How to Setup Spring MVC Project From Scratch in Intellij IDEA ?
  • Spring Configuration Class in JAVA [Class VS XML Config]
  • Annotations Based Configuration in Spring Framework
  • How to Configure Spring Framework with XML Configurations?
  • How to Remove Project Name from URL in JSP Project in Intellij IDEA ?

© 2012-22 CodeIn House.  •  All Rights Reserved.