WP admin ajax return 404 - php

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

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

Why does my frontend Wordpress login form get stuck in a redirect loop?

I'm currently building a Wordpress application which requires a custom front end login form, which then redirects the user to a dashboard page once logged in.
The login form however appears to get stuck in a redirect loop, and occasionally just refreshes the login page on submit, instead of redirecting the user.
Any thoughts on why this is happening would be much appreciated
// login.php
<form id="login" action="login" method="post" class="row">
<div class="col-md-12 mb-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupPrepend">#</span>
</div>
<input type="text" class="form-control" id="username" placeholder="Username" name="username" aria-describedby="inputGroupPrepend" required>
</div>
</div>
<div class="col-md-12 mb-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupPrepend">
<svg class="bi bi-lock-fill" width="1em" height="1em" viewBox="0 0 20 20" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<rect width="11" height="9" x="4.5" y="8" rx="2"/>
<path fill-rule="evenodd" d="M6.5 5a3.5 3.5 0 117 0v3h-1V5a2.5 2.5 0 00-5 0v3h-1V5z" clip-rule="evenodd"/>
</svg>
</span>
</div>
<input type="password" class="form-control "name="password" placeholder="Password" aria-describedby="inputGroupPrepend" id="password" />
</div>
</div>
<div class="col-md-12 mb-3">
<div class="input-group">
<input type="submit" name="submit" value="Log in">
</div>
</div>
<div class="col-md-12 mb-3">
<p><a class="lost small" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a></p>
<p class="status"></p>
</div>
<?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</form>
//ajax-login.script.js
jQuery(document).ready(function() {
// Perform AJAX login on form submit
jQuery('form#login').on('submit', function(e){
jQuery('form#login p.status').show().text(ajax_login_object.loadingmessage);
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: ajax_login_object.ajaxurl,
data: {
'action': 'ajaxlogin', //calls wp_ajax_nopriv_ajaxlogin
'username': jQuery('form#login #username').val(),
'password': jQuery('form#login #password').val(),
'security': jQuery('form#login #security').val()
},
success: function(data){
jQuery('form#login p.status').text(data.message);
if (data.loggedin == true){
document.location.href = ajax_login_object.redirecturl;
}
}
});
e.preventDefault();
});
});
// functions.php
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/app/js/ajax-login-script.js', array('jquery') );
wp_enqueue_script('ajax-login-script');
wp_localize_script( 'ajax-login-script', 'ajax_login_object', array(
'ajaxurl' => home_url() . '/wp-admin/admin-ajax.php',
'redirecturl' => get_permalink(200),
'loadingmessage' => __('')
));
// 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();
}
// logout redirect
add_action('wp_logout','ps_redirect_after_logout');
function ps_redirect_after_logout(){
wp_redirect( get_permalink(9) );
exit();
}
// destroy sessions on logout
function destroy_sessions() {
$sessions->destroy_all();//destroys all sessions
wp_clear_auth_cookie();//clears cookies regarding WP Auth
}
add_action('wp_logout', 'destroy_sessions');
// header.php
<?php
// check user login success/fail and redirect to dashboard page
if (is_user_logged_in() && is_page(9)) {
wp_redirect( get_permalink( 200 ) );
exit;
}
?>
Interesting I am using almost the same code :). Here is what I think you should change:
1) admin_url, remove /wp-admin/ you won't need it
2) home_url instead of get_permalink
3) remove you add_action from your function.
if ( ! function_exists( 'ajax_login_init' ) ) {
function ajax_login_init(){
wp_register_script('ajax-login-script', get_stylesheet_directory_uri() . '/js/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('/my-account/'),
'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_init' );
}
}

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

Wordpress modal login works but default login submit not working any more

Im creating a modal wordpress login using the leanmodal js, I figuret it out the form is working fine but I have a problem with the default login.
This is my login form and php function:
<?php
function modal_login_jquery_wp() {
?>
<div id="login">
<div id="login-ct">
<div id="login-header">
<h2 class="login">Login to your account</h2>
<p class="new-account"><?php _e('Do not have an account yet?', 'themename'); ?> <?php _e('Create one for free', 'themename'); ?>.</p>
<a class="modal_close" href="#"></a>
</div>
<form action="login" method="post">
<p class="status"></p>
<div class="txt-fld">
<label class="name" for=""><?php _e('Username', 'themename'); ?></label>
<input id="username" class="good_input" name="username" type="text" />
</div>
<div class="txt-fld">
<label class="pass" for=""><?php _e('Password', 'themename'); ?></label>
<input id="password" name="password" type="password" />
</div>
<div class="btn-fld">
<button id="wp-submit" type="submit"><?php _e('Sign In »', 'themename'); ?></button>
</div>
<label class="rememberme"><input type="checkbox" value="yes" name="remember" checked="checked"><?php _e('Remember me.', 'themename'); ?></label>
<label class="forgot"><a class="lost" href="<?php echo wp_lostpassword_url(); ?>"><?php _e('Lost your password?', 'themename'); ?></label>
<?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</form>
</div>
</div>
<?php
}
add_action('wp_footer', 'modal_login_jquery_wp');
function ajax_login_init(){
wp_register_script('ajax-login-script', get_template_directory_uri() . '/scripts/js/ajax-login.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(),
'loadingmessage' => __('Sending user info, please wait...', 'themename')
));
// 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.', 'themename')));
} else {
echo json_encode(array('loggedin'=>true, 'message'=>__('Login successful, redirecting...', 'themename')));
}
die();
}
all work fine.when I click/open modal I enter username and password and everything is ok, I get the status messagge
so my jquery code is below:
jQuery(document).ready(function($) {
$('#login').on('submit', function(e){
$('#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': $('#login #username').val(),
'password': $('#login #password').val(),
'security': $('#login #security').val() },
success: function(data){
$('#login p.status').text(data.message);
if (data.loggedin == true){
document.location.href = ajax_login_object.redirecturl;
}
}
});
e.preventDefault();
});
});
as I said above everything is working but the problem now is in wp-admin login form.When I want to enter in wp-admin or wp-login.php using the default login nothing happens by clicking on default submit button
and finaly I changed the modal login div name in css and form as #modal-login because it has the same name with the default wordpress login form but now the ajax modal login not working. the status messagge remaining as sending user info and nothing happens.
do you have any idea about this?
Thanks
there is no name for submit button
<button name="give some name" id="wp-submit" type="submit"><?php _e('Sign In »', 'themename'); ?></button>

Categories