Answer the question
In order to leave comments, you need to log in
How to save form data to database using ajax/jquery?
Tell me a real solution, how to safely save data from the form to the database and display this data in the site admin panel? Plus it will be parallel to send data to soap too.
It is possible on Wordpress, Joomla - it is possible without.
Tried on Joomla with ChronoForms5 - everything worked fine without ajax enabled (in ChronoForms settings). As soon as I turn on ajax, it stops sending email and saving it to the database.
Found an interesting plugin for Wordpress - Contact Form DB . I read in the description for it that it can work directly with html forms (and not those created in wordpress, such as contact form 7).
But so far I have not been able to get it to work with my form.
I created a topic on the module forum (you can see all my code in more detail there):
https://wordpress.org/support/topic/how-use-this-p...
Form in HTML
<form id="f2" action="" method="post">
<input type="text" name="name" placeholder="ФИО" maxlength="50" required>
<input type="text" name="email" placeholder="Email" maxlength="50" required>
<input type="text" name="phone" placeholder="Телефон" maxlength="50" required>
<input type="text" name="org" placeholder="Учебное заведение" maxlength="50" required>
<button class="btn" type="submit">Отправить</button>
</form>
$(document).ready(function() {
//...
$("form#f2").submit(function() {
var form = $(this),
name = form.find("input[name='wpname']").val(),
email = form.find("input[name='wpemail']").val(),
phone = form.find("input[name='wpphone']").val(),
org = form.find("input[name='wporg']").val();
if (!name || !email || !phone || !org) {
alert("Заполните поля формы.");
return false;
}
var email_regexp = /[email protected]+\..+/i;
var email_test = email_regexp.test(email);
if (!email_test) {
alert("Введен некоректный Email-адрес.");
return false;
}
$.ajax({
type: "POST",
url: "wp-content/themes/epixx/mail.php",
data: $("form#f2").serialize(),
success: function(response) {
$(".order_status").show();
$("form#f1").hide();
$("form#f2").hide();
console.log('response: ' + response);
},
error: function(xhr, str){
alert('Возникла ошибка: ' + xhr.responseCode);
}
}).done(function() {
setTimeout(function() {
$.fancybox.close();
}, 2000);
});
return false;
});
});
<?php
$recepient = "[email protected]";
$sitename = "Sitename";
$name = trim($_POST["wpname"]);
$email = trim($_POST["wpemail"]);
$phone = trim($_POST["wpphone"]);
$org = trim($_POST["wporg"]);
$pagetitle = "New message from site \"$sitename\"";
$message = "Name: $name\r\nEmail: $email\r\nPhone: $phone\r\nOrganization: $org";
mail($recepient, $pagetitle, $message, "Content-type: text/plain; charset=\"utf-8\"$EOL From: $name <$email>");
/* contact-form-7-to-database */
require_once(ABSPATH . 'wp-content/plugins/contact-form-7-to-database-extension/CFDBShortCodeSavePostData.php');
$handler = new CFDBShortCodeSavePostData;
$handler->handleShortcode(null);
<br />
<b>Warning</b>: require_once(ABSPATHwp-content/plugins/contact-form-7-to-database-extension/CFDBShortCodeSavePostData.php) [<a href='function.require-once'>function.require-once</a>]: failed to open stream: No such file or directory in <b>/var/www/u0081082/public_html/donkon.ru/devwp/wp-content/themes/epixx/mail.php</b> on line <b>16</b><br />
<br />
<b>Fatal error</b>: require_once() [<a href='function.require'>function.require</a>]: Failed opening required 'ABSPATHwp-content/plugins/contact-form-7-to-database-extension/CFDBShortCodeSavePostData.php' (include_path='.:') in <b>/var/www/u0081082/public_html/donkon.ru/devwp/wp-content/themes/epixx/mail.php</b> on line <b>16</b><br />
Answer the question
In order to leave comments, you need to log in
Being in WordPress is very inconvenient to use separate php scripts from it (like my mail.php). The ABSPATH variable did not work.
I created a send_form() function in function.php (located in the theme folder) and added all the code from my mail.php to it.
Before any require get_template_directory()............. wrote:
function send_form(){
//весь код из mail.php тут
}
add_action('wp_ajax_send_form', 'send_form');
add_action('wp_ajax_nopriv_send_form', 'send_form');
I would advise you to use jquery.validate or something similar in 1, and not write bicycles, but you can collect data using form.serialize()
js
var params = form.serialize();
// вернет примерно следующее name=&email= и т д
$.post(url, params, function(response) {
}, 'json');
$ajaxData = array();
// Тут все серверные операции, включая добавление, мыло и все что угодно,
// ну учтите, чтобы отловить теже ошибки и показать их, надо передавать в массив ajaxData а в JS это дело ловить через .response.error и т д
die(json_encode($ajaxData));
add to php script
wp_enqueue_script( 'bundle', plugins_url( '/bundle.js', __FILE__ ), array('jquery'), '1.11', true );
wp_localize_script( 'bundle', 'MyAjax', array(
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('myajax-nonce')
) );
add_action( 'wp_ajax_cr_new_patient', 'cr_new_patient' );
function cr_new_patient() {
$nonce = $_POST['nonce'];
if(wp_verify_nonce( $nonce, 'myajax-nonce' )){
$id = sanitize_text_field($current_user->user_login);
$ur = sanitize_text_field($_POST["patient_ur"]);
$dob = sanitize_text_field($_POST["patient_dob"]);
$gender = sanitize_text_field($_POST["patient_gender"]);
$ident = sanitize_text_field($_POST["patient_ident"]);
$other = sanitize_text_field($_POST["patient_other"]);
$loc = sanitize_text_field($_POST["patient_loc"]);
$query="INSERT INTO patient (
'ur', 'dob', 'gender', 'ident', 'other', 'loc'
) VALUES (
'$ur', '$dob', '$gender', '$ident', '$other', '$loc',
)";
$mysqli = new mysqli("xxx","xxx","xxx","xxx");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
handleSubmit(data) {
jQuery.post(
MyAjax.ajaxurl,
{
'action': 'cr_new_patient',
'patient_ur': data.patient_ur,
'patient_dob': data.patient_dob,
'patient_gender': data.patient_gender,
'patient_ident': data.patient_ident,
'patient_other': data.patient_other,
'patient_loc': data.patient_loc,
'nonce' : MyAjax.nonce
},
function(response){
alert('The server responded: ' + response);
}
);
}
To quickly collect form data without selectors, you can use JQuery.SerializeArray().
I made a pull request for SerializeObject, but they refused, citing the presence of plugins.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question