I'm tring to create a simple contact form using jquery to validate the form and ajax to pass it to php and WP wp_mail to send it.
I have a simple form like this.
<form role="form">
<div class="form-group">
<label class="">Name</label>
<input type="text" id="name" class="form-control" name" />
</div>
<div class="form-group">
<label class="">Email</label>
<input type="text" id="email" class="form-control" name="email" />
</div>
<?php wp_nonce_field( 'atex_php', 'atex_nonce' ); ?>
<button class="submit">Submit</button>
</form>
jQuery to validate the inputs and send to php
//IsEmail and fadeOut functions aren't shown
$atj(function(){
$atj('submit').click(function(e) {
e.preventDefault();
if(verfiyFields()) {
$atj.post({
data : {
action : "request",
firstName : $atj("#name").val(),
email : $atj("#email").val(),
}
})
}
});
})
//Verfiy
function verfiyFields() {
var flag = true;
var name = $atj('#name');
var email = $atj('#email');
if(name.val().indexOf(' ') === -1 ){
name.parent().prepend('<p class="form-error">Please enter name, first space last</p>');
fadeOut();
flag = false;
}
if(!IsEmail(email.val())){
email.parent().prepend('<p class="form-error">Please enter valid email address</p>');
fadeOut();
flag = false;
}
return flag;
}
And the php in the function.php
add_action( 'wp_ajax_nopriv_request', 'my_action_callback' );
function my_action_callback() {
if ( isset( $_POST['atex_nonce'] ) && wp_verify_nonce( $_POST['atex_nonce'], 'atex_php' ) ) {
$name = $_POST['firstName'];
$email = $_POST['email'];
$send_to = me#test.co.uk;
$subject = 'Request from'. $name;
$success = wp_mail($send_to, $subject, $message);
if($success){
return true;
}else{
return false;
}
}
}
I'm getting a 404 Not Found for [object%20Object] in the Network tab of chrome dev tools when the submit is clicked.
How can I get this to work
you need to enqueue some scripts:
Let's say you validation script is in a file called validationForm.js
function ajaxScript(){
$params = array(
'ajaxurl' => admin_url('admin-ajax.php')
);
wp_enqueue_script( 'validation', get_template_directory_uri() . '/js/validationForm.js', array(), '', true );
wp_localize_script( 'validation', 'ajax_object', $params );
}
add_action( 'wp_enqueue_scripts', 'ajaxScript' );
Also you need to add this action hook:
add_action('wp_ajax_amc_form_fr', 'my_action_callback');
Then, use ajax jquery function to send info:
var dataString = $(form).serialize();
jQuery.ajax({
type: "POST",
url: ajax_object.ajaxurl,
dataType : 'JSON',
data : 'action=jQuery.ajax({
type: "POST",
url: ajax_object.ajaxurl,
dataType : 'JSON',
data : 'action=amc_form_fr&'+dataString,&'+dataString,
success: function(response) {
console.log(response);
// your code
}
If im not wrong, i think that is. And check this link
Related
I want create custom login page. I have some problems with ajax-admin php. When i send data for loggined i get response 0, and 404 error. Also when i try get success response data similarly give null. Where my mistake ?
My main task after successful authorization was redirected to the main page and if unsuccess authorization give error text
login.php
<form id="login" action="login" method="post" >
<p class="status"></p>
<div class="form-group">
<label>Email</label>
<input class="form-control required" id="logusername" type="email" name="logusername">
</div>
<div class="form-group">
<label>Password</label>
<input class="form-control required" id="logpassword" type="password" name="logpassword" >
</div>
<a class="forgot-pass" href="<?php echo wp_lostpassword_url(); ?>">Forgot Password</a>
<div class="d-flex justify-content-center mt-3">
<input type="submit" class="btn btn-success submit_button" value="Login">
<?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</div>
</form>
ajax-login-script.js
jQuery(document).ready(function($) {
$('form#login').on('submit', function(e){
$('form#login p.status').show().text(ajax_login_object.loadingmessage);
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
'action': 'ajax_login',
'username': $('form#login #logusername').val(),
'password': $('form#login #logpassword').val(),
'security': $('form#login #security').val() },
success: function(data){
console.log(data); // null
$('form#login p.status').text(data.message);
if (data.loggedin == true){
document.location.href = ajax_login_object.redirecturl;
} else {
console.log(false);
}
}
});
e.preventDefault();
});
});
function.php
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery'), time() );
wp_enqueue_script('ajax-login-script');
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending user info, please wait...!')
));
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}
if (!is_user_logged_in()) {
add_action('init', 'ajax_login_init');
}
function ajax_login(){
check_ajax_referer( 'ajax-login-nonce', 'security' );
$info = array();
$info['user_login'] = $_POST['username'];
$info['user_password'] = $_POST['password'];
$info['remember'] = true;
$user_signon = wp_signon( $info, false );
if ( !is_wp_error($user_signon) ){
wp_set_current_user($user_signon->ID);
wp_set_auth_cookie($user_signon->ID);
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
}
die();
}
You must have to pass correct hook name after,
The Hook must be end with the name of action you are passing through jQuery request ex.
wp_ajax_nopriv_{action_name} so please correct it first.
add_action( 'wp_ajax_nopriv_ajax_login', 'ajax_login' );
Put this action outside the function and do your login condition inside the hook callback function.
function ajax_login(){
if (!is_user_logged_in()) { // It's not necessary it should be based on your requirement
// Your code goes here.
}
}
So i want to send the form data to a custom post type that i created in WP, with the name, email and the message(text). But i cant send it, the AJAX request its not working. Without the ajax request everything its working. What i missed here?
<div class="group">
<form id="form" class="form" method="post" action="<?php echo admin_url('admin-ajax.php'); ?>">
<div class="form-control1">
<input type="text" placeholder="Name" id="username" name="nume" />
<small>Error message</small>
</div>
<div class="form-control1">
<input type="email" placeholder="Email" id="email" name="email"/>
<small>Error message</small>
</div>
<div class="form-control1">
<textarea class="input" name="mesaj" id="text" name="mesaj" cols="40" rows="5" placeholder="Write a nice message for us:)"></textarea>
<small>Error message</small>
</div>
<button type="submit" id="submit" name="submit">Submit</button>
</form>
</div>
the Jquery:
jQuery('#form').submit(function (event) {
event.preventDefault();
var data = $('#form').serialize();
$.post(window.ajaxObject.ajaxUrl,{
method: 'POST',
action: 'messaging_post',
'data':data,
success: function (response) {
console.log(data);
}
})
});
and PHP:
function ajax_scripts1() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() .'/form.js', array ( 'jquery' ), 1.12, true);
wp_localize_script( 'ajax-script', 'ajaxObject',
array( 'ajaxUrl' => admin_url( 'admin-ajax.php') ));
}
add_action( 'wp_enqueue_scripts', 'ajax_scripts1' );
add_action( 'wp_ajax_messaging_post', 'messaging_post' );
add_action('wp_ajax_nopriv_messaging_post', 'messaging_post');
function messaging_post(){
if(isset($_POST['submit']) == '1') {
$new_post = array(
'ID' => '',
'post_type' => 'dn_message',
'post_status' => 'publish',
'post_title' => $_POST['nume'],
'post_content' => $_POST['mesaj'],
);
//here i introduce the data in the custom type post
$post_id = wp_insert_post($new_post);
$post = get_post($post_id);
$field_key1 = "movie_form";
$value1 = $title;
$update1 = update_field( $field_key1, $value1, $post_id );
$field_key = "email";
$value = $_POST['email'];
$update = update_field( $field_key, $value, $post_id );
};
}
Try this ajax call:
jQuery('#form').submit(function(event) {
event.preventDefault();
var data = "action=messaging_post&" + $('#form').serialize();
console.log(data);
jQuery.ajax(
{
type: "POST",
url: window.ajaxObject.ajaxUrl,
data: data,
success: function(msg) {
console.log(msg);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
Looks like you are treating wordpress action as ajax property. Ajax action should be sent like this with formdata.
I have created a custom html form on WordPress and placed it using HTML widget
<form id="form">
<label for="fname">Full Name</label>
<input type="text" id="fname" name="name" placeholder="Your name..">
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="Your email..">
<label for="contact">Contact number</label>
<input type="tel" id="contact" name="phone" placeholder="Your contact number..">
<label for="subject">Description</label>
<textarea id="subject" name="msg" placeholder="Tell us your requirements.." style="height:100px">
</textarea>
<input type="submit" value="Submit" onclick="myFunction()">
</form>
and here is my js code
function myFunction() {
var name = document.getElementById("fname").value;
var email = document.getElementById("email").value;
var Contact = document.getElementById("contact").value;
var Message = document.getElementById("subject").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1=' + name + '&email1=' + email + '&contact=' + Contact + '&message=' + Message;
if (name == '' || email == '' || Contact == '' || Message == '') {
alert("Please Fill All Fields");
} else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "ajaxjs.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
Now I want to send mail using this form data so How can I send email using WordPress wp-mail.php
First of all, you need to make some changes in your HTML and javascript and have do add few PHP code :
1) Change in form tag
<form id="form" method="post" action="">
2) Add a hidden field in the form with action name
<input type="hidden" name="action" value="my_form_submission">
3) add ajaxurl in functions.php file where you have enqueued your js file
add_action( 'wp_enqueue_scripts', 'your function' );
function enqueue_my_frontend_script() {
wp_enqueue_script( 'my-script', plugin_dir_url(__FILE__).'frontend-scripts.js', array('jquery'), null, true );
$variables = array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
);
wp_localize_script('my-script', "jsObj", $variables);
}
4) In your ajax call, change this
$.ajax({
type: "POST",
url: jsObj.ajaxurl, // this will get ajax url
data: $( "#form" ).serialize() , // send your form data with serialize mode
success: function(html) {
alert(html);
}
});
4) Add ajax actions in theme's functions.php file :
add_action('wp_ajax_my_form_submission', 'my_form_submission_callback');
add_action('wp_ajax_nopriv_my_form_submission', 'my_form_submission_callback');
function my_form_submission_callback(){
$data = $_POST;
$html = $_POST['message'];
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail("toemail#gmail.com", "Some subject", $html, $headers);
}
This way you can get ajax data and pass html wp_mail() function.
Check this link for whole demo : https://dev.to/shwetadanej/ajax-calls-in-wordpress-front-end-2g09
I have form which is using Ajax to be submitted on WordPress. The form works fine and the information from it goes to the database and it is saved correctly.
The problem is that I can't get it to redirect to another page. The form is really simple
<form method="post" id="main">
<?php wp_nonce_field( 'my_nonce' ); ?>
<div class="columns is-multiline">
<div class="column is-4">
<input type="text" name="firstname" />
</div>
<div class="column is-4">
<input type="text" name="middlename" />
</div>
<div class="column is-4">
<input type="text" name="lastname" />
</div>
</div>
<div id="success_message"></div>
<div class="columns">
<div class="column is-3">
<input type="submit" name="submit-button" id="submit-button" value="Submit" />
</div>
</div>
</div>
</form>
Then I have this in functions.php
add_action('wp_enqueue_scripts', 'my_ajax_scripts');
function my_ajax_scripts(){
wp_localize_script( 'myscript', 'myajax', array( 'ajaxurl' => admin_url( '/admin-ajax.php' ) ) );
}
add_action('wp_enqueue_scripts', 'ajax_scripts');
function ajax_scripts(){
wp_enqueue_script( 'form', get_template_directory_uri().'/assets/js/form.js', array('jquery'), '1.0', true );
}
function form(){
global $wpdb;
if (!check_ajax_referer( 'my_nonce' )){
wp_die();
}
$table = UPC_jobs;
$formdata = $_POST['formdata'];
parse_str($formdata, $formdata_array);
$data = array(
'firstname' => $_POST['firstname'],
'middlename' => $_POST['middlename'],
'lastname' => $_POST['lastname'],
);
$format = array(
'%s', '%s', '%s',' %s'
);
$success=$wpdb->insert( $table, $data, $format );
if($success) {
wp_redirect( '/my-target' );
wp_die();
}
}
And if need the js part
$('#main').submit(function(e) {
e.preventDefault();
var form = $(this);
var formdata = (window.FormData) ? new FormData(form[0]) : null;
var data = (formdata !== null) ? formdata : form.serialize();
formdata.append("action", "form");
$.ajax({
type: 'POST',
url: myajax.ajaxurl,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata,
success: function( data ){
window.location.replace("https://example"); // this doesn't work as well
},
});
});
When I click Submit nothing happen, absolutely nothing. All the info is stored in database as is should but the page doesn't react/show anything.
Also working solution would be to just show a message that the form is submitted successfully (not alert)
Have you tried instead of a success callback, use always?
In your case you can try this
$.ajax({
type: 'POST',
url: myajax.ajaxurl,
contentType: false,
processData: false,
dataType: 'JSON',
status: 200,
data: formdata
}).always(function() {
window.location.replace("https://example"); // this doesn't work as well
});
I have created an AJAX function in Wordpress. The function is called on form submission. The function is run, but it is not receiving any of the form data that I have submitted. What am I missing?
PHP Function
I have added the PHP function here, which is called successfully via AJAX. This form creates a new user successfully, but only when I create the variables manually (eg. see $new_user_data['user_login'] = 'This Text Works';). For some reason, the $_POST data isn't coming through to the function.
add_action("wp_ajax_register_user", __NAMESPACE__ . "\\register_user");
add_action("wp_ajax_nopriv_register_user", __NAMESPACE__ . "\\register_user");
function register_user() {
// NONCE VERIFICATION
if ( !wp_verify_nonce( $_REQUEST['nonce'], "rtr_register_nonce")) {
exit("Oops! This is embarassing!");
}
// Get all post data for the user.
$new_user_data = array();
$new_user_data['first_name'] = sanitize_text_field($_POST['first-name']);
$new_user_data['last_name'] = sanitize_text_field($_POST['last-name']);
$new_user_data['user_email'] = $_POST['email'];
$new_user_data['user_pass'] = sanitize_text_field($_POST['password']);
$new_user_data['user_login'] = 'This Text Works';
$new_user_data['role'] = 'subscriber';
// Create the User
$registered_user = wp_insert_user( $new_user_data );
$result['user'] = $registered_user;
// AJAX CHECK
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
JQuery
function registerUser(){
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("form-tab");
// Exit the function if any field in the current tab is invalid:
if (n === 1 && !validateForm()) {
return false;
}
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:
//document.getElementById("regForm").submit();
registerUser();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
$('#nextBtn').click(function () {
nextPrev(1);
});
$('#prevBtn').click(function () {
nextPrev(-1);
});
Form
<?php
$nonce = wp_create_nonce("rtr_register_nonce");
$link = admin_url('admin-ajax.php?action=register_user&nonce='.$nonce);
?>
<form id="regForm" <?php echo 'data-nonce="' . $nonce . '"'; ?> action="<?php echo $link; ?>" method="post" enctype="multipart/form-data">>
<div class="my-3 text-center">
<span class="form-step">1</span>
<span class="form-step">2</span>
</div>
<div class="form-tab">
<p><input name="first-name" placeholder="First Name" oninput="this.className = ''"></p>
<p><input name="last-name" placeholder="Last Name" oninput="this.className = ''"></p>
<p><input name="dob" type="date" oninput="this.className = ''"></p>
</div>
<div class="form-tab">
<p><input name="email" type="email" placeholder="Email" oninput="this.className = ''"></p>
<p><input name="password" type="password" placeholder="Password" oninput="this.className = ''"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" class="btn btn-brand" id="prevBtn">Previous</button>
<button type="button" class="btn btn-brand" id="nextBtn">Next</button>
</div>
</div>
</form>
Seems you are not triggering registerUser() check following script works fine for me
jQuery(document).ready(function($) {
jQuery('body').on('click', '#nextBtn', function() {
registerUser();
});
});
function registerUser(){
var nonce = jQuery('#regForm').attr("data-nonce");
var formData = jQuery('#regForm').serialize();
jQuery.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
add method="post" to your 'form' - 'get' is the default https://stackoverflow.com%2Fquestions%2F2314401%2Fwhat-is-the-default-form-http-method&usg=AOvVaw1dKc3hW4K6r5SwQurLztBw
The "user_login" is a username of the user so probably it doesn't accepts space too.
See also WP Insert Post
Please try passing some username such as "custom_user" and see the result.
Hope this might work.
Ok it was a bit of help from everyone here. But yes, I was calling the AJAX correctly, but not actually submitting the form. I added a .on(submit) to the form and then added a listener to the form to perform the AJAX call on submit. Here's the amendments below.
function nextPrev(n) {
var x = document.getElementsByClassName("form-tab");
if (n === 1 && !validateForm()) {
return false;
}
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
// ADDED THIS SUBMIT() HERE
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
// ADDED AN EVENT LISTENER TO TRIGGER THE AJAX CALL HERE
$('#regForm').on('submit', function () {
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data: {
action: 'register_user',
nonce: nonce,
formData: formData
},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
});