livevalidation.js custom username check function - php

I am sure this is probably something simple that i am not doing. Running livevalidation.js jquery plugin (livevalidation.com). It provides for custom function callbacks. I am trying to check for username availability. The server side is working fine and I am getting the proper responses back in my data var...
Here is my JS:
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
if (data.status === 'notavailable')
{
Validation.fail('oops, not available.');
}
});
};
I am calling it using:
var username = new LiveValidation('username', { validMessage: curr_username + "is available!" });
username.add( Validate.Presence, { failureMessage: "Choose a username" });
username.add( Validate.Username, { failureMessage: "Username is not available." } );
The problem I am getting is:
Uncaught ReferenceError: Validation is not defined
If I put the Validation.fail() outside of my .post() function it works fine. So am pretty sure it is because it's not able to be referenced inside the .post() function.
I've tried using a callback function
if (data.status === 'notavailable')
{
status_not_available();
}
I get the same error.
I realize this is something probably extremely simple, but any help would be appreciated. Thank you in advance.

i am having the same issue.
Ive found the following, http://forum.jquery.com/topic/ajax-return-value-on-success-or-error-with-livevalidation but have not been able to get it working.
BUT YES! At this very moment i made som (crappy) javascript addon that made it behave, i think :)
This is what i use.
function check_avail(name, id, postUrl)
{
var dataVal = name+'='+$(id).val();
var isaccepted = ''
$(id).next('div').remove();
$(id).after("Undersøger om "+name+" er ledigt");
$.ajax({
url: postUrl,
cache: false,
type: 'post',
dataType: 'json',
data: dataVal,
async: false,
success: function(data) {
if( data.success == 'true' )
{
$('#'+name+'-availability').remove();
//return false;
isaccepted = false;
}
if( data.success == 'false' )
{
$('#'+name+'-availability').remove();
// name.destroy();
isaccepted = true;
}
}
});
if (isaccepted == false) {
return false;
} else{
return true
};
}
And
f1.add( Validate.Custom, { against: function() {
return check_avail( 'brugernavn', '#ft001', 'usernamecheck.asp' );
}, failureMessage: 'Brugernavnet er optaget' } );
Hope it helps you :)
The json query you can read about on the link in the begining :)
(I am not at all skilled at javascript, and the "isaccepted" solution could problalby be made a lot better)

try to change it from Validation.fail to Validate.fail
try wrapping it in another function and try putting your validateStatus(status) function both inside and outside your Validate.Username function. example below is inside
Validate.Username = function(value, paramsObj) {
var paramsObj = paramsObj || {};
var message = paramsObj.failureMessage || "Username is not available";
var isSuccess = true;
$.post("<?php echo fURL::getDomain(); ?>/ajax/username",
function(data) {
validateStatus(data.status);
});
function validateStatus(status){
if (status === 'notavailable'){
Validate.fail("not available");
}
}
};

Related

Ajax post does not give value to php file, post becomes get

I have this ajax function for login.
Edit: I just noticed that this server runs php7 while other server where the login does work uses php5. What has changed in php that this script doesn't work anymore?
Edit 2: Looks like the server request method isn't post but changed to get, why?
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅
var InName = $('#InName').val();
var InPass = $('#InPass').val();
alert(InName);
$.ajax({
type: "POST",
url: "./ajaxcall/login.php",
dataType: "json",
data: {InName:InName, InPass:InPass},
error: function (request, error) {
console.log(arguments);
alert("Inlog Can't do because: " + error);
},
success : function(data){
if (data.code == "200"){
$("#InErEr").html(data.msg);
//window.location.reload(true);
} else {
$("#InErEr").html(data.msg);
$('.lds-dual-ring').animate({opacity: 0}, 300);
}
}
});
On the alert(InName); I get the correct value of the username. But when I check in my php file $_POST['InName'] it is empty.
Part of php file
include('../config.php');
if(empty($_POST['InName'])) {
$Ierror = 'Username is required.';
}
if($_POST['InPass'] == '') {
$Ierror = 'Password is required.';
}
$username = $_POST['InName'];
$passwordL = $_POST['InPass'];
// count user in between //
if($Inlognumber_of_rows == 0) {
$Ierror = 'Username not found.';
} else {
// password check //
if(password_verify($salty_pass, $hashed_password)) {
} else {
$Ierror = 'Password incorrect.';
}
}
if ($Ierror == '') {
// do login //
} else {
$showerror = '<span style="color:#F00;">'.$Ierror.$username.$passwordL.$_POST['InName'].$_POST['InPass'].'</span>';
echo json_encode(['code'=>404, 'msg'=>$showerror]);
exit;
}
In the return message, $showerror I only get, Username not found, without the posted values. So the login is not working because of empty values? User is also present in the database of course. I also don't get the empty $_POST errors. So to cap up, in javascript I get the correct value for InName but not in php.
You are close but your error catch is not correct ... try this (Jquery):
var InName = 'something';
var InPass = 'morething';
$.post("./ajaxcall/login.php", {
InName: InName,
InPass: InPass
}, function(data, status) {
console.log(data, status);
}).done(function() {
alert("second success");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("finished");
});
on your php file just do print_r($_POST); and you will receive this in your console...:
Array
(
[InName] => something
[InPass] => morething
)
success
Basically you were trying to print the error where you should have consoled log the request.responeText...
A good trick to know if posts arrived to the php even if the console.log won't show is doing this in the php file:
<?php
print_r($_POST) ;
$newfile = fopen('newfile.txt','a');
fwrite($newfile,json_encode($_POST));
fclose($newfile);
This will print and also store on a local file the post data....
Solution: needed to remove the .php from url: "./ajaxcall/login.php", because I use pretty url htaccess.😅

calling php code with ajax results in an error

I'm trying to call some php code using ajax:
$(document).ready(function() {
$("#email_address").on("keypress", function() {
request = $.ajax({
url: '../verify_email.php',
data: {email: $("#email_address").val(),
submitted: true},
type: 'post'
});
request.done(function(response) {
//fooling around to see if this works
if(response) {
alert("valid email");
} else {
alert("invalid email");
}
});
request.error(function(response) {
alert("an error occurred");
});
});
});
However, the request.error function runs. I'm not too sure why. Here is the php code:
<?php
if(isset($_POST['submitted']) and isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo 'true';
} else {
echo 'false';
}
}
?>
Thanks in advance.
ugh, noob mistake. i had set the php url to be relative to the .js file instead of to the web page. it was supposed to be:
request = $.ajax({
url: 'verify_email.php'
instead of
request = $.ajax({
url: '../verify_email.php',
i figured it out with the use of Chrome's web inspector . i learned two new things today: what the url has to be relative to and how to use Chrome's web inspector. thanks all for your help
If your url work fine, in php try to return json ;)
<?php
$return = false;
if(isset($_POST['submitted']) and isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$return = true;
} else {
$return = false;
}
}
header('Content-Type: application/json');
echo json_encode(array('result' => $return));
die;
?>
And in javascript try:
request.done(function(response) {
//fooling around to see if this works
if(response.result) {
alert("valid email");
} else {
alert("invalid email");
}
});

Problems sending array of favorites to a view in PHP via AJAX

I would like to know the best way to send this array of favorites to php, Im trying to use ajax, but I keep getting a 403 forbidden error. The path is correct, I must be doing something wrong here, any help would be greatly appreciated.
$(function(){
var favorite = localStorage.getItem( 'favorite' );
if (favorite !== null){
favorite = JSON.parse(favorite) || [];
}
$('.favorites' ).each(function() {
var petid = $(this).attr('data-petid');
if(favorite.indexOf(petid) !== -1){
$(this).css('background-image', 'url(../assets/img/heart-red.svg)');
$(this).css('background-color', '#fefefe');
}
});
// This function changes the color of the heart on the landing page and stores the values into local storage
$(".favorites").click(function() {
var favorite = localStorage.getItem( 'favorite' );
var petid = $(this).attr('data-petid');
var index;
favorite = JSON.parse(favorite) || [];
if ((index = favorite.indexOf(petid)) === -1) {
favorite.push(petid);
$(this).css('background-image', 'url(../assets/img/heart-red.svg)');
$(this).css('background-color', '#fefefe');
}else {
$(this).css('background-image', 'url(../assets/img/heart-full.svg)');
$(this).css('background-color', '#25aae3');
favorite.splice(index, 1);
}
localStorage.setItem('favorite', JSON.stringify(favorite) );
$.ajax({
type: "POST",
url: '/petlist/fuel/app/views/site/favorites.php',
data: favorite,
success: function(response){
console.log(response);
}
});
});
});
For ajax calls in Fuel, use a controller that extends Controller_Rest
Your ajax request should look like this.
$.post('/petlist/fuel/app/views/site/favorites.php', { "favorite" : favorite }, function(data) {
console.log(data);
});
Then in PHP, you can access the data via
print_r($_POST['favorite']);

my jquery code is not working code igniter

this is my javascript code ...i have written a function in my controller in which if false is return then i am echoing the 'userNo' other wise echo the json .. here is my javascript in which only else part is working not if part ... i have checked in firebug also .. i am getting a response "userNo" but dont know why it is not running the first part
<script type="text/javascript">
$(document).ready(function(){
$('#hide').hide();
$('#bill_no').blur(function(){
if( $('#bill_no').val().length >= 3 )
{
var bill_no = $('#bill_no').val();
getResult(bill_no);
}
return false;
})
function getResult(billno){
var baseurl = $('.hiddenUrl').val();
$('.check').addClass('preloader');
$.ajax({
url : baseurl + 'returnFromCustomer_Controller/checkBillNo/' + billno,
cache : false,
dataType: 'json',
success : function(response){
$('.check').removeClass('preloader');
if (response == "userNo") //this part is not working
alert("true");
else
$('.check').removeClass('userNo').addClass('userOk');
// $(".text").html(response.result);
$('#hide').show();
$(".text1").html(response.result1);
$(".text2").html(response.result2);
$(".text3").html(response.result3);
}
})
}
})
</script>
my Controller
function checkBillNo($billno)
{
$this->load->model('returnModel');
$query = $this->returnModel->checkBillNo($billno);
//$billno = $this->uri->segment(3);
$billno_results = $this->returnModel->sale($billno);
if (!$billno_results){
echo "userNo";
}else{
echo json_encode($billno_results);
}
}
Instead of echo "userNO", try to use it:
echo json_encode(array('return' => 'userNo'));
... and in your JS, use this:
if (response.return == "userNo") { // ...

Jquery and ajax, my function for username checking?

I have written this ajax request for username checking...
function check_username() {
var username = $("#username").val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: $('#username').val(),
}, function (response) {
$('.error, .success').hide();
setTimeout(function () {
$('.loading').hide();
finishAjax('username', response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#' + id).after(response).fadeIn(1000);
}
It all works fine just a couple of questions,
Can this code be improved in any way, this is the first ever one I have wrote so I wouldn't know.
Is there a way to make this a function for all my ajax requests rather than just username checking, so it can be used for email checking and such too. I am not sure on how to make a function like that would I have to pass variables on my onblur event which is attached to my form, at the minute it looks like this.
Is there a way to stop the ajax from running if the same error is there as previous, ie, string length should be over 3, so someone inputs AJ, and the error message 'must be over 3 characters' comes up, it the user then triggers the onblur event again, with the value of AJ, or CG, then the same error comes up, triggering a script that is useless and using memory.
Is there a way to make the ajax request with every character the user enters?
My ajax php is as follows...
<?php
require('dbc.php');
if (isset($_REQUEST['username'])) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
?>
To answer 1 & 2. I would turn it into a plugin and do something along these lines.
$.fn.checkValid = function(options)
{
var response = function(response) {
var setClass = '';
var $span = $(this).data('checkValidTip');
if ($span)
{
$span.remove();
}
if (response === undefined) return;
setClass = (response.valid ? 'valid' : 'invalid');
var $span = $('<span>' + response.msg + '</span>');
$(this)
.data('checkValidTip', $span)
.after($span);
$span.hide()
.fadeIn(1000)[0]
.className = setClass;
};
var ajaxOptions = {
type: 'GET',
url: 'ajax.php',
success: response,
dataType: 'json'
};
this.each(function() {
var that = this;
var ajaxRequest = ajaxOptions;
ajaxRequest.data = {};
ajaxRequest.data[options.key] = this.value;
ajaxRequest.context = that
$.ajax(ajaxRequest);
});
};
Usage
$('#username, #email').blur(function() {
$(this).checkValid({ key: this.id });
});
PHP changes
You should make your PHP function return a JSON, instead of HTML i.e.
<?php
// Do your sql statements here, decide if input is valid or not
$arr = array('valid' => $is_valid,
'msg' => $error_or_good_msg
);
echo json_encode($arr);
/* For example will output:
{
"valid": "false",
"msg": "<b>Error: Must be at least 2 characters</b>"
}
Which can be read directly as response.valid
or response.msg from within response() function
*/
To answer question 3: short answer is no. For this to work, you should have basic validation in JS. The best option would be to use a plugin that uses objects for validation parameters, that way you can output your validation requirements dynamically from your database, from within PHP using json_encode i.e. your output format would be:
var validations = {
username: {
min_chars: 4,
max_chars: 10,
valid_chars: 'qwertyuiopasdfghjklzxcvbnm_-'
},
email: {
regex: /./ //your magic regex here
}
};
jsFiddle
http://jsfiddle.net/sqZfp/2/
To answer 4, just change the event as above from .blur to .keyup should do the trick.

Categories