Wordperss admin-ajax.php error 400 Bad Request - php

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!

Related

Wordpress based ajax form submission not working

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;
}

Sending form data to a custom post type WP with AJAX request

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.

Multiple Ajax login forms

I have mulitple logins on my WordPress, when the user logs in I want to redirect them to another page. E.g. login form 1, takes you to page 1. Login form 2, takes you to page 2.
I have followed the tutorial http://natko.com/wordpress-ajax-login-without-a-plugin-the-right-way/ which was excellent in gaining an understanding of how this works.
All is working well, however form 2 is not submitting and seems to be getting stuck on 'Sending user info, please wait..'
Could anyone please help?
<div class="half-login">
<div class="global-login">
<div class="login-dets">
<div class="loginform">
<form id="login" action="login" method="post">
<p class="status"></p>
<input id="username" type="text" name="username" placeholder="Username">
<input id="password" type="password" name="password" placeholder="Password">
<input class="submit_button" type="submit" value="Login" name="submit">
</form>
</div>
</div>
</div>
<div class="exhibition-login">
<div class="login-dets">
<div class="loginform">
<form id="login2" action="login" method="post">
<p class="status2"></p>
<input id="username2" type="text" name="username" placeholder="Username">
<input id="password2" type="password" name="password" placeholder="Password">
<input class="submit_button" type="submit" value="Login" name="submit">
<?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</form>
<?php } ?>
</div>
</div>
</div>
</div>
JS
jQuery(document).ready(function($) {
// Perform AJAX login on form submit
$('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': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
'username': $('form#login #username').val(),
'password': $('form#login #password').val(),
'security': $('form#login #security').val() },
success: function(data){
$('form#login p.status').text(data.message);
if (data.loggedin == true){
document.location.href = "link-1/";
}
}
});
e.preventDefault();
});
// Perform AJAX login on form submit
$('form#login2').on('submit', function(e){
$('form#login2 p.status2').show().text(ajax_login_object.loadingmessage);
$.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
'username': $('form#login2 #username2').val(),
'password': $('form#login2 #password2').val(),
'security': $('form#login2 #security2').val() },
success: function(data){
$('form#login p.status2').text(data.message);
if (data.loggedin == true){
document.location.href = "/link-2/";
}
}
});
e.preventDefault();
});
});
PHP
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/ajax-login-script.js', array('jquery') );
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('/home-page-new'),
'loadingmessage' => __('Sending user info, please wait...')
));
// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxlogin', 'ajax_login' );
}
// Execute the action only if the user isn't logged in
if (!is_user_logged_in()) {
add_action('init', 'ajax_login_init');
}
function ajax_login(){
// First check the nonce, if it fails the function will break
check_ajax_referer( 'ajax-login-nonce', 'security' );
// Nonce is checked, get the POST data and sign user on
$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) ){
echo json_encode(array('loggedin'=>false, 'message'=>__('Wrong username or password.')));
} else {
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...')));
}
die();
}
Thank you so much!
Given the error you mention in the comments:
ALERT:- [DOM] Found 2 elements with non-unique id #security: ​
It appears that the security field is some form of authentication which is failing in the request due to the duplicate id attributes. The PHP is then returning an unauthorised response due to the missing/invalid data in the request.
To fix this you need to fix the duplicate ids (by making them unique) and then include the values correctly in the AJAX requests.

Redirect after form submission with ajax in WordPress

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
});

Message: undefined index in CI image upload

I am working a CI developer since from 1 year and i didn't face this type of error. I try to get image name through post but it will give me image like this: c:\fakelink\imagename, i don't know what's the issue kindly help me to solve this issue.
Here is my view code:
<form id="profile_update" enctype="multipart/form-data">
<div class="form-group">
<img src="<?php echo base_url()?>public/assets/plugins/images/users/varun.png" class="thumb-lg img-circle" alt="img">
<div class="row">
<div class="form-group col-sm-6">
<input type="file" class="form-control" id="user_image" name="user_image">
</div>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
here is Ajax Code:
type: "POST",
url: base_url + "admin/update_profile",
data: 'user_image=' + user_image,
here is Model Code:
$config = array(
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png|jpeg',
'max_size' => '2048',
);
if($_FILES['user_image']['name'] != '') {
$image = 'user_image';
$upload_data = $this->do_upload($image, $config);
if ($upload_data['condition'] == 'error') {
echo json_encode(array('condition' => 'error', 'message' => $upload_data['error'] . ' (Profile image)'));
exit;
} else {
$account_array['foto'] = $upload_data['upload_data']['file_name'];
}
}
The error is located on this line:
if($_FILES['user_image']['name'] != '') {
Thanks to all for any help.
Your Ajax code is not correct. Add these lines to your Ajax:
var formdata = new FormData ($('#profile_update')[0]); //get form data using HTML5 FormData Object
$.ajax({
type: "POST",
url: base_url + "admin/update_profile",
data: formdata,
contentType: false, //set content type to false so that the browser will set the content type to multipart
processData: false, //Also set process data to false so that the data being sent will not be serialized
success: function(res){
//Success function goes here..
}
});
Use **name user_image instead of id.**

Categories