I've been trying to save some input to a DB using jquery. I'd like to prevent the user filling the DB with blank spaces. The code I've done so far doesn't allow to continue if the customer leaves the input box blank, which is ok. The thing is, if the customer hits the space bar more than once the record will be saved to the database. Bottom line is... I'd like to let the user keep going ONLY when he's written something into the input box. Sorry for my grammar. Hope you guys can understand. Thank you so much!
Here's the script I'm using ATM:
<script>
$(document).ready(function(){
$(function()
{
$('.btn-det').click(function(e)
{
e.preventDefault();
var name = $('#name').val();
var surname = $('#surname').val();
if (name === "" && surname === "")
{
alert("Please, enter your details!");
$("#userQuestion").hide();
}
else if(name != "" && surname === "")
{
alert("Please, enter your Surname");
$("#userQuestion").hide();
}
else if(name === "" && surname != "")
{
alert("Please, enter your Name");
$("#userQuestion").hide();
}
else {
$.post("saveDetails.php",
{
name: name,
surname: surname
});
$("#userDetails").hide(500);
$("#userQuestion").show(600);
}
});
});
});
</script>
I forgot to mention that, before saving to the DB, I have the following function which uses .trim() but it does not delete white space. It deletes only spaces at the begining and end of whatever the input is. Thanks again!
function test_input($data)
{
$data = trim($data);
$data = stripcslashes($data);
$data = htmlspecialchars($data);
return $data;
}
In javascript you can use the trim function on a string before sending the data :
var name = $('#name').val();
name = name.trim();
http://www.w3schools.com/jsref/jsref_trim_string.asp
This will remove the blank spaces before and after the string
In php you can do the same
$name = trim((string) $_POST['name']);
Just to be clear, TRIM by default only remove spaces (not all whitespaces). Here is the doc.
UPDATE FOO set FIELD2 = TRIM(FIELD2);
http://www.w3schools.com/jsref/jsref_trim_string.asp
If you need to use trim in select query, you can also use regular expressions
SELECT * FROM table_name WHERE field RLIKE ' * query-string *'
MySql Resouces
Another Example:
UPDATE student_surveys
SET favorite_activities =
TRIM(LEADING SPACE(1) FROM TRIM(TRAILING ',' FROM favorite_activities));
use following function
trim($data," \t")
this will remove whitespaces and tabs from the beginning and end of a string.
Have a look at
http://php.net/manual/en/function.trim.php
you have to give " " as second parameter which means that remove
whitespace (i.e " ") beginning and end of a string and "\t" means remove tab. Combining both (i.e " \t") means remove space and tab.
Ok guys. This is what I did. Instead of using just an "else", I used an "else if" with the condition that none of the input fields are blank, and trimmed those at the same time... Here's just the piece I edited:
Thanks a lot for your help!
if (name === "" && surname === "")
{
alert("Please, enter your details!");
$("#userQuestion").hide();
}
else if(name !== "" && surname === "")
{
alert("Please, enter your Surname");
$("#userQuestion").hide();
}
else if(name === "" && surname !== "")
{
alert("Please, enter your Name");
$("#userQuestion").hide();
}
//If there's any data saved into the variables, it deletes any leading and trailing white spaces//
else if($.trim(name) != "" && $.trim(surname) != "")
{
$.post("saveDetails.php",
{
name: name,
surname: surname
});
$("#userDetails").hide(500);
$("#userQuestion").show(600);
Again, thank you very much!
Related
I'm trying to create an AJAX script that calls a PHP script to check the entered username and password. The PHP script simply returns "true" if the entered details are correct and false if otherwise.
At the end of the AJAX script, I've placed a simple if else condition for true/false returns. Every time the PHP script returns true, the AJAX scripts jumps to else part overlooking the if.
I know there might be some stupid mistake or it is probably a ludicrous question but I'm stuck on it since many days. Stack is the last resort!
Here's my AJAX SCRIPT
function authenticate()
{
//XMLHttpRequest Object
var xhttp = new XMLHttpRequest();
var email = document.getElementById('email').value;
var pass = document.getElementById('pass').value;
var url = "php/user_authentication.php";
var url2 = "php/user_authentication.php?email=" + email + "&pass=" + pass;
var result = "";
xhttp.open("GET", url2, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
xhttp.onreadystatechange = function f()
//f() would be called everytime the onreadystatechange property changes the value
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
alert(this.responseText);
result = this.responseText;
if (result == "true")
//!! -> NOT ENTERING THIS PART EVEN WHEN result="true" !!
{
alert("Inside true");
document.getElementById('email_pass').innerHTML = 'login successful';
} else {
document.getElementById('email_pass').innerHTML = 'login failed';
alert("2 " + xhttp.responseText);
}
}
}
}
Here's the PHP script [user_authentication.php]
<?php
//User Authentication
//1.Including the database_connection.php
include "database_connection.php";
//2.1.Fetching the user id and password from the form
$email = $_GET['email'];
$pass = $_GET['pass'];
//2.2.Defining th select query
$qry = 'select * from user_auth where Email="'.$email.'" and Password = "'.$pass.'"';
//3.Executing the query and storing it to result
$result = mysqli_query($connection,$qry);
//authenticating
if(mysqli_num_rows($result)>0)
{
echo "true";
}
else
{
echo "false";
}
?>
Obligatory comment about prepared statements in php and sql PHP Manual.
But I would try to cast the comparison
if (result == "true")
to boolean like so
if (Boolean(result) === true)
I admit, my knowledge of ajax and JS is limited but in such cases Ive learned to not trust JS automatic type casting. Note also that I would definately use 3x= if we are casting result to a boolean.
The issue was,
I was getting some extra spaces along with my responseText that made the following condition false every time I got "true" in my responseText.
if (result == "true")
//Turns false because result.length = 11 (extra empty spaces due to some unknown reasons)
The solution was as follows :
Changing the return value in my PHP to 't' and 'f'
Using the slice method to slice the first variable of responseText to eliminate all the white-spaces in the string and then making further comparison
xhttp.onreadystatechange = function f()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
result = this.responseText;
var temp = result.slice(0,1);
//This will only select the first char in the result string
if (temp == "t")
document.getElementById('email_pass').innerHTML = 'login successful';
else
document.getElementById('email_pass').innerHTML = 'login failed';
}
}
$result not getting "true" make sure or double check below:
Html element IDs are (email, pass)
Database connection work properly,
$qry: select query related fields have matched with table columns
$result will get true only if requested email and password exits in database user_auth table
I think it may help...good luck
First, let me say that I've looked through other similar questions on this site and the jQuery documentation. So far I haven't found something that fixes my issue.
I'm trying to setup a login form for logging in using an email address and password. I have a PHP-only solution that works just fine, but I'm trying to add AJAX functionality as well.
The code I'm using now returns the whole page that's making the AJAX call. Just for some extra info, I'm using jQuery 1.10.2 and PHP 5.4.12. This is also my first time setting up a site to use a PHP script for deciding what other scripts to use based on what data is sent to it, so please bear with me.
Here's my form:
<form id="employee_login" name="employee_login" action="portal.php" method="post">
<input type="text" name="email" placeholder="Email address">
<input type="password" name="password" placeholder="Password">
<button id="login" type="submit" name="submit">Submit</button>
</form>
<div id="error_box">
<?php if(isset($GLOBALS['loginError']) && $GLOBALS['loginError'] != '') { ?>
<p class="error"><?php echo $GLOBALS['loginError']; ?></p>
<?php } ?>
</div>
Here's my AJAX function:
function ajaxValidate(email, pass, error) {
if($(email).val() == '' || $(pass).val() == '') {
$(error).html('<p class="error">You must enter your email address and password!</p>');
}
else {
$.ajax({
type: 'POST',
url: '/php-modules/ajax_filter.php',
dataType: 'text',
data: { emailAddr: $(email).val(), password: $(pass).val()},
success: function(text, textStatus, jqXHR)
{
console.log(Date() + ': ' + text);
try{
if( IsType(text, 'json') ) {
var ajaxData = $.parseJSON(text);
if(ajaxData['error'] != null && ajaxData['error'] != 'undefined')
$(error).html('<p class="error">' + ajaxData['error'] + '</p>');
else if(ajaxData['is_email'] != 1)
$(error).html('<p class="error">You must enter a <strong>VALID</strong> email address.</p>');
else if(ajaxData['is_email'] == 1)
document.location = jqXHR.getResponseHeader('Location');
else
$(error).html('<p class="error">You must enter your email address and password!</p>');
}
else if( IsType(text, 'html') ) $(error).html( $.parseHTML(text) );
else if( IsType(text, 'xml') ) alert('Data is XML.');
}
catch(e) {
$(error).html('<p class="error">' + e.description + '</p>');
console.debug(e);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$(error).html('<p class="error">' + jqXHR.status + ' ' + errorThrown + ' ' + jqXHR.responseText + '</p>');
}
});
}
}
The script I'm sending the AJAX call to is only setup for 1 request so far. I intend to add more later. I'm not sure if I've setup too many checks either, but I wanted to be safe since I'm not very familiar with something like this. And the "unidentified error" thing I added just today was a replacement for a "return false" that I thought could've been causing the problem. Here's the code:
<?php
// a filter for all AJAX requests
// for email checking
if( isset($_POST['emailAddr']) ) {
require_once('login.php');
if(isset($GLOBALS['loginError']) && $GLOBALS['loginError'] != '') {
echo '{"error":"' . $GLOBALS['loginError'] . '"}';
} else echo '{"error":"Unidentified error"}';
}
// if $_POST isn't set, isn't an array, or has a length less than 1, return an error
else if(!isset($_POST) || !is_array($_POST) || count($_POST) < 1) {
echo '{"error":"No data sent"}';
}
// if the previous check fails, invalid or insuficient data was sent
else {
echo '{"error":"Could not process request"}';
}
?>
The last piece is my login checking script. I've omitted the actual query and table fields because those parts work fine when using my PHP-only solution.
<?php
if($_SERVER['REQUEST_METHOD'] == "POST") {
// halt execution if the login fields are empty
if((!isset($_POST['emailAddr']) || $_POST['emailAddr'] == "") && (!isset($_POST['password']) || $_POST['password'] == "")) {
$GLOBALS['loginError'] = 'You must enter your email and password!';
}
else {// check for valid email
require_once('is_email.php');
if( !is_email($_POST['emailAddr']) ) $GLOBALS['loginError'] = 'You must enter a valid email address!';
else if($_POST['emailAddr'] != "" && $_POST['password'] != "") {
try{
// PDO setup
include('pdo.php');
$con = createPDO();
// PDO statement preparation and execution
$query = $con->prepare("[query code];");
$email = $_POST['emailAddr'];
$password = $_POST['password'];
// returned PDO query data
if($query->execute( array($email) ) ) {
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
if(strtolower($email) == strtolower($row['email']) && $password == $row['password']) {
// set session data
$_SESSION['user_id'] = $row['[id field]'];
$_SESSION['name'] = ucfirst($row['[name field]']);
$_SESSION['email'] = $row['[email field]'];
session_regenerate_id();
header("location: /");
}
else $GLOBALS['loginError'] = 'ID or password incorrect!';
}
}
} catch(Exception $e) {
$GLOBALS['loginError'] = $e->getMessage();
}
}
else $GLOBALS['loginError'] = 'You must enter your email and password!';
}
}
?>
I've cut out an unnecessary function and return false; lines, added the console.log(); method, changed the email: value name in the ajax data: option to emailAddr: (in my PHP code too) in case of a name conflict between it and my email variable, and changed my code to parse for HTML in case of PHP generating HTML error messages. My parentheses, braces, and brackets seem to be matched ok (I checked using Sublime Text's parenthesis/brace/bracket highlighting to check), the form checking portion of the script works fine.
I'm honestly at a loss...
Also, thanks to everyone who reads through this long-winded post.
Question updates:
I just realized that parsing code in the try is working correctly. Since the $.parseJSON doesn't work, it's skipping down to the if statement for parsing HTML and that one is working.
Code changes:
I replaced some return statements with echo, per Morganster.
When you are going to return data across an ajax call, you must print your data.
For example,
$var['error']="Could not process request";
echo json_encode($var);
The problem is fixed. Someone named Scott Sawyer said header("Location: /") would cause the $.ajax() method to return the whole current page. The redirect seems to be working now. Thanks for the input everyone.
I have this function, and I call it from PHP with onClick="login_f('.$return.')"
But in Firefox it gives me an error "javascript missing ) after argument list"
Any help?
function login_f(return_v){
email = document.login.email.value;
email2 = document.login.email2.value;
if(email == "" || email2 == ""){
if(readCookie("lang") == "it_IT")
msg('<span style="color:#D90909">Compila tutti i campi!</span>');
else
msg('<span style="color:#D90909">Fill in all fields!</span>');
}
else if(email != email2){
if(readCookie("lang") == "it_IT")
msg('<span style="color:#D90909">Le email non coincidono!</span>');
else
msg('<span style="color:#D90909">The emails do not match!</span>');
}
else{
var date = new Date();
date.setTime(date.getTime() + (365*24*60*60*1000));
var expires = "; expires=" + date.toGMTString();
document.cookie = "email=" + email + expires + "; path=/sbm/";
if(return_v == "" || return_v == null)
window.location.href = "http://www.xriuk.com/sbm/";
else
window.location.href = return_v;
}
}
It looks like (based on where it is used) $return (and therefore return_v) is a string.
If that's the case, then it needs quotes around it.
I highly recommend using json_encode to embed ANY kind of variable, not least because it greatly helps prevent XSS.
So your PHP becomes:
echo '...... onClick="login_f('.htmlspecialchars(json_encode($return),ENT_QUOTES)."');"....';
you could do like:
echo '<a ... onClick="login_f(\''.$return.'\')">....</a>';
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 8 years ago.
Below is my validation function of my registration form. Problem is if the user input all the correct data, how to I trigger my php function with SQL statement to insert it into my database?
<script type="text/javascript">
function validate(){
var school_name = document.formValidation.school_name.value;
var mailing_address = document.formValidation.mailing_address.value;
var city = document.formValidation.city.value;
var state = document.formValidation.state.value;
var postcode = document.getElementById('postcode');
var courier_address = document.formValidation.courier_address.value;
var courier_city = document.formValidation.courier_city.value;
var courier_state = document.formValidation.courier_state.value;
var courier_postcode = document.getElementById('courier_postcode');
var phonenumber = document.getElementById('phonenumber');
var faxnumber = document.getElementById('faxnumber');
var email = document.getElementById('email');
var website = document.formValidation.website.value;
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(school_name == "" || mailing_address == "" || city == "" || state == "" || postcode == "" || courier_address == "" || courier_city == "" || courier_state == "" || courier_postcode == "" || phonenumber == "" || faxnumber == "" || email == "" || website == ""){
alert("Please enter fields marked with an asterisk");
return false;
}
if (!/^[0-9]+$/.test(postcode.value)) {
alert("Please enter numbers only for postcode");
postcode.value = postcode.value.substring(0,postcode.value.length-1);
return false;
}
if (!/^[0-9]+$/.test(courier_postcode.value)) {
alert("Please enter numbers only for courier postcode");
courier_postcode.value = courier_postcode.value.substring(0,courier_postcode.value.length-1);
return false;
}
if (!filter.test(email.value)) {
alert("Please enter a valid email address");
email.focus;
return false;
}
else {
alert("Registration Success!");
<?php
?>
return true;
}
}
Javascript runs on the users' browsers. PHP runs on your server. You have to send that data to the server, validate it there as well, then insert into the database.
Next you need a POST or GET action to send the variables to your PHP script on the serverside (this JavaScript is executed on the clientside). JQuery offers some real good and handy functions for that: .post() and .get().
http://api.jquery.com/jQuery.post/
and
http://api.jquery.com/jQuery.get/
I'm working on a js form validation and so far I have this:
// grab form field values
var valid = '';
var name = $('form #name').val();
// perform error checking
if (name = '' || name.length <= 2) {
valid = '<p>Your name' + required +'</p>';
}
How can I validate that the user has chosen one of the options from a dropdown that I have in my form?
Thanks in advance.
$('select.foo').val();
check this
http://api.jquery.com/val/
if($('select.your-class-here').val() !== '') { //value select
} else { //nothing selected
}