I am trying to build a custom wordpress ajax login form but I can't get it sorted. Here is the codes I use:
HTML:
<form class="well form-inline" id="login">
<div class="rowmargin">
<h4>Login</h4>
</div>
<div class="rowmargin">
<input type="text" name="username" id="loginUsername" class="input-medium" placeholder="Username">
<input type="password" name="password" id="loginPassword" class="input-medium" placeholder="Password">
</div>
<a class="btn btn-primary" id="loginButton"><i class="icon-check icon-white"></i> Login</a>
</form>
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#loginButton").click(function() {
var username = $('#loginUsername').val();
var password = $('#loginPassword').val();
var rememberme = "forever";
var redirect = '<?php bloginfo('url'); ?>';
var data = {
user_login: username,
user_password: password,
remember: rememberme,
redirect_to: redirect
}
$.ajax({
url: '<?php bloginfo('url'); ?>/wp-login.php',
data: data,
type: 'GET',
dataType: 'jsonp',
success: function( result ) {
if (result.success==1) {
alert("Ok!");
} else {
alert("Not Ok!");
}
}
});
});
});
</script> <!-- Login Script --->
Can someone tell me what am I doing wrong here?
WordPress: Simple Ajax Login Form
<form id="login" action="login" method="post">
<h1>Site Login</h1>
<p class="status"></p>
<label for="username">Username</label>
<input id="username" type="text" name="username">
<label for="password">Password</label>
<input id="password" type="password" name="password">
<a class="lost" href="<?php echo wp_lostpassword_url(); ?>">Lost your password?</a>
<input class="submit_button" type="submit" value="Login" name="submit">
<a class="close" href="">(close)</a>
<?php wp_nonce_field( 'ajax-login-nonce', 'security' ); ?>
</form>
--
<?php
//add this within functions.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(),
'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();
}
Create a file ajax-login-script.js within theme's directory and paste this js
jQuery(document).ready(function($) {
// Show the login dialog box on click
$('a#show_login').on('click', function(e){
$('body').prepend('<div class="login_overlay"></div>');
$('form#login').fadeIn(500);
$('div.login_overlay, form#login a.close').on('click', function(){
$('div.login_overlay').remove();
$('form#login').hide();
});
e.preventDefault();
});
// 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 = ajax_login_object.redirecturl;
}
}
});
e.preventDefault();
});
});
You would need to use wp function for login.
http://codex.wordpress.org/Function_Reference/wp_signon
Then use ajax to access this function to log in. You could write a log in function in functions.php
Click below to see how to use ajax in wordpress.
http://wpmu.org/how-to-use-ajax-with-php-on-your-wp-site-without-a-plugin/
<form class="well form-inline" id="login">
<div id="message"></div>
<div id="loading" style="display:none;"></div>
<div class="rowmargin">
<h4>Login</h4>
</div>
<div class="rowmargin">
<input type="text" name="username" id="loginUsername" class="input-medium" placeholder="Username">
<input type="password" name="password" id="loginPassword" class="input-medium" placeholder="Password">
</div>
<a class="btn btn-primary" id="loginButton"><i class="icon-check icon-white"></i> Login</a>
</form>
jQuery(document).ready(function(){
jQuery('#loading').hide();
jQuery("#loginButton").click(function() {
jQuery('#message').hide().html('');
jQuery('#loading').hide();
var input_data = jQuery('#login').serialize();
var logUser = jQuery('#loginUsername').val();
var logPass = jQuery('#loginPassword').val();
if(logUser == '' && logPass != ''){ jQuery('#message').show().html('Your Username is empty!'); return false; }
if(logPass == '' && logUser != ''){ jQuery('#message').show().html('Your Password is empty!'); return false; }
if(logUser == '' && logPass == ''){ jQuery('#message').show().html('Your Username and Password is empty!'); return false; }
jQuery('#loading').show();
jQuery.ajax({
type: "POST",
url: "<?php echo site_url('wp-login.php','login_post'); ?>",
data: input_data,
success: function(msg) {
// login success. redirect users to some page.
jQuery(location).attr('href', '<?php echo home_url( '/thank-you/' ); ?>');
},
error: function(msg) {
// login error.
jQuery('#message').show();
jQuery('#message').html("<?php _e('Your login is not correct. Please try again.'); ?>");
jQuery('#loading').hide();
}
});
return false;
});
});
All AJAX-requests in WordPress must go though wp-admin/admin-ajax.php. wp-login.php won't respond.
http://codex.wordpress.org/Class_Reference/WP_Ajax_Response
There is a set of actions available but none of them comes close to a login-method. You could register your own actions though and handle the login process yourself if you know what you are doing.
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)
add_action('wp_ajax_my_login_action','my_action');
add_action('wp_ajax_nopriv_my_login_action','my_action');
function my_action(){
$userdata = array(
'user_login' => $_POST['user_login'],
'user_password' => $_POST['user_password']
);
$user = wp_signon($userdata);
$response = array();
if ( is_wp_error( $user)) {
$response = array('status'=>'fail', 'msg' => $user->get_error_message() );
}
else{
$response = array('status'=>'pass');
}
echo json_encode($response);
die;
}
add_shortcode('login','loginfunction');
function loginfunction()
{
if( is_user_logged_in() ){
echo 'logout';
}
?>
<center>Login Form:</center>
<form action="" method="post" id="login">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control form-control-sm" id="user_login" aria-describedby="emailHelp" name="user_login">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control form-control-sm" id="user_password" aria-describedby="emailHelp" name="user_password">
</div>
<input type="hidden" name="action" value="my_login_action">
<button type="submit" class="btn btn-primary btn-block">log in</button>
<div class="sign-up">
Don't have an account? Create One
</div>
</form>
<script>
var ajax_url= '<?php echo admin_url('admin-ajax.php');?>';
jQuery(document).ready(function($){
$("#login").submit(function(e){
e.preventDefault();
$.ajax({
type:"POST",
url: ajax_url,
data:{
action:'my_login_action',
user_login:$('input[name="user_login"]').val(),
user_password:$('input[name="user_password"]').val()
}
}).done(function(response){
let result = JSON.parse(response);
if(result.status=='pass')
{
window.location.href='http://localhost/check_wp/';
}
else{
// alert(result.msg);
alert('Sorry Password is worrng');
}
})
});
});
</script>
<?php
}
Related
I am new in CI and I am trying to upload image but dont know why its not uploading,
Here is my view,
<form action="<?php echo site_url('admin/test/'.$param2.'/add'); ?>" enctype="multipart/form-data" method="post" id = 'mcq_form'>
<input type="hidden" name="question_type" value="mcq">
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="attachment" name="attachment" onchange="changeTitleOfImageUploader(this)">
<label class="custom-file-label" for="attachment"><?php echo get_phrase('attachment'); ?></label>
</div>
</div>
<div class="text-center">
<button class = "btn btn-success" id = "submitButton" type="button" name="button" data-dismiss="modal"><?php echo get_phrase('submit'); ?></button>
</div>
</form>
<script>
$('#submitButton').click( function(event) {
$.ajax({
url: '<?php echo site_url('admin/test/'.$param2.'/add'); ?>',
type: 'post',
data: $('form#mcq_form').serialize(),
success: function(response) {
if (response == 1) {
success_notify('<?php echo get_phrase('question_has_been_added'); ?>');
}else {
error_notify('<?php echo get_phrase('no_options_can_be_blank_and_there_has_to_be_atleast_one_answer'); ?>');
}
}
});
showLargeModal('<?php echo site_url('modal/popup/test/'.$param2); ?>', '<?php echo get_phrase('test'); ?>');
});
</script>
on Controller I am trying to get image data but dont know why its not fetching,
print_r($_FILES['attachment']['name']);
die();
I don't understand, what I am missing. Please help me out.
You can try it like this
<input type="file" name="logo" class="form-control" value="">
in your controller
$logo = '';
if (!empty($_FILES['logo']['name'])) {
/* Conf Image */
$file_name = 'profile_' . time() . rand(100, 999);
$configImg['upload_path'] = './uploads/profile/';
$configImg['file_name'] = $file_name;
$configImg['allowed_types'] = 'png|jpg|jpeg';
$configImg['max_size'] = 2000;
$configImg['max_width'] = 2000;
$configImg['max_height'] = 2000;
$configImg['file_ext_tolower'] = TRUE;
$configImg['remove_spaces'] = TRUE;
$this->load->library('upload', $configImg, 'logo');
if ($this->logo->do_upload('logo')) {
$uploadData = $this->logo->data();
$logo = 'uploads/profile/' . $uploadData['file_name'];
} else {
$this->custom_errors['logo'] = $this->logo->display_errors('', '');
}
}
Please tell me, I ran into a problem. There is a site based on Laravel 5.5. The site has a multilanguage (two languages en/ru). For multilanguage I'm using:
dimsav/laravel-translatable
mcamara/laravel-localization
Added language files to the directory resources/lang/ru. The problem is the validation of the form. The site has a feedback form in the modal window, working with ajax (sending and validating), error messages are displayed only in the default language, the default language is en. I tried to send data from the form without the help of ajax, everything works well, messages are displayed in both Russian and English.
reoutes/web.php
Route::group(['prefix' => LaravelLocalization::setLocale()], function(){
Route::get('/', 'PagesController#getProfile')->name('profile');
Route::get('/skills', 'PagesController#getSkills')->name('skills');
Route::get('/portfolio', 'PagesController#getPortfolio')->name('portfolio');
Route::get('/resume', 'PagesController#getResume')->name('resume');
Route::post('/contact', 'PagesController#contact');
});
controller
public function contact(Request $request){
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'message' => 'required'
]);
if ($validator->passes()) {
Mail::to('mycontactform#mail.ru')->send(new Contact($request));
return response()->json(['success'=>'Message sent successfully!']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
js
$(document).ready(function() {
$(".btn-send-message").click(function(e){
e.preventDefault();
$.ajax({
url: "/contact",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
});
var $success_msg = $(".print-success-msg");
var $error_msg = $(".print-error-msg");
function printSuccessMsg() {
$success_msg.html('Message sent successfully!');
$success_msg.css('display','block');
$success_msg.delay(5000).fadeOut(350);
$('#contact-form')[0].reset();
}
function printErrorMsg (msg) {
$error_msg.find("ul").html('');
$error_msg.css('display','block');
$.each( msg, function( key, value ) {
$error_msg.find("ul").append('<li>'+value+'</li>');
});
$error_msg.delay(5000).fadeOut(350);
}
});
form
<div class="modal-body col-md-8 offset-md-2">
<div class="alert alert-danger print-error-msg" style="display:none">
<strong>Errors:</strong>
<ul></ul>
</div>
<div class="alert alert-success print-success-msg" style="display:none"></div>
{!! Form::open(['id'=>'contact-form']) !!}
<div class="form-group">
<input class="form-control" type="text" name="name" id="name" placeholder="Your Name">
</div>
<div class="form-group">
<input class="form-control" type="email" name="email" id="email" placeholder="Your Email">
</div>
<div class="form-group">
<textarea class="form-control" name="message" id="message" rows="3"></textarea>
</div>
<button type="button" class="btn btn-success btn-send-message"><i class="fas fa-paper-plane"></i>
Send Message <span id="loading" style="display: none;"><img class="loader"
src="{{ asset('images/loading.gif') }}"></span>
</button>
{!! Form::close() !!}
</div>
Use LaravelLocalization::getLocalizedURL() which returns an URL adapted to $locale.
So your ajax code will be.
$.ajax({
url: "{{ LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLocale(),'/contact') }}",
type:'POST',
data: $('#contact-form').serialize(),
beforeSend: function() {
$("#loading").show();
$(".fa-paper-plane").hide();
},
complete: function() {
$("#loading").hide();
$(".fa-paper-plane").show();
},
success: function(data) {
if($.isEmptyObject(data.error)){
printSuccessMsg();
}else{
printErrorMsg(data.error);
}
}
});
When you return your response try to use this helper __('translated_string')
To use this helper, you have to create some translate.php file in those folders resources/lang/en and resources/lang/en
For example:
File resources/lang/en/translate.php should contain this array
return [
'success_message' => 'Message sent successfully!',
];
File:
resources/lang/ru/translate.php should contain this array
return [
'success_message' => 'Сообщение успешно отправлено!',
];
For example:
return response()->json(['success'=> __('translate.success_message') ]);
To get some translated string, use dot notation for this helper;
Laravel localization helper
<div class="modal-body">
<form>
<div class="form-group">
<label for="email" class="col-form-label">Email address:</label>
<input type="email" class="form-control" id="signUpEmail" name="email">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Password:</label>
<input type="password" class="form-control" id="signUpPassword" name="password" onchange="check_pass()">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Confirm Password:</label>
<input type="password" class="form-control" id="signUpConPassword" name="password" onchange="check_pass()">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="signUpSubmit" disabled="true" >Sign Up</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function check_pass()
{
//alert(document.getElementById('signUpPassword').value);
if (document.getElementById('signUpPassword').value ==
document.getElementById('signUpConPassword').value) {
document.getElementById('signUpSubmit').disabled = false;
}
else
{
document.getElementById('signUpSubmit').disabled = true;
}
}
$('#signUpSubmit').click(function()
{
//alert("signup completed");
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: $email,
password: $password
},
success: function() {
alert('Email Sent');
}
});
});
</script>
This code snippet shows ReferenceError: $email is not defined when I click on the signupSubmit button although I defined the variable inside the function.
I also try
var email=document.getElementById('signUpEmail').value;
var password = document.getElementById('signUpPassword').value;
but, same error. I guess there is a problem in variable declaration. What is the correct form of variable declaration inside the function?
You have to change the $email and $password to email ,password
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: email,
password: password
},
success: function() {
alert('Email Sent');
}
});
Remove the $
data: {
email: $email,
password: $password
},
The data being passed has two properties - "email" and "password", the values of the properties are stored in the variables email and password.
Your code should look like this:
/* Remove these two lines */
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
...
data: {
"email": $("#signUpEmail").val(),
"password": $("#signUpPassword").val()
}
The $ is the jQuery function call, and the "#signUpEmail" is the selector for the element with an id of "signUpEmail". The val() method will return the value of the input.
document.getElementById("something").value
is the same as
$("#something").val()
If you're using jQuery for the Ajax, you might as well use it to get the values.
i am working on commenting module in my project by ajax. i am getting this error
POST http://127.0.0.1:8000/comments 500 (Internal Server Error)
and the data not post. what i am doing wrong? My route is a resource route and i want to display it without refreshing the page .
Form
<form action="{{route('comments.store')}}" method="post">
{{ csrf_field() }}
<div class="col-md-11 col-sm-11">
<div class="form-group">
<textarea name="comment-msg" id="comment-name" cols="30" rows="1" class="form-control" placeholder="comment here..."></textarea>
<input type="hidden" id="eventID" name="eventID" value="<?php echo $eventData->id; ?>">
<input type="hidden" id="userID" name="userID" value="<?php echo Auth::user()->id; ?>">
</div>
</div>
<div class="col-md-12">
<button type="submit" id="submit-comment" class="btn-primary pull-right">Comment</button>
</div>
</form>
Ajax Call
<script>
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')}
});
$( '#submit-comment' ).click(function() {
var formData = {
'message' : $('#comment-msg').val(),
'eventID' : $('#eventID').val(),
'userID' : $('#userID').val(),
};
$.ajax({
type : 'POST',
url : '{{route('comments.store')}}',
data : formData,
dataType : 'json',
encode : true,
success: function (response) {
console.log(response);
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
}
});
event.preventDefault();
} );
</script>
Controller
public function store(Request $request)
{
$content = $request->input( 'comment-msg' );
$userID = $request->input( 'userID' );
$eventID = $request->input( 'eventID' );
$response=Comment::create([
'user_id' => $userID,
'event_id' => $eventID,
'message' => $content,
]);
return response()->json($response);
}
Route
Route::resource('comments', 'CommentsController');
Is it possible to make codeigniter not to redirect after a failed login attempt and show a message on the same login box.
My login box is a popup type, which appears after I have clicked on the login button and disappears after clicking on the background.
Controllers
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required|trim|callback_validate_credentials');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run()){
$data=array(
'email' => $this->input->post('email'),
'is_logged_in' => 1
);
$this->session->set_userdata($data);
redirect('site/members');
}else {
$this->main();
}
}
public function validate_credentials(){
$this->load->model('model_users');
if($this->model_users->can_log_in()){
echo 'success';
} else {
echo 'failed';
}
}
I was trying to change elses with error messages but it still redirected to another page.
Html:
<div id="login-box" class="login-popup">
<input id="username" name="email" value="" type="text" autocomplete="on" placeholder="Username">
<input id="password" name="password" value="" type="password" placeholder="Password">
<button name="login_submit" class="submitbutton" onclick="checkFormData()">Login</button>
</div>
<script>
function checkFormData(){
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>site/validate_credentials",
data: {
email: $("#email").val(),
password: $("#password").val()
},
success: function(response) {
if(response == 'success'){
location.href = 'site/members';
} else {
$("#errors").show();
}
}
});
}
</script>
If you want to have the alert in the modal, you'll want to check the data with ajax (javascript or jquery). For example you'd have something like this:
function checkFormData(){
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>your_controller/validate_credentials",
data: {
email: $("#email").val(),
password: $("#password).val()
},
success: function(response) {
if(response == 'success'){
location.href = <where you want to send them>;
} else {
$("#errors").show();
}
}
});
}
And your HTML would look something like:
<div class="hide" id="errors">Incorrect username/password.</div>
<input type="email" id="email" />
<input type="password" id="password" />
The class="hide" is meant to be something CSS related where you would have something like "display: none;".
Then in your controller you'd check like this:
if($this->model_users->can_log_in()){
echo 'success';
} else {
echo 'failed';
}
The echoed response is what will be sent to your ajax success function.
Edit:
You need to not use the form submission for the above to work, because with that method we don't want to submit the form, we want to pass the data from it.
<div id="login-box" class="login-popup">
<input id="username" name="email" value="" type="text" autocomplete="on" placeholder="Username">
<input id="password" name="password" value="" type="password" placeholder="Password">
<button name="login_submit" class="submitbutton" onclick="checkFormData()">Login</button>
</div>
I've also changed the javascript function above to be viewed as a function.
use
window.location.href = '/redirectpage'