Basically I am beginner to WordPress and ajax and I am trying to make a custom newsletter with Wordpress using ajax method. It seems something is wrong with my code which I have been trying to sort for quite while. any help would be appreciated.
front page code:
<form id="myform" method="POST">
<div class="newsletter" data-aos="fade-up" data-aos-delay="300">
<h2>Newsletter</h2>
<div class="form-element">
<input type="text" class="input-element" name="email" id="email" placeholder="Email"><br>
<span class="email-message" id="email_msg"></span>
<button class="btn form-btn" name="submit" value='Submit' id="submit" type="button">Subscribe</button>
</div>
</div>
<div class="messageDiv"></div>
</form>
ajax:
<script>
jQuery(function() {
jQuery('#myform').submit(function(event){
event.preventDefault();
jQuery.ajax({
dataType : "json",
type : "post",
data : jQuery('#myform').serialize(),
url : my_ajax_object.ajax_url,
success:function(data)
{
jQuery('.messageDiv').html(data.message);
}
});
});
});
</script>
function.php:
function my_enqueue() {
wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
if(isset($_POST['email'])){
global $wpdb;
$email = $_POST['email'];
$con = new mysqli("localhost", "root", "", "blogger", 3306);
$table_name ='newletter';
$sql=$wpdb->insert("newletter", array("email" =>$email));
if($rowResult == 1){
echo json_encode(array('message' => '<h1>form submit sucesss</h1>', 'status'=> 1 ));
}else{
echo json_encode(array('message' => '<h1>error submission</h1>', 'status'=> 0 ));
}
die;
}
Related
I can't find where this error 400 comes from?
FontOffice only avaible for logged in persons.
I'm trying to create a form to post a custom post type through Ajax.
Here is the form in front office:
<form id="form_info" enctype="multipart/form-data">
<div class="form-group">
<label for="titre_info">Titre *</label>
<input type="text" id="titre_info" name="titre_info" placeholder="Titre" />
</div>
<div class="form-group">
<label for="message_info">Message *</label>
<textarea id="message_info" name="message_info" placeholder="Message"></textarea>
</div>
<div class="form-group">
<label for="img_info">Visuel (facultatif)</label>
<input type="file" id="img_info" name="img_info" />
</div>
<div style="text-align:center;">
<input type="submit" id="submit_info" name="submit_info" value="Poster" />
<div class="status_info"></div>
</div>
</form>
Here is my JQuery :
$('#form_info').on('submit',function(e){
$('.status_info').hide();
e.preventDefault();
var validForm = true;
var title = $("#titre_info").val();
var message = $('#message_info').val();
var image = $('#img_info').prop('files');
if(title=="" || message==""){
validForm=false;
}
if(validForm) {
$('.status_info').show().html("<p>Envoi du message en cours...</p>");
$.ajax({
type: 'POST',
dataType: 'json',
contentType: false,
processData: false,
url: '/wordpress/wp-admin/admin-ajax.php',
data: {
'action': 'addinfo',
'titre': title,
'message': message,
'image': image
},
success: function (data) {
$('.status_info').show().html("<p class='success'>Merci de votre ajout</p>");
setTimeout(function(){location.reload();},750);
}
})
} else {
$('.status_info').show().html("<p class='error'>Merci de compléter les champs obligatoires</p>");
$("#titre_info").addClass('error');
$("#message_info").addClass('error');
}
});
Here is my function PHP :
add_action( 'wp_ajax_nopriv_addinfo', 'AddInfo' );
add_action( 'wp_ajax_addinfo', 'AddInfo' );
function AddInfo(){
$titre=$_POST['titre'];
$message=$_POST['message'];
$image=$_POST['image'];
$my_post = array(
'post_title' => $titre,
'post_content' => $message,
'post_status' => 'publish',
'post_type' => 'annonce',
);
$my_new_post = wp_insert_post($my_post);
echo json_encode(array('post'=>$my_new_post,"status"=>"succes"));
die();
}
It used to work but I then try to add the file upload and then everything skratch. Now returned to basic creating simple text post_type I'm stuck with my Error 400 Bas Request on url admin-ajax.php
I also tried to add the security none, same problem.
I tried to use ajax_object to create the ajax url but same probleme.
The Php function change this way :
add_action('init','ajax_register_action');
function ajax_register_action() {
wp_register_script('ajax-addinfo-script', get_stylesheet_directory_uri() . '/ajax-addinfo-script.js', array('jquery'));
wp_localize_script('ajax-addinfo-script', 'ajax_addinfo_object', array('ajaxurl' => admin_url('admin-ajax.php'),));
wp_enqueue_script('ajax-addinfo-script');
add_action( 'wp_ajax_nopriv_addinfo', 'AddInfo' );
add_action( 'wp_ajax_addinfo', 'AddInfo' );
}
And the jQuery call the ajax url this way :
url: ajax_addinfo_object.ajaxurl,
I checked a lot of StackOverflow and Google questions about this error but still can't find where it comes from.
If you can see what's wrong that will be a gret relief!
Thanks a lot!
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 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'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