I’m new to WordPress. I have a jQuery code like this… in my header.php
file.
jQuery(document).ready(function(){
jQuery("#wp-submit").click(function(){
username=jQuery("#userName").val();
password=jQuery("#passWord").val();
jQuery.ajax({
type: "POST",
url: "<?php echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true') {
jQuery("div#result").css('display', 'inline', 'important');
jQuery("div#result").html("Login Successful");
console.log('true');
}
else{
jQuery("div#result").css('display', 'inline', 'important');
jQuery("div#result").html("Wrong username or password");
}
} });
return false;
});
});
and here is the php code in the same file (header.php):
<?php
$uName = $_POST['name'];
$pWord = md5($_POST['pwd']);
$results= $wpdb->get_results("select * from wp_users where user_email="".$uName."" and user_pass="".$pWord.""");
if(count($results)==1)
{
echo 'true';
}
else {
echo 'false';
}
I’m not able to send request to server, i got a 404 error.
What am i doing wrong?
1 Answer
Ajax url should be set to wp-admin/admin-ajax.php
as ajax requests should be handled via wp-admin/admin-ajax
in wordpress.
if ajaxurl is not defined you can get it by defining html attribute data-url
as data-url="<?php echo get_admin_url().'admin-ajax.php'?>"
.
jQuery(document).ready(function($){
$("#wp-submit").on('click',function(e){
e.preventDefault();
username = $("#userName").val();
password = $("#passWord").val();
ajaxurl = $(this).data('url');
$.ajax({
type: "POST",
url: ajaxurl,
data : {
name : username,
password : password,
action : 'check_user_login'
},
success: function(response){
if(response =='true') {
$("div#result").css('display', 'inline', 'important');
$("div#result").html("Login Successful");
console.log('true');
}else{
$("div#result").css('display', 'inline', 'important');
$("div#result").html("Wrong username or password");
}
}
});
});
});
Now Create your ajax function as
function user_login(){
//do your stuff here
global $wpdb;
$username=$_POST['name'];
$password=$_POST['password'];
$hash = md5($password);
$query = $wpdb->prepare( "SELECT * FROM `wp_users` WHERE `user_email` = %s AND `user_pass` = %s", $username, $hash );
$result = $wpdb->get_results($query);
if (count($result)==1) { echo 'true';
echo '<span>Login Successful</span>'; exit();
} else if(count($result) < 1) {
echo 'false'; exit(); }
}
Now the ajax function should be hooked to hook
wp_ajax_*
and wp_ajax_nopriv_*
. Here, * is your action value i.e data.action so it becomes
add_action('wp_ajax_nopriv_check_user_login','user_login');
add_action('wp_ajax_check_user_login','user_login');