Wordpress doesn't recognize AJAX code (Enfold theme) - customization

I'm trying to customize the "lost password" area in my Wordpress theme, called Enfold. Everything it's ok, so my code sends a link to a "new password introduction" area correctly to users email.
The link is: /new-password/?action=rp&key=TDeJEj7vVmmmJqbd&login=my_username
But when the user clicks on this link and the code redirects him to a "[new password introduction]/[repeat password]" area, the button who execute AJAX code after user write his new password and password confirmation is not responding.
I've added the wp_register_script and wp_enqueue_script to functions.php but I think probably here's my error. I've added it this way:
if(!function_exists('avia_register_frontend_scripts'))
{
if(!is_admin()){
add_action('wp_enqueue_scripts', 'avia_register_frontend_scripts');
}
function avia_register_frontend_scripts()
{
$template_url = get_template_directory_uri();
$child_theme_url = get_stylesheet_directory_uri();
//register js
wp_register_script( 'avia-compat', $template_url.'/js/avia-compat.js', array('jquery'), 1, false ); //needs to be loaded at the top to prevent bugs
wp_register_script( 'avia-default', $template_url.'/js/avia.js', array('jquery'), 1, true );
wp_register_script( 'avia-shortcodes', $template_url.'/js/shortcodes.js', array('jquery'), 1, true );
wp_register_script( 'avia-prettyPhoto', $template_url.'/js/prettyPhoto/js/jquery.prettyPhoto.js', 'jquery', "3.1.5", true);
// wp_register_script( 'wp-mediaelement', $template_url.'/js/mediaelement/mediaelement-and-player.min.js', 'jquery', "1", true);
wp_register_script( 'discount', $template_url.'/js/discount.js', 'javascript', "1", true);
wp_register_script( 'reset_user_pass', $template_url.'/js/reset-user-pass.js','jquery', "1", true );
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'avia-compat' );
wp_enqueue_script( 'avia-default' );
wp_enqueue_script( 'avia-shortcodes' );
wp_enqueue_script( 'avia-prettyPhoto' );
wp_enqueue_script( 'wp-mediaelement' );
wp_enqueue_script( 'reset_user_pass' );
Here is the "[new password introduction]/[repeat password]" form code:
<?php
/*Load Scripts for password reset page*/
wp_enqueue_script( 'zxcvbn-async' );
wp_enqueue_script( 'user-profile' );
wp_enqueue_script( 'password-strength-meter' );
wp_enqueue_script( 'user-suggest' );
?>
<form method="post" action="<?php echo get_bloginfo('url') ?>/wp-login.php" id="resetpassform" name="resetpassform">
<input type="hidden" name="login" value="<?php echo $_GET['login'] ?>" autocomplete="off">
<input type="hidden" name="key" value="<?php echo strip_tags($_GET['key']); ?>" />
<p style="margin-bottom:20px" class="description indicator-hint">Your password needs to be at least seven characters. Mixing upper and lower case, numbers and symbols like ! " ? $ % ^ & ) will make it stronger.</p>
<p class="login-username">
<input type="password" tabindex="10" size="20" value="" placeholder="New Password"class="input" id="pass1" name="pass1">
</p>
<p class="login-password">
<input type="password" tabindex="20" size="20" value="" placeholder="Confirm Password" class="input" id="pass2" name="pass2">
</p>
<div class="pass-meter"><div id="pass-strength-result" ><?php _e('Strength indicator'); ?></div></div>
<p class="forgotpass-submit">
<a id="forgot-cancel" href="<?php echo home_url('/signin'); ?>">Cancel</a>
<a id="submitforgotpasswordform" href="javascript:void(0)" style="background-position: 0px 4px;"><input type="submit" tabindex="100" value="Get New Password" id="forgot-submit" name="wp-submit"></a>
</p>
<div class="login-error"><div></div></div>
</form>
Here is the php code to reset pass on validation in my functions.php:
function reset_user_pass(){
parse_str( $_POST['form_values'], $params );
$user = check_password_reset_key($params['key'], $params['login']);
$status='';
// Check if key is valid
if ( is_wp_error($user) ) {
if ( $user->get_error_code() === 'expired_key' ){
$status = 'expiredkey' ;
}
else{
$status = 'invalidkey' ;
}
echo $status;
die;
}
// check if keys match
if ( isset($params['pass1']) && $params['pass1'] != $params['pass2'] ){
$status = 'mismatch';
}else{
// Update the user pass
reset_password($user, $params['pass1']);
$status ='success';
}
echo $status;
die;
}
add_action('wp_ajax_nopriv_reset_user_pass', 'reset_user_pass');
And finally here's the AJAX code who is not responding to submit button:
(function($){
$(document).ready(function() {
// Submit the password reset form via ajax
$( '#resetpassform' ).submit(function(e){
e.preventDefault();
$('.login-error').slideUp();
//check if password fields are empty
if( $('#pass1').val()=='' || $('#pass1').val()=='' ){
return false;
}
var formData= $(this).serialize();
$.ajax({
url: ajaxurl,
type: 'POST',
data: {form_values: formData, action:'reset_user_pass' },
})
.done(function(status) {
switch(status){
case 'expiredkey' :
case 'invalidkey' :
$('.login-error').html('<div>Sorry, the link does not appear to be valid or is expired.</div>').slideDown();
break;
case 'mismatch' :
$('.login-error').html('<div>The passwords do not match.</div>').slideDown();
break;
case 'success' :
$('.login-error').html('<div>Your password has been reset.</div>').slideDown();
break;
default:
console.log(status);
$('.login-error').html('<div>Something went wrong.Please try again </div>').slideDown();
break;
}
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
})
})
})(jQuery)
Thank you so much in advance for your help and time.

Finally the solution was adding the ajax url in a header.php script:
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
Hope it helps.

Related

How can I generate access error and error message, leaving user on the page?

In laravel / jquery apps if I need to make checks if user is logged I make in controller:
$loggedUser = Auth::user();
if ( empty($loggedUser->id) ) {
return response()->json(['error_code'=> 1, 'message'=> "You must be logged!"],HTTP_RESPONSE_INTERNAL_SERVER_ERROR);
}
as I do not need to leave the user from the page, but only restrict some functionality
I show error message above using bootstrapGrowl library.
Now with laravel 7 /livewire 1.3 / turbolinks:5 / alpine#v2 I search how can I generate error and
show similar error message, leaving user on the page ?
UPDATED :
Let me explain it with detailed example :
In laravel / jquery apps I have in JS code :
var quiz_quality_radio= $('input[name=quiz_quality_radio]:checked').val()
var href = this_frontend_home_url + "/make-quiz-quality";
$.ajax( {
type: "POST",
dataType: "json",
url: href,
data: {"quiz_quality_id": quiz_quality_radio, "vote_id": this_vote_id, "_token": this_csrf_token},
success: function( response )
{
$('input[name=quiz_quality_radio]:checked').prop('checked', false);
frontendVote.showQuizQualityResults()
popupAlert("Thank you for rating ! Your rate was added!", 'success')
},
error: function( error )
{
$('input[name=quiz_quality_radio]:checked').prop('checked', false);
popupAlert(error.responseJSON.message, 'danger') // 'info', 'success'
}
});
and relative action in control :
public function make_quiz_quality(Request $request)
{
$requestData = $request->all();
$quiz_quality_id = ! empty($requestData['quiz_quality_id']) ? $requestData['quiz_quality_id'] : '';
$vote_id = ! empty($requestData['vote_id']) ? $requestData['vote_id'] : '';
if ( ! Auth::check()) {
return response()->json(['message' => "To rate you must login to the system !"], HTTP_RESPONSE_BAD_REQUEST);
}
if (empty($quiz_quality_id)) {
return response()->json([
'message' => "To rate you must select quiz quality !",
'quiz_quality_id' => $quiz_quality_id
], HTTP_RESPONSE_OK);
}
$vote = Vote::find($vote_id);
if ($vote === null) {
return response()->json([ 'message' => "Vote Item # " . $vote_id . " not found !"],HTTP_RESPONSE_NOT_FOUND);
}
$loggedUser = Auth::user();
$found_count = QuizQualityResult
::getByVoteIdAndUserId($vote_id, $loggedUser->id)
->count();
if ($found_count > 0) {
return response()->json(['message' => "You have already rated '" . $vote->name . "' # vote !", 'vote_id' => $vote_id],
HTTP_RESPONSE_BAD_REQUEST);
}
$newVoteItemUsersResult = new QuizQualityResult();
try {
$newVoteItemUsersResult->quiz_quality_id = $quiz_quality_id;
$newVoteItemUsersResult->vote_id = $vote_id;
$newVoteItemUsersResult->user_id = $loggedUser->id;
DB::beginTransaction();
$newVoteItemUsersResult->save();
DB::commit();
} catch (Exception $e) {
DB::rollBack();
return response()->json(['message' => $e->getMessage(), 'voteCategory' => null], HTTP_RESPONSE_INTERNAL_SERVER_ERROR);
}
return response()->json(['message' => '', 'id' => $newVoteItemUsersResult->id], HTTP_RESPONSE_OK_RESOURCE_CREATED);
} // public function make_quiz_quality(Request $request)
and in case of error generated in error block I show message with function popupAlert
(implemented with bootstrapGrowl), without leaving the page.
That is what I want to make in livewire / turbolinks / alpine app. How can I do it?
UPDATED # 2:
That is just listing of items user can vote for:
<div class="table-responsive">
<table class="table text-primary">
#foreach($quizQualityOptions as $key=>$next_quiz_quality_option)
<tr>
<td>
<input class="" type="radio" name="quiz_quality_radio" id="quiz_quality_radio_{{ $next_quiz_quality_option }}" value="{{ $key }}">
<label class="col-form-label" for="quiz_quality_radio_{{ $next_quiz_quality_option }}">{{ $next_quiz_quality_option }}</label>
</td>
</tr>
#endforeach
</table>
</div>
<div class="row p-3">
<a class="btn btn-primary a_link" onclick="javascript:frontendVote.MakeQuizQuality()">Rate !</a>
</div>
with 2 restrictions :
User must be logged
Any logged user can vote only once
these 2 errors were genarated at server.
UPDATED # 3:
I found decision with using of axios, like :
<button type="submit" class="btn btn-primary btn-sm m-2 ml-4 mr-4 action_link" #click.prevent="submitNewTodo()">
Submit
</button>
submitNewTodo() {
console.log('submitNewTodo::')
let is_insert= 1
let current_toto_id= 1
axios({
method: (is_insert ? 'post' : 'patch'),
url: '/api/todos' + (!is_insert ? "/" + current_toto_id : ''),
data: {
text : this.new_todo_text,
priority : this.new_todo_priority
},
}).then((response) => {
this.new_todo_text= ''
this.new_todo_priority= ''
this.loadTodosRows()
popupAlert( 'Todo ' + (is_insert ? 'added' : 'updated') + ' successfully !', 'success' )
}).catch((error) => {
var validationErrors= convertObjectToArray(error.response.data.errors.text)
this.validation_errors_text= ''
validationErrors.map((next_error, index) => {
if(next_error && typeof next_error[1] != "undefined" ) {
this.validation_errors_text += '<li>'+next_error[1]+'</li>'
}
})
popupErrorMessage(error.response.data.message)
});
},
With it I show message both on success and failure as I need but I see big disadvantage with it
as I use livewire and I would like to use livewire here, if that is possible...
Hope I explained what I want clearly...
Thanks!
With Alpine.js and axios you could do something like this, note that I'm not sure whether or not this_frontend_home_url, this_vote_id and this_csrf_token will be defined.
<div x-data="quiz()">
<div>
<div class="table-responsive">
<table class="table text-primary">
#foreach($quizQualityOptions as $key=>$next_quiz_quality_option)
<tr>
<td>
<input x-model="selected_quiz" class="" type="radio" name="quiz_quality_radio"
id="quiz_quality_radio_{{ $next_quiz_quality_option }}" value="{{ $key }}">
<label class="col-form-label"
for="quiz_quality_radio_{{ $next_quiz_quality_option }}">{{ $next_quiz_quality_option }}</label>
</td>
</tr>
#endforeach
</table>
</div>
<div class="row p-3">
<a class="btn btn-primary a_link" #click="submitQuizQuality()">Rate !</a>
</div>
</div>
</div>
<script>
function quiz() {
return {
selected_quiz: null,
submitQuizQuality() {
const url = this_frontend_home_url + "/make-quiz-quality";
axios.post(url, {
quiz_quality_id: this.selected_quiz,
vote_id: this_vote_id, // no idea where this is coming from,
_token: this_csrf_token // no idea where this is coming from
}).then(() => {
// reset "checked" state
this.selected_quiz = null;
frontendVote.showQuizQualityResults();
popupAlert("Thank you for rating ! Your rate was added!", 'success');
}).catch(error => {
// reset "checked" state
this.selected_quiz = null;
if (error && error.response) {
popupAlert(error.response.message, 'danger')
}
});
}
}
}
</script>

How to update customer TIN Number in Opencart

Am new in OpenCart MVC, I have page called my_account.tpl. In this page am displaying customer name and tin_number.
If customers want to change their tin_number just fill the TIN Number field and click save, it will update oc_customer tabel.
I tried but data's not update.
Following view, model, and controller codes
View: my_account.tpl
<form action="<?php echo $action;?>" method="POST" enctype="multipart/form-data" class="form-horizontal">
<div class="col-md-9 col-lg-6 col-sm-12">
<?php foreach($customerData as $customer) { ?>
<div class="form-group">
<label>Name:</label>
<input type="text" style="display: none" placeholder="ID" name="id" value="<?php echo $result['tin_number'];?>">
<input type="text" name="name" value="<?php echo $customer['name']; ?>" placeholder="Name" class="form-control" disabled>
</div>
<div class="form-group">
<label>TIN Number:</label>
<input type="text" name="tin_number" value="<?php echo $customer['tin_number']; ?>" placeholder="TIN Number" class="form-control">
</div>
<?php } ?>
<div class="form-group">
<input type="submit" name="save" value="<?php echo 'Save'; ?>" class="btn btn-primary">
</div>
</div>
</form>
Controller: my_account.php
public function edit() {
/*form edit my_account*/
if(isset($_GET['tin_number']))
{
$tin_number=$_GET['tin_number'];
}
$this->load->model('account/customer');
$data['delivery_point']=$this->model_account_customer->getcustomerId($tin_number);
$data['action'] = $this->url->link('account/my_account', '', 'SSL');
if ($this->request->server['REQUEST_METHOD'] == 'POST')
{
$this->model_account_customer->editCustomerTin($this->request->post);
$this->response->redirect($this->url->link('account/home', '', 'SSL'));
echo "<script>javascript: alert('test msgbox')></script>";
}
/*form edit my_account*/
}
Model: my_account.php
public function editCustomerTin($data)
{
$query = $this->db->query("UPDATE " . DB_PREFIX . "customer set tin_number='".$data['tin_number']."' where customer_id=".$data['id']);
}
I got the answer it working in another function see below the coding
controller my_account.php
public function index() {
$this->load->language('account/account');
$this->document->setTitle($this->language->get('heading_title'));
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('Home'),
'href' => $this->url->link('common/home')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('Previous'),
'href' => $this->url->link('common/home', '', 'SSL')
);
if (isset($this->session->data['success'])) {
$data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
} else {
$data['success'] = '';
}
$data['heading_title'] = $this->language->get('heading_title');
$url = '';
$this->load->model('account/customer');
//$data['customerData']=array();
$results=$this->model_account_customer->getCustomerByTin();
foreach($results as $result)
{
$query1 = $this->db->query("SELECT concat(firstname,' ',lastname) as name,tin_number,invoice_no_overwrite FROM " . DB_PREFIX . "customer where customer_id='".$_COOKIE['customerId']."'");
$customer_name= $query1->row['name'];
$tin_number= $query1->row['tin_number'];
$invoice_no_overwrite= $query1->row['invoice_no_overwrite'];
$data['customerData'][0] = array(
'name' => $customer_name,
'invoice_no_overwrite'=> $invoice_no_overwrite,
'tin_number'=>$tin_number
);
}
//var_dump($data['CustomerData']);
/*form edit my_account*/
if ($this->request->server['REQUEST_METHOD'] == 'POST')
{
$this->model_account_customer->editCustomerTin($this->request->post);
$this->response->redirect($this->url->link('account/my_account', '', 'SSL'));
}
/*form edit my_account*/
$data['column_left'] = $this->load->controller('common/column_left');
$data['column_right'] = $this->load->controller('common/column_right');
$data['content_top'] = $this->load->controller('common/content_top');
$data['content_bottom'] = $this->load->controller('common/content_bottom');
$data['footer'] = $this->load->controller('common/footer');
$data['header'] = $this->load->controller('common/header');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/my_account.tpl')) {
$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/account/my_account.tpl', $data));
} else {
$this->response->setOutput($this->load->view('default/template/account/my_account.tpl', $data));
}
}
I don't know how its happen can any one teach me...?

Opencart extra field customer number with validation

I'm trying to add a new field (programmatically) in the (admin->customer->tab general) customer section of customers called customer number. Everything works as expected but I don't want to get double numbers in the database since the user can enter his own number. Every time a new user gets created from the admin the code looks for the last (highest) customer number and adds +1 to it.
I cannot find a solution for this case:
If the customer already exists (edit mode) it should show a not editable value (readonly)
if registering a new customer the last (highest) customer number should be shown (editable). If the user enters a number that is lower than the highest customer number an error should show up and the highest customer number + 1 should show.
This is the code I have so far
In the controller (getForm):
if (isset($this->error['customer_number'])) {
$data['error_customer_number'] = $this->error['customer_number'];
} else {
$data['error_customer_number'] = '';
}
$data['latest_customer'] = $this->model_sale_customer->getLatestCustomerNumber();
if (isset($this->request->post['customer_number'])) {
$data['customer_number'] = $this->request->post['customer_number'];
} elseif (!empty($customer_info)) {
$data['customer_number'] = $customer_info['customer_number'];
} else {
$data['customer_number'] = '0';
}
In the validation (validateForm):
$data['latest_customer'] = $this->model_sale_customer->getLatestCustomerNumber();
if (isset($this->request->post['customer_number']) && ($this->request->post['customer_number'] <= $data['latest_customer'])) {
$this->error['customer_number'] = $this->language->get('error_customer_number');
}
In my customer_form.tpl I have:
<div class="form-group">
<label class="col-sm-2 control-label" for="input-customer-number"><span data-toggle="tooltip" title="<?php echo $help_customer_number; ?>"> <?php echo $entry_customer_number; ?></span></label>
<div class="col-sm-10">
<?php if (!empty($customer_number) || $customer_number != 0){ ?>
<input type="text" name="customer_number" value="<?php echo $customer_number; ?>" placeholder="<?php echo $entry_customer_number; ?>" id="input-customer-number" class="form-control" />
<?php }else{ ?>
<input type="text" name="customer_number" value="<?php echo $latest_customer + 1; ?>" placeholder="<?php echo $entry_customer_number; ?>" id="input-customer-number" class="form-control" />
<?php if ($error_customer_number) { ?>
<div class="text-danger"><?php echo $error_customer_number; ?></div>
<?php } ?>
<?php } ?>
</div>
</div>
This obviously doesn't work because when editing an existing customer the customer number is always lower than the highest customer number in the system (and thus gives an error). Hope some one can help me out with this! Thanks in advance!
For other who are looking into this I solved my problem myself. Ali's comment made me think. I added a hidden input field so I could check against that. Is it an existing customer or not (has number or not). I only have to check for new customers cause that is an inputfield (existing is readonly and thus not editable). The check is to see if this is a new customer (value 0) - is the posted value < The highest customer number. That's it!
This is the code I have so In the controller (getForm):
if (isset($this->error['customer_number'])) {
$data['error_customer_number'] = $this->error['customer_number'];
} else {
$data['error_customer_number'] = '';
}
if (isset($this->request->post['customer_number']) && (($this->request->post['customer_number'] < $data['latest_customer']) && $this->request->post['existing_customer'] == '0')) {
$this->request->post['customer_number'] = '0';
$data['customer_number'] = '0';
} elseif (isset($this->request->post['customer_number'])) {
$data['customer_number'] = $this->request->post['customer_number'];
} elseif (!empty($customer_info)) {
$data['customer_number'] = $customer_info['customer_number'];
} else {
$data['customer_number'] = '0';
}
if (isset($this->request->post['existing_customer'])) {
$data['existing_customer'] = $this->request->post['existing_customer'];
} else {
$data['existing_customer'] = '0';
}
In the validation (validateForm):
$data['latest_customer'] = $this->model_customer_customer->getLatestCustomerNumber();
if (isset($this->request->post['customer_number']) && (($this->request->post['customer_number'] < $data['latest_customer']) && ($this->request->post['existing_customer'] == '0' || $data['existing_customer'] = '0'))) {
$this->error['customer_number'] = $this->language->get('error_customer_number');
}
In my customer_form.tpl I have:
<div class="form-group">
<label class="col-sm-2 control-label" for="input-customer-number"><span data-toggle="tooltip" title="<?php echo $help_customer_number; ?>"> <?php echo $entry_customer_number; ?></span></label>
<div class="col-sm-10">
<?php if (!empty($customer_number) || $customer_number != 0){ ?>
<input type="text" name="customer_number" value="<?php echo $customer_number; ?>" placeholder="<?php echo $entry_customer_number; ?>" id="input-customer-number" class="form-control" readonly />
<input type="hidden" name="existing_customer" value="1" id="input-existing-customer" class="form-control" />
<?php }else{ ?>
<input type="text" name="customer_number" value="<?php echo $latest_customer + 1; ?>" placeholder="<?php echo $entry_customer_number; ?>" id="input-customer-number" class="form-control" />
<input type="hidden" name="existing_customer" value="0" id="input-existing-customer" class="form-control" />
<?php } ?>
<?php if ($error_customer_number) { ?>
<div class="text-danger"><?php echo $error_customer_number; ?></div>
<?php } ?>
</div>
</div>

Install Opencart store in subdirectory with a Login in the root folder

hope all is well. I am trying to install Opencart (2.0.3) into a subdirectory (Ie. www.website.com/shop/) I want the root URL www.website.com to go to a Login page, where once a user logs in. It will redirect them to the /shop/ portion of the site and allow them to continue their business. I was wondering what the easiest way was to accomplish this. Would I install everything in the root folder, and then modify the .htaccess file along with the config files? Then how would i Make the login files work in the root folder? I tried installing everything first into the subdirectory /shop/... but then I get issues trying to figure out how to get files in the root folder to work.
Thanks in advance!
Yes, need to work with ajax functionality as below. In the index.php insert the following code and replace URL_WITH_SHOP with your urlshop. Then I have taken "shop" as sub-folder installation if it is different then replace "shop" with your sub-folder name:
<script src="shop/catalog/view/javascript/jquery/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="shop/catalog/view/javascript/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div class="container">
<div class="row">
<div id="content" class="col-sm-12 ">
<div class="row ">
<div class="col-sm-6" style="margin: 0px auto; float: none;">
<div class="well">
<h2>Returning Customer</h2>
<p><strong>I am a returning customer</strong></p>
<form method="post" enctype="multipart/form-data">
<div class="error"></div>
<div class="form-group">
<label class="control-label" for="input-email">E-Mail Address</label>
<input type="text" name="email" value="" placeholder="E-Mail Address" id="input-email" class="form-control" />
</div>
<div class="form-group">
<label class="control-label" for="input-password">Password</label>
<input type="password" name="password" value="" placeholder="Password" id="input-password" class="form-control" />
</div>
<button type="button" id="button-cart" data-loading-text="Checking login" class="btn btn-primary ">Login</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript"><!--
$('#button-cart').on('click', function() {
$.ajax({
url: 'shop/index.php?route=account/loginajax',
type: 'post',
data: $('input[type=\'text\'], input[type=\'password\']'),
dataType: 'json',
beforeSend: function() {
$('#button-cart').button('loading');
},
complete: function() {
$('#button-cart').button('reset');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
$('.error').after('<div class="alert alert-danger has-error">' + json['error'] + '</div>');
}
if (json['success']) {
$('.error').after('<div class="alert alert-success">' + json['success'] + '</div>');
window.location = "URL_WITH_SHOP";
}
}
});
});
//--></script>
Above is the presentation layer, now let's make the logical layer, go to shop/catalog/controller/account and create loginajax.php and paste following code:
<?php
class ControllerAccountLoginAjax extends Controller
{
private $error = array();
public function index()
{
$this->load->model('account/customer');
$json = array();
// Login override for admin users
if (!empty($this->request->get['token'])) {
$this->event->trigger('pre.customer.login');
$this->customer->logout();
$this->cart->clear();
unset($this->session->data['wishlist']);
unset($this->session->data['payment_address']);
unset($this->session->data['payment_method']);
unset($this->session->data['payment_methods']);
unset($this->session->data['shipping_address']);
unset($this->session->data['shipping_method']);
unset($this->session->data['shipping_methods']);
unset($this->session->data['comment']);
unset($this->session->data['order_id']);
unset($this->session->data['coupon']);
unset($this->session->data['reward']);
unset($this->session->data['voucher']);
unset($this->session->data['vouchers']);
$customer_info = $this->model_account_customer->getCustomerByToken($this->request->get['token']);
if ($customer_info && $this->customer->login($customer_info['email'], '', true)) {
// Default Addresses
$this->load->model('account/address');
if ($this->config->get('config_tax_customer') == 'payment') {
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
if ($this->config->get('config_tax_customer') == 'shipping') {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
$this->event->trigger('post.customer.login');
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
}
if ($this->customer->isLogged()) {
$this->response->redirect($this->url->link('account/account', '', 'SSL'));
}
if (!$json) {
$this->load->language('account/login');
$this->document->setTitle($this->language->get('heading_title'));
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
$json['success'] = "Successfully logging in! ";
unset($this->session->data['guest']);
// Default Shipping Address
$this->load->model('account/address');
if ($this->config->get('config_tax_customer') == 'payment') {
$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
if ($this->config->get('config_tax_customer') == 'shipping') {
$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
}
// Add to activity log
$this->load->model('account/activity');
$activity_data = array(
'customer_id' => $this->customer->getId(),
'name' => $this->customer->getFirstName() . ' ' . $this->customer->getLastName()
);
$this->model_account_activity->addActivity('login', $activity_data);
}
else{
$json['error'] = $this->language->get('error_login');
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/home')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_account'),
'href' => $this->url->link('account/account', '', 'SSL')
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_login'),
'href' => $this->url->link('account/login', '', 'SSL')
);
$data['heading_title'] = $this->language->get('heading_title');
$data['text_new_customer'] = $this->language->get('text_new_customer');
$data['text_register'] = $this->language->get('text_register');
$data['text_register_account'] = $this->language->get('text_register_account');
$data['text_returning_customer'] = $this->language->get('text_returning_customer');
$data['text_i_am_returning_customer'] = $this->language->get('text_i_am_returning_customer');
$data['text_forgotten'] = $this->language->get('text_forgotten');
$data['entry_email'] = $this->language->get('entry_email');
$data['entry_password'] = $this->language->get('entry_password');
$data['button_continue'] = $this->language->get('button_continue');
$data['button_login'] = $this->language->get('button_login');
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
$data['action'] = $this->url->link('account/login', '', 'SSL');
$data['register'] = $this->url->link('account/register', '', 'SSL');
$data['forgotten'] = $this->url->link('account/forgotten', '', 'SSL');
if (isset($this->session->data['success'])) {
$data['success'] = $this->session->data['success'];
unset($this->session->data['success']);
} else {
$data['success'] = '';
}
if (isset($this->request->post['email'])) {
$data['email'] = $this->request->post['email'];
} else {
$data['email'] = '';
}
if (isset($this->request->post['password'])) {
$data['password'] = $this->request->post['password'];
} else {
$data['password'] = '';
}
} else {
$json['error'] = $this->language->get('error_login');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
protected function validate() {
$this->event->trigger('pre.customer.login');
// Check how many login attempts have been made.
$login_info = $this->model_account_customer->getLoginAttempts($this->request->post['email']);
if ($login_info && ($login_info['total'] >= $this->config->get('config_login_attempts')) && strtotime('-1 hour') < strtotime($login_info['date_modified'])) {
$this->error['warning'] = $this->language->get('error_attempts');
}
// Check if customer has been approved.
$customer_info = $this->model_account_customer->getCustomerByEmail($this->request->post['email']);
if ($customer_info && !$customer_info['approved']) {
$this->error['warning'] = $this->language->get('error_approved');
}
if (!$this->error) {
if (!$this->customer->login($this->request->post['email'], $this->request->post['password'])) {
$this->error['warning'] = $this->language->get('error_login');
$this->model_account_customer->addLoginAttempt($this->request->post['email']);
} else {
$this->model_account_customer->deleteLoginAttempts($this->request->post['email']);
$this->event->trigger('post.customer.login');
}
}
return !$this->error;
}
}
This will help you.
Download files and folders for above codes
Hope it also help you
If you just want the login page then here is the tricks, create index.php or index.html at root folder then paste the following code and change URL_WITH_SHOP in the code with your url with shop like "http://www.example.com/shop" :
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div class="container">
<div class="row">
<div id="content" class="col-sm-12 ">
<div class="row ">
<div class="col-sm-6" style="margin: 0px auto; float: none;">
<div class="well">
<h2>Returning Customer</h2>
<p><strong>I am a returning customer</strong></p>
<form action="URL_WITH_SHOP/index.php?route=account/login" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="control-label" for="input-email">E-Mail Address</label>
<input type="text" name="email" value="" placeholder="E-Mail Address" id="input-email" class="form-control" />
</div>
<div class="form-group">
<label class="control-label" for="input-password">Password</label>
<input type="password" name="password" value="" placeholder="Password" id="input-password" class="form-control" />
</div>
<input type="submit" value="Login" class="btn btn-primary" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
The issue will be if the customer enters wrong username and password then it redirects to the actual login page.

amazon turk, submit is not working

I've created an amazon Turk HIT.
after submitting the HIT. we are always getting emails from people telling us the submit is not working...
honestly, I don't know what I'm doing wrong.
form inside my HTML:
<form name='mturk_form' method='post' id='mturk_form' action='https://www.mturk.com/mturk/externalSubmit'>
<div class="inputs">
<label class="input-green"><input name="EXISTS" type="radio" value="YES" id="ckeck-yes">YES</label>
<label class="input-red"> <input name="EXISTS" type="radio" value="NO" id="ckeck-no">NO</label>
</div>
<input type="hidden" name="IMG_ID" value="${Img_ind}">
<input type="hidden" id="assignment_id" name="assignmentId" value=""/>
<p class="text-center"><input type="submit" id="submitButton" class="btn btn-primary" value="Submit"></p>
</form>
Javascript:
<script type='text/javascript'>
var checkedYes = document.getElementById('ckeck-yes');
var checkedNo = document.getElementById('ckeck-no');
window.onload = function() {
var submitButtons = document.getElementById('submitButton');
// Get the Assignment ID, which will be added to your URL by Mechanical Turk.
var assignment_id = location.search.match(/assignmentId=(\w+)/)[1];
document.getElementById("assignment_id").value = assignment_id;
// Assignment ID "ASSIGNMENT_ID_NOT_AVAILABLE" of indicates preview mode. Warn worker.
if( assignment_id == "ASSIGNMENT_ID_NOT_AVAILABLE" ) {
submitButtons.disabled = true;
document.getElementById("click_accept_warning").style.display = "block";
}
// Get the Submit URL, which will be added to your URL by Mechanical Turk. */
var submit_to_url_base = (location.search.match(/turkSubmitTo=([^=&]+)/)||[])[1];
if(submit_to_url_base) {
document.getElementById("mturk_form").action = submit_to_url_base + "/mturk/externalSubmit";
}
if(submitButtons) {
submitButtons.setAttribute('onclick', 'return validateForm()');
}
};
function validateForm() {
if(checkedYes.checked == false && checkedNo.checked == false) {
alert("Please select the most matching result!");
return false;
}
return true;
}
</script>
What I'm missing?
the problem was amazon turk replace my http:// WITH http%3A%2F%2F
so i created a new hit, inspect the new HIT javascript and copied 2 javascript function from amazon example.
function decode(strToDecode) {
var encoded = strToDecode;
return unescape(encoded.replace(/\+/g, " "));
};
function turkGetSubmitToHost() {
return decode(turkGetParam("turkSubmitTo", "https://www.mturk.com"));
};
var form = document.getElementById("mturk_form");
if (form) {
form.action = turkGetSubmitToHost() + "/mturk/externalSubmit";
}
thank you