Image is not uploading in CI - image

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('', '');
}
}

Related

How to run my function from my functions.php to a ajax request

I have a problem getting my function running through ajax.
I need it to use my function when the page has finished loading.
This is not a get function ore Post, it's pure code.
There should be a select opportunity.
I've really searched a lot on google but just can't find the solution.
I would then like to be able to use my php function and display it on the page after the page has finished loading
add_action('wp_ajax_add_woocommerce_file', 'add_woocommerce_file');
add_action('wp_ajax_nopriv_add_woocommerce_file', 'add_woocommerce_file');
function add_woocommerce_file() { ?>
<form class="cart variation" action="" method="post" enctype='multipart/form-data'>
<div class="popup">
<div class="popup-content">
<div class="close-content-container">X</div>
<?php the_content(); ?>
</div>
</div>
<?php
global $product, $post;
$output = '
<select name="variation_id" id="variation_id">
<option value="">Vælg...</option>';
foreach( $product->get_available_variations() as $variation ){
if($variation['max_qty'] > 0) {//Finder ud af om der er vare på lager det den kalde variation.
$option_value = array();
foreach( $variation['attributes'] as $attribute => $term_slug ){
$taxonomy = str_replace( 'attribute_', '', $attribute );
$attribute_name = get_taxonomy( $taxonomy )->labels->singular_name; // Attribute name
$term_name = get_term_by( 'slug', $term_slug, $taxonomy )->name; // Attribute value term name
$option_value[] = ' ' .$term_name. ' ';
}
$option_value = implode( ' :: ', $option_value );
$output .= '
<option class="option_value" value="'.$variation['variation_id'].'">'.$option_value.'</option>';
}
}
$output .= '
</select>';
?><a type="button" id="open" class="open-popup">Kort varebeskrivelse</a><?php
echo $output;
?>
<input type="hidden" name="variation_id" id="variation_id" value="" />
<input type="hidden" name="product_id" value="<?php echo esc_attr( $post->ID ); ?>" />
<input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $post->ID ); ?>" />
<div class="tilfoej"><div class="cart_flex">Læg i kurv</div></div>
</form> <?php
}
add_filter('woocommerce_after_shop_loop_item', 'add_woocommerce_file', 60);
// My ajax call
jQuery(document).ready( function () {
// Ajax
jQuery.ajax({
url: the_ajax_script.ajaxurl,
type: "POST",
dataType: 'html',
data: {
action: 'add_woocommerce_file'
},
success: function( response ) {
jQuery(".variation").show();
},
error : function() {
alert("virker ikke");
}
});
});
// output on category
<div class="variation"></div>
$(window).on('load', function() {
// code here
});
Can you try this?

Laravel 5: When store data to database The server responded with a status of 405 (Method Not Allowed)

I m new in Laravel and trying to add data to the database via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" I define two routes for this one is for form page
Route::get('/create/{id}', 'Participant\ParticipantProjectDefinitionController#create')->name('participant.project-definition.create');
and other route to save this data like this:
// To save Project definition Data
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
And the Ajax code I'm using is this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: {
'_token' : token,
'customer_name' : $('#field_name_0').val(),
'customer_name' : $('#field_data_0').val(),
// 'form_fields' : form_fields
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
Controller code
/**
* create project Definition Form
*
*/
public function create(request $request, $id){
$ProjectDefinitionFields = ProjectDefinitionFields::all();
$ProjectDefinitionFieldRow = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
// dd($ProjectDefinitionFieldRow);
return view('participants.project_definition.create', ['ProjectDefinitionFieldRow' => $ProjectDefinitionFieldRow]);
}
public function store(request $request, $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields){
$project = ProjectDefinitionFields::find('field_id');
$count = ProjectDefinitionFields::where('project_definition_id','=', $id)->count();
$pd_id = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
for($i=0;$i<$count;$i++){
$data[]= array (
'field_name'=>$request->get('field_name_'.$i),
'field_data'=>$request->get('field_data_'.$i),
'user_id' => Auth::user()->id,
// 'user_id' => $request->user()->id,
'project_definition_id' => $pd_id,
// 'field_id' => $projectDefinitionFields->id,
);
}
$project_data = ProjectDefinitionData::create($data);
if($project_data){
return response()->json($project_data);
}
}
Model
on ProjectDefinition
public function formFields(){
// return $this->hasMany('App\Model\ProjectDefinitionFields');
return $this->belongsTo('App\Model\ProjectDefinitionFields');
}
on projectDefinitionFields
public function projectDefinition(){
return $this->belongsTo('App\Model\ProjectDefinition');
}
This is my create.blade.php
<form id="create_project_definition_data_form" enctype="multipart/form-data" >
#csrf
{{ method_field('PUT') }}
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
#section('scripts')
<script src="{{ asset('js/participants/project-definition.js') }}"></script>
<script>
// on document ready
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var indexPdUrl = "{{ route('participant.projectDefinition') }}";
var token = "{{ csrf_token() }}";
{{-- // var addUrl = "{{ route('participant.project-definition.create') }}"; --}}
storeDefinitionFormData(token, baseUrl);
// console.log(addUrl);
});
</script>
ERROR
Request URL:http://127.0.0.1:8000/participant/project-definition/create/2kxMQc4GvAD13LZC733CjWYLWy8ZzhLFsvmOj3oT
Request method:POST
Remote address:127.0.0.1:8000
Status code: 405 Method Not Allowed
Version:HTTP/1.0
Add method attribute in form
method="post"
Change your route from
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
to
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
Firstly, you should post here what's your problem and where's your problem we don't need to see all of your code to solve a basic problem.
Your form should be this:
<form id="create_project_definition_data_form" enctype="multipart/form-data" method='post'>
#csrf
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
You should use 'post' method when you're creating a something new, this is safer than using 'get' method. so change route method too.
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
also, in your 'ParticipantProjectDefinitionController->store()' function has
$id, User $user, ProjectDefinitionFields $ProjectDefinitionFields parameters but your router not. We can fix it like this:
Route::post('/store-project-definition-data/{id}/{user}/{ProjectDefinitionFields}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
That means you should pass all of them to your controller.
Soo we can edit your ajax call like this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: { // $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields
'_token' : token,
'id' : 'your_id_field',
'user' : '{{ Auth::user() }}',
'ProjectDefinitionFields' : 'your_definition_fields' // you need to pass type of 'ProjectDefinitionFields'
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
before try it, I'll give you a advice. Read whole documentation and review what others do on github or somewhere else
Route::match(['GET','POST'],'/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
You can try this Route it will resolve 405

ajax form request from a while - confuse variable

I want to send a form with a button from a while, but I have a problem. If post the button, the form confuse the variable. E.g: i post the button with id 1, and the script get the variable from the last input.
Code:
index:
<?php
$res = getProdus();
foreach($res as $row) { ?>
<form action="addtocart.php" method="POST">
<div class="col-12 col-sm-6 col-md-4 single_gallery_item women wow fadeInUpBig" data-wow-delay="0.2s">
<div class="product-img">
<img src="img/product-img/product-1.jpg" alt="">
<div class="product-quicview">
<i class="ti-plus"></i>
</div>
</div>
<div class="product-description">
<h4 class="product-price">$39.90</h4>
<p>Jeans midi cocktail dress</p>
<input type="hidden" name="addtcart" value="<?=$row['ID'];?>">
<button type="submit" class="add-to-cart-btn">ADD TO CART</button>
</div>
</div>
</form>
<?php } ?>
the ajax request:
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'addtcart' : $('input[name=addtcart]').val()
};
$.ajax({
type : 'POST',
url : 'addtocart.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
and the addtocart.php
<?php
include("includes/functions.php");
session_start();
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if (empty($_POST['addtcart']))
$errors['addtcart'] = 'Este necesar produsul id-ului.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$ok = AddToCart(filtrare($_POST['addtcart']), getSpec("username", "users", "email", $_SESSION['magazin-user']));
if($ok == 1) {
$data['success'] = true;
$data['message'] = 'Success!';
} else {
$data['success'] = false;
$errors['mysqli'] = "Nu s-a realizat bine query-ul.";
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
Replace your button code with this
<button type="submit" value="<?=$row['ID'];?>" class="add-to-cart-btn">ADD TO CART</button>
and after that replace you
make changes to your script code
$(".add-to-cart-btn").click(function() {
var formData = {
'addtcart' : $(this).val()
};
.
.
.
and your rest of the code.

How to insert custom data in database using Opencart

Am creating my store using Opencart. Here am creating a custom page called sales_performance.
Am trying to insert some value in database.
But i can't insert the data, how can i do that?.
And also it not showing error
Following my code:
Controller
sales_performance.php
<?php
class ControllerProductSalesPerformance extends Controller
{
private $error = array();
private $data = array();
public function index()
{
$this->load->language('product/allproduct');
$this->document->setTitle($this->language->get('Sales Performance'));
$this->load->model('catalog/allproduct');
$data['action']=$this->url->link('product/sales_performance','','SSL');
$this->data['text_list'] = $this->language->get('text_list');
$this->data['text_no_results'] = $this->language->get('text_no_results');
$this->data['text_confirm'] = $this->language->get('text_confirm');
$this->data['text_missing'] = $this->language->get('text_missing');
$this->data['column_order_id'] = $this->language->get('column_order_id');
$this->data['column_customer'] = $this->language->get('column_customer');
$this->data['column_status'] = $this->language->get('column_status');
$this->data['column_total'] = $this->language->get('column_total');
$this->data['column_date_added'] = $this->language->get('column_date_added');
$this->data['column_date_modified'] = $this->language->get('column_date_modified');
$this->data['column_action'] = $this->language->get('column_action');
$this->data['entry_return_id'] = $this->language->get('entry_return_id');
$this->data['entry_order_id'] = $this->language->get('entry_order_id');
$this->data['entry_customer'] = $this->language->get('entry_customer');
$this->data['entry_order_status'] = $this->language->get('entry_order_status');
$this->data['entry_total'] = $this->language->get('entry_total');
$this->data['entry_date_added'] = $this->language->get('entry_date_added');
$this->data['entry_date_modified'] = $this->language->get('entry_date_modified');
$this->data['button_invoice_print'] = $this->language->get('button_invoice_print');
$this->data['button_shipping_print'] = $this->language->get('button_shipping_print');
$this->data['button_add'] = $this->language->get('button_add');
$this->data['button_edit'] = $this->language->get('button_edit');
$this->data['button_delete'] = $this->language->get('button_delete');
$this->data['button_filter'] = $this->language->get('button_filter');
$this->data['button_view'] = $this->language->get('button_view');
//$data['token'] = $this->session->data['token'];
$pagination = new Pagination();
//$pagination->total = $order_total;
//$pagination->page = $page;
$data['pagination'] = $pagination->render();
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['header'] = $this->load->controller('common/header');
$this->data['column_left'] = $this->load->controller('common/column_left');
$this->data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('default/template/product/sales_performance.tpl', $this->data));
}
public function insertSelectedCustomer()
{
#####Add sales persion achievement####
if ($this->request->server['REQUEST_METHOD'] == 'POST')
{
$date = $_GET['date'];
$sales_person_id = $_GET['sales_person_id'];
$sales_person_name = $_GET['sales_person_name'];
$customer_id = $_GET['customer_id'];
$customer_name = $_GET['customer_name'];
$achievement = $_GET['achievement'];
$query = $this->db->query("insert into ".DB_PREFIX."sales_person_achievement('date') value('".$date."')");
if($query==false)
{
echo ''.mysql_error();
}
}
##### Add sales persion achievement ####
}
}
This is my tpl file
sales_performance.tpl
<form action="<?php echo $action; ?>" method="POST" class="form-inline" enctype="multipart/form-data">
<div class="form-group">
<label for="">Select Date:</label>
<input type="text" name="date" id="datepicker" class="form-control" placeholder="Select Date">
<input type="hidden" name="sales_person_id" value="<?php echo $sales_person1['customer_id']; ?>">
<input type="hidden" name="sales_person_name" value="<?php echo $sales_person1['name']; ?>">
<input type="hidden" name="customer_id" value="<?php echo $customer['customer_id'];; ?>">
<input type="hidden" name="customer_name" value="<?php echo $customer['name'];; ?>">
</div>
<div class="form-group">
<label for="">Fill Achievement Amonut:</label>
<input type="number" name="achievement" class="form-control" placeholder="Achievement Amount">
</div>
<div class="form-group">
<input type="submit" id="saveachievement" name="save" class="btn btn-primary">
</div>
</form>
<script type="text/javascript">
$('#saveachievement').on('click', function() {
var date = document.getElementsByName('date')[0].value;
var sales_person_id = document.getElementsByName('sales_person_id')[0].value;
var sales_person_name = document.getElementsByName('sales_person_name')[0].value;
var customer_id = document.getElementsByName('customer_id')[0].value;
var customer_name = document.getElementsByName('customer_name')[0].value;
var achievement = document.getElementsByName('achievement')[0].value;
//alert(achievement);
location="index.php?route=product/sales_performance&sales_person_id="+sales_person_id+"&customer_id="+customer_id;
});
</script>
Actually am miss spelling for value
$query = $this->db->query("insert into ".DB_PREFIX."sales_person_achievement('date') value('".$date."')");
change To
$query = $this->db->query("insert into ".DB_PREFIX."sales_person_achievement('date') values('".$date."')");
i mean value change to values
Now its working.

Wordpress AJAX Login

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
}

Resources