Jquery checking that passwords match with php + Json - php

I have a form that I am validating with JS and PHP. Everything is going well so far apart from when I try to check if the passwords match.
Here is the form:
<div>
<label for="passlength">Password, valid: 0-9</label>
<input type="text" name="passlength" value="<?=#$_REQUEST['passlength']?>" id="passlength" />
<span id="validatePasslength"><?php if ($error) { echo $error['msg']; } ?></span>
</div>
<div>
<label for="passlength">Password2, valid: 0-9</label>
<input type="text" name="passlength2" value="<?=#$_REQUEST['passlength2']?>" id="passlength2" />
<span id="validatePasslength2"><?php if ($error) { echo $error['msg']; } ?></span>
</div>
This is the Javascript:
var r = $('#passlength').val()
;
var validatePasslength2 = $('#validatePasslength2');
$('#passlength2').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validatePasslength2.removeClass('error').html('<img src="../../images/layout/busy.gif" height="16" width="16" /> checking availability...');
this.timer = setTimeout(function () {
$.ajax({
url: 'ajax-validation.php',
data: 'action=check_passlength2&passlength=' + r + '&passlength2=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validatePasslength2.html(j.msg);
}
});
}, 200);
this.lastValue = this.value;
}
});
Here is the php:
//Check for passlength
if (#$_REQUEST['action'] == 'check_passlength' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
// means it was requested via Ajax
echo json_encode(check_passlength($_REQUEST['passlength']));
exit; // only print out the json version of the response
}
function check_passlength($password) {
// global $taken_usernames, $usersql;
$resp = array();
// $password = trim($password);
if (!preg_match('/^[0-9]{1,30}$/', $password)) {
$resp = array("ok" => false, "msg" => "0-9 Only");
} else if (preg_match('/^[0-9]{1,2}$/', $password)) {
$resp = array("ok" => false, "msg" => "Password too short");
} else if (preg_match('/^[0-9]{6,30}$/', $password)) {
$resp = array("ok" => false, "msg" => "Password too long");
} else {
$resp = array("ok" => true, "msg" => "Password ok");
}
return $resp;
}
//Check for passlength2
if (#$_REQUEST['action'] == 'check_passlength2' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
// means it was requested via Ajax
echo json_encode(check_passlength2($_REQUEST['passlength'],$_REQUEST['passlength2']));
exit; // only print out the json version of the response
}
function check_passlength2($password,$password2) {
// global $taken_usernames, $usersql;
$resp = array();
// $password = trim($password);
if (!preg_match('/^[0-9]{1,30}$/', $password2)) {
$resp = array("ok" => false, "msg" => "0-9 Only");
} else if (preg_match('/^[0-9]{1,2}$/', $password2)) {
$resp = array("ok" => false, "msg" => "Password too short");
} else if (preg_match('/^[0-9]{6,30}$/', $password2)) {
$resp = array("ok" => false, "msg" => "Password too long");
} else if ($password !== $password2) {
$resp = array("ok" => false, "msg" => "Passwords do not match");
} else {
$resp = array("ok" => true, "msg" => "Password ok");
}
return $resp;
}
I am pretty sure it is an issue with the javascript because if I set var r = 1234; It works. Any ideas??

You just want to see if the passwords match, and are between a min and max length? Isn't the above overkill? Am I missing something?
You could use js alone to check the length of the first password field, then in the onblur event of the second field, check to see if field1==field2.
Minor thing I noticed, the label for the second field has the wrong "for" attribute.

Related

Unexpected token s in JSON at position 0

I am using ajax to get texts from an input field and check them through php than store them in the database...But somewhere on the line, something is wrong and I am getting Unexpected token s in JSON at position 0 this error...
$(".d-f-sub").on('click',function(e){
e.preventDefault();
resetErrors();
$('.inputTxtError').children('form input').css({'border-color' : '','box-shadow' : ''});
var data = {};
$.each($('form input, form select'), function(i, v) {
if (v.type !== 'submit') {
data[v.name] = v.value;
}
});
$.ajax({
dataType: "JSON",
type: "POST",
data: data,
cache: false,
url: "/ajax/diet/diet-page-error-display.php",
success: function(result){
if(result === "true"){
console.log('raboti do tuk');
$(".d-f-sub").submit();
window.location = "http://www.homepage.co.uk/thankyou";
return false;
}else {
console.log('ne raboti');
$.each(result, function(i, v) {
//console.log(i + " => " + v); // view in console for error messages
var msg = '<label class="diet-error" for="'+i+'" style="background:red;">'+v+'</label>';
$('input[name="' + i + '"], select[name="' + i + '"]').css({'border-color' : '#cc0000','box-shadow' : '0 0 10px #cc0000'}).closest('div').addClass('inputTxtError').after(msg);
});
var keys = Object.keys(result);
$('input[name="'+keys[0]+'"]').focus();
}
return false;
},
error: function(jqXHR, textStatus, errorThrown) {
//console.log(JSON.stringify(result));
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
});
function resetErrors() {
$('form input, form select').removeClass('inputTxtError');
$('label.diet-error').remove();
}
});
<?php
header('Content-type:application/json;charset=utf-8');
if(isset($_POST)){
if (filter_var($_POST['age'], FILTER_VALIDATE_INT) === false){
$_SESSION['errors']['age'] = 'Моля използвайте само цифри в полето за Вашата възраст!';
}
if (filter_var($_POST['height'], FILTER_VALIDATE_INT) === false){
$_SESSION['errors']['height'] = 'Моля използвайте само цифри в полето за Вашата височина!';
}
if (filter_var($_POST['weight'], FILTER_VALIDATE_INT) === false){
$_SESSION['errors']['weight'] = 'Моля използвайте само цифри в полето за Вашато тегло!';
}
if (filter_var($_POST['budget'], FILTER_VALIDATE_INT) === false){
$_SESSION['errors']['budget'] = 'Моля използвайте само цифри в полето за Вашият бюджет!';
}
if (filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) === false){
$_SESSION['errors']['email'] = 'Моля въведете валиден имейл адрес!';
}
if(empty($_POST['email'])){
$_SESSION['errors']['email'] = 'Моля въведете имейл за връзка';
}
if(empty($_POST['age'])){
$_SESSION['errors']['age'] = 'Моля въведете Вашата възраст!';
}
if(empty($_POST['height'])){
$_SESSION['errors']['height'] = 'Моля въведете Вашата височина!';
}
if(empty($_POST['weight'])){
$_SESSION['errors']['weight'] = 'Моля въведете Вашето тегло!';
}
if(!isset($_POST['sex'])){
$_SESSION['errors']['sex'] = 'Моля изберете пол !';
}
if(!isset($_POST['activity'])){
$_SESSION['errors']['activity'] = 'Моля изберете активност! !';
}
if(!isset($_POST['goal'])){
$_SESSION['errors']['goal'] = 'Моля изберете цел !';
}
}//
if(count($_SESSION['errors']) > 0){
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
echo json_encode($_SESSION['errors']);
unset($_SESSION['errors']);
exit();
}
echo "<ul>";
foreach($_SESSION['errors'] as $key => $value){
echo "<li>" . $value . "</li>";
}
echo "</ul>";
unset($_SESSION['errors']);
exit();
}else{
$age = clean_xss_int($_POST['age']);
$height = clean_xss_int($_POST['height']);
$weight = clean_xss_int($_POST['weight']);
$email = clean_xss($_POST['email']);
$sex = clean_xss($_POST['sex']);
$activity = clean_xss($_POST['activity']);
$goal = clean_xss($_POST['goal']);
$diseases = clean_xss($_POST['diseases']);
$liked_foods = clean_xss($_POST['liked_foods']);
$hated_foods = clean_xss($_POST['hated_foods']);
$budget = clean_xss_int($_POST['budget']);
$intership = clean_xss($_POST['training']);
$description = clean_xss($_POST['eat_usually']);
$data = array(
'age' => $age,
'height' => $height,
'weight' => $weight,
'email' => $email,
'sex' => $sex,
'activity' => $activity,
'goal' => $goal,
'diseases' => $diseases,
'liked_foods' => $liked_foods,
'hated_foods' => $hated_foods,
'budget' => $budget,
'intership' => $intership,
'description' =>$description
);
//Here is the query usually
echo json_encode($data);
?>
No matter what I do it's always returning Unexpected token s in JSON at position 0.For now i have tried to remove DataType: "JSON" used Content-Type header, use json_encode() (there is the result from JSON encode)
Link to network response tab
Also tried utf8_encode() before json,but it require a string not array.
Thank you!
OK so i was on this error whole day, there is the solution which worked for me.
First i checked if JSON is valid in www.jsonlint.com and it was valid.
Second my clean_xss_int function was wrong, i was imploding the input value if it is array, so the end result was strings for number fields and arrays for text fields.
Third (because i am new to ajax) I checked the whole php side, and realized that even if there is empty field a.k.a must return error or return the data array ajax got it both for successful operation.Plus that there is no need to pass the $data array to json again,because i need it only for the insert query. So i wrote array which i am returning as success in ajax which is array('0' => 'true'); And i am making it string in ajax and checking if success is equal to string 'true'.There is how code looks like:
$.ajax({
type: "POST",
data: data,
dataType: "JSON",
url: "/ajax/diet/diet-page-error-display.php",
success: function(result){
JSON.stringify(result);// <---- new ;d
if(result == "true"){ <--- comparing with 2 x = instead of 3
$(".d-f-sub").submit();
window.location = "http://www.musclevale.com/diet";
return false;
}else {
$.each(result, function(i, v) {
var msg = '<label class="diet-error" for="'+i+'" style="background:red;">'+v+'</label>';
$('input[name="' + i + '"], select[name="' + i + '"]').css({'border-color' : '#cc0000','box-shadow' : '0 0 10px #cc0000'}).closest('div').addClass('inputTxtError').after(msg);
});
var keys = Object.keys(result);
$('input[name="'+keys[0]+'"]').focus();
}
return false;
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
});
<?php
$age = clean_xss_int($_POST['age']);
$height = clean_xss_int($_POST['height']);
$weight = clean_xss_int($_POST['weight']);
$email = clean_xss($_POST['email']);
$sex = clean_xss($_POST['sex']);
$activity = clean_xss($_POST['activity']);
$goal = clean_xss($_POST['goal']);
$diseases = clean_xss($_POST['diseases']);
$liked_foods = clean_xss($_POST['liked_foods']);
$hated_foods = clean_xss($_POST['hated_foods']);
$budget = clean_xss_int($_POST['budget']);
$intership = clean_xss($_POST['training']);
$description = clean_xss($_POST['eat_usually']);
$data = array(
'age' => $age,
'height' => $height,
'weight' => $weight,
'email' => $email,
'sex' => $sex,
'activity' => $activity,
'goal' => $goal,
'diseases' => $diseases,
'liked_foods' => $liked_foods,
'hated_foods' => $hated_foods,
'budget' => $budget,
'intership' => $intership,
'description' =>$description
);
$fields = implode(',',array_keys($data));
$values = '\'' . implode('\', \'', $data) . '\'';
$query = mysqli_query($connect,"INSERT INTO buyed_diets ($fields) VALUES ($values)");
echo json_encode(array('0' => 'true'));// <----new ;d
?>

CodeIgniter + jQuery Ajax runs error but successfully callback is called

My Codeigniter: (Do you think there is an error?)
public function KayitOl()
{
$data = array(
'kullaniciadi' => $this->input->post('kullaniciadi'),
'email' => $this->input->post('email'),
'sifre' => $this->input->post('sifre')
);
$kuladi = $this->input->post('kullaniciadi');
$sorgu = $this->db->query("SELECT * FROM uyeler WHERE kullaniciadi='".$kuladi."'");
if ($sorgu->num_rows() > 0)
{
$response_array['status'] = 'error';
echo json_encode($response_array);
}
else
{
$this->db->insert('uyeler',$data);
$response_array['status'] = 'success';
echo json_encode($response_array);
}
}
My jQuery Code: (Do you think there is an error?)
$(".submit").on("click", function(){
var kuladi = $("#kullaniciadi").val();
var email = $("#email").val();
var sifre = $("#sifre").val();
var confirm = $("#sifreonay").val();
var hata = $("#hata").val();
var checkbox = $("#checkbox").is(":checked");
var link = "http://tantunisiparis:8080/main/anasayfa/KayitOl";
var pattern = /^\b[A-Z0-9._%-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i;
if (!kuladi || !email || !sifre) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Boş bırakılan alanlar var!");
}
else if (!pattern.test(email)) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Lütfen geçerli bir e-mail giriniz!");
}
else if (!checkbox) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Kullanıcı Sözleşmesini Kabul Etmediniz.");
}
else if (sifre != confirm) {
$("p#hata").removeClass("hidden");
$("p#hata").html("Şifreler eşleşmiyor!");
}
else{
$.ajax({
type :"POST",
url :link,
data : $("#kayitform").serialize(),
success: function (data){
console.log(data.status);
alert("Success döndü");
},
error: function (data){
console.log(data.status);
alert("Error döndü");
}
});
}
});
Why I am having a problem like this?
Any answer attempts are appreciated. Any correct answers are doubly appreciated ;)
Thanks!
You need to set HTTP status code. So in case of error call this code in the controller $this->output->set_status_header(500);.
public function KayitOl()
{
$data = array(
'kullaniciadi' => $this->input->post('kullaniciadi'),
'email' => $this->input->post('email'),
'sifre' => $this->input->post('sifre')
);
$kuladi = $this->input->post('kullaniciadi');
$sorgu = $this->db->query("SELECT * FROM uyeler WHERE kullaniciadi='".$kuladi."'");
if ($sorgu->num_rows() > 0)
{
$response_array['status'] = 'error';
$this->output->set_status_header(500); // or any other code
echo json_encode($response_array);
}
else
{
$this->db->insert('uyeler',$data);
$response_array['status'] = 'success';
echo json_encode($response_array);
}
}
You can read more about output class in the docs http://www.codeigniter.com/userguide3/libraries/output.html
$.ajax({
type :"POST",
url :link,
data : $("#kayitform").serialize(),
success: function (data){
if(data.status == 'success'){
console.log(data.status);
alert("Success döndü");
}
if(data.status == 'error'){
console.log(data.status);
alert("Error döndü");
}
}
});
I thing, This code will work for you...

AngularJS and PHP's json_encode

I have a simple code here that uses json_encode and echo out the response in PHP. Here is my code:
app.js
$scope.login = function() {
var data = {
username: $scope.login.username,
password: $scope.login.password
};
$http.post('endpoints/login.php', data)
.success(function(response) {
if(response.success == "true") {
alert('nice');
} else {
alert('not nice');
}
})
.error(function(response) {
console.log(response);
});
};
login.php
$data = json_decode(file_get_contents("php://input"));
$stmt = $db->prepare('SELECT * FROM accounts WHERE username=? AND password=?');
$stmt->execute(array($data->username, $data->password));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row > 0)
{
$response = [
"success" => true
];
echo json_encode($response);
}
else
{
$response = [
"success" => false
];
echo json_encode($response);
}
It works perfectly but this part doesn't work:
if(response.success == "true") {
alert('nice');
} else {
alert('not nice');
}
When I add console.log(response) I get Object {success: true} or Object {success: false}.
Am I missing something here? Thank you.
You need to use a boolean in your if statement, not a string because true != "true". Change your if statement to the following:
if(response.success === true) {

Ajax Call and Returned Response

I'm trying to add an address to a list in dotmailer (which for those not familiar is a service like mailchimp) I can get the address added but am struggling to get any sort of returned status via Ajax.
I've got the following in my form page in php
var emailEntered;
$(document).ready(function() {
$.fn.search = function() {
return this.focus(function() {
if( this.value == this.defaultValue ) {
this.value = "";
}
}).blur(function() {
if( !this.value.length ) {
this.value = this.defaultValue;
}
});
};
$("#email").search();
$("#sendButton").click(function() {
$(".error").hide();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
var emailaddressVal = $("#email").val();
if(emailaddressVal == '') {
$("#message").html('<span class="error">Enter your email address before submitting.</span>');
return false;
}
else if(!emailReg.test(emailaddressVal)) {
$("#message").html("<span class='error'>Please check your email address.</span>");
return false;
}
else {
emailEntered = escape($('#email').val());
}
});
$('#signup').submit(function() {
$("#message").html("<span class='error'>Adding your email address...</span>");
$.ajax({
url: 'dotmailerInput.php',
data: 'ajax=true&email=' + emailEntered,
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
<form id="signup" action="dotmailer.php" method="get">
<input type="email" name="email" id="email" class="textinput" value="Enter" />
<input type="submit" id="sendButton" name="submit" class="textinput" value="" />
</form>
<div id="message"> </div>
In the dotmailer.php page that it is referencing I've got the following. I can see it gives me a response "adding your email address" but nothing else after this and the email as I said gets added correctly.
$email = $_GET['email'];
$username = ""; //apiusername
$password = ""; //api password
$addressbookid = ;
$AudienceType = "Unknown";
$OptInType = "Unknown";
$EmailType = "Html";
try {
$client = new SoapClient("http://apiconnector.com/api.asmx?WSDL");
$contact = array("Email" => $email,"AudienceType" => $AudienceType, "OptInType" => $OptInType, "EmailType" => $EmailType, "ID" => -1);
$dotParams = array("username" => $username, "password" => $password, "contact" => $contact, "addressbookId" => $addressbookid);
$result = $client->AddContactToAddressBook($dotParams);
return "Success";
}
catch (Exception $e) {
return "Error";
}
Any helps or tips on what to look at or where to go next would be greatly appreciated.
Chris
Try echo instead of return because you are at the top level in PHP and will do output using this (instead of return gibing a function a value).
echo "Success";
}
catch (Exception $e) {
echo "Error";

Javascript Password Change Form Validation doesn't work on IE8

got this function to validate two fields from a changing password form and it's doesn't seem to work at IE8. FF, Opera, Safari and Chrome work.
function chk_form_pw()
{
if(document.getElementById('new_passwd').value == '')
{
alert("<?php _e('Please enter New Password') ?>");
document.getElementById('new_passwd').focus();
return false;
}
if(document.getElementById('new_passwd').value.length < 5 )
{
alert("<?php _e('Please enter New Password minimum 5 chars') ?>");
document.getElementById('new_passwd').focus();
return false;
}
if(document.getElementById('cnew_passwd').value == '')
{
alert("<?php _e('Please enter Confirm New Password') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
if(document.getElementById('cnew_passwd').value.length < 5 )
{
alert("<?php _e('Please enter Confirm New Password minimum 5 chars') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
if(document.getElementById('new_passwd').value != document.getElementById('cnew_passwd').value)
{
alert("<?php _e('New Password and Confirm New Password should be same') ?>");
document.getElementById('cnew_passwd').focus();
return false;
}
}
This is the form:
<form name="registerform" id="registerform" action="<?php echo get_option( 'siteurl' ).'/?page=account&chagepw=1'; ?>" method="post">
<p><label><?php _e('New Password'); ?> <span class="indicates">*</span></label></p>
<p><input type="password" name="new_passwd" id="new_passwd" class="lostpass_textfield" /></p>
<p><label><?php _e('Confirm New Password'); ?> <span class="indicates">*</span></label></p>
<p><input type="password" name="cnew_passwd" id="cnew_passwd" class="lostpass_textfield" /></p>
<p><input type="submit" name="Update" onclick="return chk_form_pw();" value="<?php _e('Update Password') ?>" class="btn grey"/></p>
</form>
And here is the chagepw=1 thing:
<?php
if($_POST)
{
if($_REQUEST['chagepw'])
{
$new_passwd = $_POST['new_passwd'];
if($new_passwd)
{
$user_id = $current_user->data->ID;
wp_set_password($new_passwd, $user_id);
$message1 = "Password Changed successfully.You need to sign back in.";
}
}else
{
$user_id = $userInfo['ID'];
$user_add1 = $_POST['user_add1'];
$user_add2 = $_POST['user_add2'];
$user_city = $_POST['user_city'];
$user_state = $_POST['user_state'];
$user_country = $_POST['user_country'];
$user_postalcode = $_POST['user_postalcode'];
$buser_add1 = $_POST['buser_add1'];
$buser_add2 = $_POST['buser_add2'];
$buser_city = $_POST['buser_city'];
$buser_state = $_POST['buser_state'];
$buser_country = $_POST['buser_country'];
$buser_postalcode = $_POST['buser_postalcode'];
$user_address_info = array(
"user_add1" => $user_add1,
"user_add2" => $user_add2,
"user_city" => $user_city,
"user_state" => $user_state,
"user_country" => $user_country,
"user_postalcode"=> $user_postalcode,
"buser_name" => $_POST['buser_fname'].' '.$_POST['buser_lname'],
"buser_add1" => $buser_add1,
"buser_add2" => $buser_add2,
"buser_city" => $buser_city,
"buser_state" => $buser_state,
"buser_country" => $buser_country,
"buser_postalcode"=> $buser_postalcode,
);
update_usermeta($user_id, 'user_address_info', serialize($user_address_info)); // User Address Information Here
$userName = $_POST['user_fname'].' '.$_POST['user_lname'];
$updateUsersql = "update $wpdb->users set user_nicename=\"$userName\", display_name=\"$userName\" where ID=\"$user_id\"";
$wpdb->query($updateUsersql);
$message = "Information Updated successfully.";
}
}
$userInfo = $General->getLoginUserInfo();
$user_address_info = unserialize(get_user_option('user_address_info', $user_id));
$user_add1 = $user_address_info['user_add1'];
$user_add2 = $user_address_info['user_add2'];
$user_city = $user_address_info['user_city'];
$user_state = $user_address_info['user_state'];
$user_country = $user_address_info['user_country'];
$user_postalcode = $user_address_info['user_postalcode'];
$display_name = $userInfo['display_name'];
$display_name_arr = explode(' ',$display_name);
$user_fname = $display_name_arr[0];
$user_lname = $display_name_arr[2];
$buser_add1 = $user_address_info['buser_add1'];
$buser_add2 = $user_address_info['buser_add2'];
$buser_city = $user_address_info['buser_city'];
$buser_state = $user_address_info['buser_state'];
$buser_country = $user_address_info['buser_country'];
$buser_postalcode = $user_address_info['buser_postalcode'];
$bdisplay_name = $user_address_info['buser_name'];
$display_name_arr = explode(' ',$bdisplay_name);
$buser_fname = $display_name_arr[0];
$buser_lname = $display_name_arr[2];
if($_SESSION['redirect_page'] == '')
{
$_SESSION['redirect_page'] = $_SERVER['HTTP_REFERER'];
}
if(strstr($_SESSION['redirect_page'],'page=checkout'))
{
$login_redirect_link = get_option( 'siteurl' ).'/?page=checkout';
}
?>
A smoother solution would be jQuery. There you can load a loading-animation, put color like red/green on wrong/correct and simplified print out text depending on what happening to the form.
Download jQuery from: http://docs.jquery.com/Downloading_jQuery
Then you insert it in the html code like this:
<script type="text/javascript" src="jquery.js">
</script>
Then you can have a valid.js like this:
$(document).ready(function () {
var validatefield = $('#validatefield');
$('#validatefield').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validatefield.html('<img src="images/Here_you_can_put_your_gif_animation"
alt="Loading..."
height="16" width="16"/>');
this.timer = setTimeout(function () {
$.ajax({
url: 'check_field.php',
data: 'action=check_field&field=' + encodeURIComponent(t.value),
dataType: 'json',
type: 'post',
success: function (j) {
if (j.ok) {
validatefield.html(j.msg);
}
else if ($("#validatefield").val() == "")
{
validatefield.html('');
}
else {
validatefield.html(j.msg);
}
}
});
}, 200);
this.lastValue = this.value;
}
});
});
Then in the check_field.php, have this;
echo json_encode(check_field($_POST['field']));
function check_field($field) {
$fieldSum = stripslashes(strip_tags(trim(htmlspecialchars($field))));
$response = array();
if (strlen($fieldSum) > 15) {
$response = array(
'ok' => false,
'msg' => "The field characters were over 15!");
}
else
{
$response = array(
'ok' => true,
'msg' => "Correct");
}
return $response;
}
The id #validatefield is an id inside the html code that you have to create in order to print things out.
Example:
<div id="validatefield">Here comes the text etc, from the valid.js</div>
Finally got it done using the JQuery script posted before:
http://code.google.com/p/form-validation-engine/downloads/list
It's been really easy to fit into my previous code and works flawlessly through every browser tested.
Thank you all for your help!

Categories