everyone!I'm creating WordPress plugin. The main goal of this plugin is creating form, and after user will fill out this form data from the form will be written to the database. I made the part of the plugin that is responsible for creating the database and displaying the form using a shortcode. But faced with a problem. How to send data from a form to a database using the ajax method.
After activating the plugin, a table is created in the database:
if ( ! function_exists ( 'jal_install' ) ) {
function jal_install (){
global $wpdb;
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
$table_name = $wpdb->prefix . "liveshoutbox";
$charset_collate = $wpdb->get_charset_collate();
if($wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") !== $table_name){
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
client_name tinytext NOT NULL,
client_mail varchar(55) DEFAULT '' NOT NULL,
PRIMARY KEY (id)
) $charset_collate;";
dbDelta( $sql );
}
}
}
The form on the page is displayed with a shortcode:
function form_shortcode() {
ob_start(); ?>
<form class="main_form" method="POST" action="">
<input type="text" name="user_name">
<input type="text" name="user_mail">
<button type="submit">Subnit</button>
</form>
<div class="main_form__success">Greate Worck!</div>
<?php
return ob_get_clean();
}
add_shortcode('form-shortcode', 'form_shortcode');
For adding data from the form to the database, there is a file: form_action.php I placed it in the main plugin directory. And for initiating the work of this file I use the form_ajax.js
$("form.main_form").submit(function() {
var th = $(this);
$.ajax({
type: "POST",
url: "/form_action.php",
}).done(function() {
$(th).find('.main_form__success').addClass('active').css('display', 'flex').hide().fadeIn();
setTimeout(function() {
$(th).find('.main_form__success').removeClass('active').fadeOut();
th.trigger("reset");
}, 3000);
});
return false;
});
As a result, I cannot get to this form_action.php file. And I have an error. The code tries to find it in the root of the site, but not in the root of the plugin. I do not understand how to fix it, tell me how to do it please.
this is a basic syntax for ajax jquery request
here , in the data field , you have to specify your form using id ,name or tag
$.ajax({
url: "/../form_action.php",
type: "POST",
data:$('form').serialize(),
success: function (data) {
.....
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.