Simple jQuery and PHP login issue - javascript

Hello I am trying to implement a simple login feature using jQuery and PHP however the login keeps failing and I cannot figure out why.
This is the PHP function that deals with the login
function login()
{
$return = array(
'success' => false
);
if ($users[$_POST['login']] == $_POST['password']) {
$return = array(
'success' => true
);
$_SESSION['loggedIn'] = true;
}
print(json_encode($return));
}
The username is declared in a different PHP file and is declared like so.
$users['admin'] = '123654';
The following jQuery code should do the loging in.
$(self).on('click', '.loginSubmitButton', function() {
var username = $('#username').val().trim();
var password = $('#password').val().trim();
$.post(settings.server, {
login: username,
password: password
}, function(data) {
if (data.success == true) {
}
else {
alert('Wrong username or password!')
}
});
});
So far it doesnt implement anything in case of success because everytime I try to run this code and I enter the login credentials I get the Wrong username or password! alert.

You need to make the following changes to two sections:
PHP - add $users to function() like function($users) or add global as so:
function login()
{
global $users;
$return = array(
'success' => false
);
if ($users[$_POST['login']] == $_POST['password']) {
$return = array(
'success' => true
);
$_SESSION['loggedIn'] = true;
}
print(json_encode($return));
}
jQuery - As you are returning a JSON encoded string you need to parse it into jQuery:
$(self).on('click', '.loginSubmitButton', function() {
var username = $('#username').val().trim();
var password = $('#password').val().trim();
$.post(settings.server, {
login: username,
password: password
}, function(data) {
var data = JSON.parse(data);
if (data.success == true) {
}
else {
alert('Wrong username or password!')
}
});
});

Related

Add Ajax Add To Cart Button to Front Page

I'm trying to add ajax to add to cart button on front page.
The setup is using Divi. Divi's woo product module does not display Add-to-cart button. I use the below to display add-to-cart button on front page. That works but the only issue is the Ajax is not working on front page. I've enabled "Enable AJAX add to basket buttons on archives" from Woocommerce settings.
add_action('template_redirect', 'work_only_on_front_page', 10);
function work_only_on_front_page(){
if ( is_front_page() ) {
add_action('woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_add_to_cart', 10);
}
}
Below works well on other pages other than the front page.
(function ($) {
$(document).on('click', '.single_add_to_cart_button', function (e) {
e.preventDefault();
var $thisbutton = $(this),
$form = $thisbutton.closest('form.cart'),
id = $thisbutton.val(),
product_qty = $form.find('input[name=quantity]').val() || 1,
product_id = $form.find('input[name=product_id]').val() || id,
variation_id = $form.find('input[name=variation_id]').val() || 0;
var data = {
action: 'woocommerce_ajax_add_to_cart',
product_id: product_id,
product_sku: '',
quantity: product_qty,
variation_id: variation_id,
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.ajax_url,
data: data,
beforeSend: function (response) {
$thisbutton.removeClass('added').addClass('loading');
},
complete: function (response) {
$thisbutton.addClass('added').removeClass('loading');
},
success: function (response) {
if (response.error && response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, $thisbutton]);
}
},
});
return false;
});
})(jQuery);
function woocommerce_ajax_add_to_cart_js() {
if (is_product() || is_product_category() || is_shop() || is_front_page()) {
wp_enqueue_script('woocommerce-ajax-add-to-cart', get_stylesheet_directory_uri() . '/assets/js/ajax-add-to-cart.js', array('jquery'), '', true);
}
}
add_action('wp_enqueue_scripts', 'woocommerce_ajax_add_to_cart_js', 99);
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
function woocommerce_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$variation_id = absint($_POST['variation_id']);
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
Another thing to check is to ensure that the function woocommerce_ajax_add_to_cart_js() is being called and the script is being enqueued on the front page.
You can check the browser's console to see if there are any errors related to the Javascript code not being loaded.

Hello, how can i add another user login pass to my code?

I am trying to add another user and I am experimenting with this code showed all around the internet.
So I tried this example below, it works fine, but how could I add another user, let's say for a guest?
is it possible? with like a conditional?
I am just trying to learn more about js and how I can solve this type of simple thing.
methods: {
login() {
if(this.input.username == "admin1" && this.input.password == "pass1") {
this.$store.commit("setAuthentication", true);
this.$router.replace({ name: "secure" });
} else {
console.log("The username and / or password is incorrect");
}
}
}
You Can use Below Code:
methods: {
login() {
if(this.input.username == "admin1" && this.input.password == "pass1") {
this.$store.commit("setAuthentication", true);
this.$router.replace({ name: "secure" });
} else if (this.input.username == "guest" && this.input.password == "guest1") {
// block of code to be executed if the condition1 is false and condition2 is true
}else {
console.log("The username and / or password is incorrect");
}
}
}

How to generate a token from a username and password in website

I have a login feature as follows:
$("#Wraper").on("click.Authenticate", '#btnLogin',btnLogin_onClick);
btnLogin_onClick: function (event) {
if (event)
event.preventDefault();
if ($(event.currentTarget).attr('id') == "btnLogin_Mobile") {
$('#txtLogin').val($('#username_mobile').val());
$('#txtPassword').val($('#password_mobile').val());
}
var username = $('#txtLogin').val(), password = $('#txtPassword').val(); // username=test password=password
//how do i create a token here
if (!username || !password) {
$("<div>Please enter user name and password</div>").dialog({
position: 'centre',
modal: true,
resizable: false,
title: "Error",
buttons: { "Okay": function () { $(this).dialog("close"); } }
});
return;
}
so the above gets my username and password.
How do i generate a token that encrypts the username and password and return that token?
for example i get the following string username=test;password=password encrypt this string to give me the following token=vZyQ4Ng+WElqWSkUzjqZhjGuxadZB+iUbVldtWE+2rk=
The token is to be passed into a URL.

Javascript validation - Check if a string is a correct object

I have a textarea where I need to put an object like that
[{
name: 'digitrust',
params: {
init: {
member: 'example_member_id',
site: 'example_site_id'
},
callback: function(digiTrustResult) {
if (digiTrustResult.success) {
var el = document.getElementById('dtidOutput');
console.log('Success', digiTrustResult.identity)
} else {
console.error('Digitrust init failed')
}
}
},
storage: {
type: 'html5',
name: 'pbjsdigitrust',
expires: 60
}
}]
I save this string in a mysql db and after I print it in a javascript object with php (laravel)
#if(!empty($useridobj))
try {
useridobj = {!! $useridobj !!};
if(typeof useridobj != 'object'){
useridobj = '';
}
} catch(err) {
useridobj = ''
}
#endif
If I put a correct obj in this textarea all works fine. But if I put something wrong like that
[{name:'digitrust',para]
console return an error.
So I'd like to validate the field first, in javascript (angular.js). I try something like that
if(!eval("var this_useridobj = "+ this.form.get("useridobj").value)){
this.form.get("useridobj").setErrors({ server: "UserId Object is not an object!" });
console.warn(this.form.get("useridobj"));
return false;
}
It doesn't work. Someone can help me please?
Thank u
Maybe you should validate in server side, eval or Function in the example above have some security issues, see this. Here you have a possible approach, but that Function executes anything:
document.getElementById("validate").addEventListener("click",()=>{
const json = document.getElementById("json").value;
const valid = (()=>{
try {
return (typeof (Function("return "+json))() === 'object')?true:false;
}
catch(error) {
return false;
}})();
console.log(valid)
});
//Try alert("something") in the textarea
<textarea id="json">{prop:[1,2,3}</textarea>
<button id="validate">
validate
</button>

How to use Ajax to Validate email or username as unique in Laravel 5.2?

This is my UserController where I check if the username exist in the database and return a json message accordingly. What i want is an ajax request to post to this controller and to return a message to a HTML form if the username exist or doesn't exist in the database.
public function postSignUp(Request $request)
{
$this->validate($request, [
'first_name' => 'required|min:3|max:120',
'last_name' => 'required|min:3|max:120',
'username' => 'required|unique:users|min:6',
'email' => 'required|email|unique:users',
'password' => 'required|min:8',
'gender' => 'required',
'birthday' => 'required',
'country' => 'required',
'state' => 'required'
]);
$username = $request->input('username', '');
$user = User::where('username', $username)->first();
// if the user was found, this will be true;
// if the user wasn't found, $user will be null and this will be false
if ($user) {
return json_encode(false);
} else {
return json_encode(true);
}
I was hoping to get a little help with this issue since I been searching the web for hours trying to figure this out.
I am currently building a logging web app with laravel 5.2 but I can't figure out how to use Ajax to do my front end validation. I found the following code online and did a little modifications to meet my needs but nothing seems to be working.
I am trying to verify the username field as a unique field. In other words, if the username exist in the database i want to let my users know before they submit the form. Can anyone help?
<script>
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//register is the form id.
$("#register").validate({
rules: {
/*username is the name of the field
that I want to validate using ajax*/
username: {
required: true,
rangelength: [6, 15],
remote: {
url: "{{ url('App/Http/Controllers/UserController/postSignUp') }}",
type: "post"
}
}
},
errorClass: "has-danger",
validClass: "has-success",
//success: "valid",
highlight: function (element, errorClass) {
$(element).fadeOut(function () {
$(element).fadeIn();
});
$(element).closest(".form-group").addClass(errorClass);
},
unhighlight: function (element, errorClass) {
$(element).closest(".form-group").removeClass(errorClass);
},
errorPlacement: function (error, element) {
error.insertAfter(element);
}
});
});
</script>

Categories

Resources