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.
Related
The code should make a pop up window, asking for confirmation "press ok to confirm the action for user" but it doesn't. i'm all out of ideas.
function friendToggle(type,user,elem){
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
if(conf != true){
return false;
}
$(elem).innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "php_parsers/friend_system.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "friend_request_sent"){
$(elem).innerHTML = 'OK Friend Request Sent';
} else if(ajax.responseText == "unfriend_ok"){
$(elem).innerHTML = '<button onclick="friendToggle(\'friend\',\'<?php echo $u; ?>\',\'friendBtn\')">Request As Friend</button>';
} else {
alert(ajax.responseText);
$(elem).innerHTML = 'Try again later';
}
}
}
ajax.send("type="+type+"&user="+user);
}
</script>
PHP code:
<?php
$friend_button = '<button disabled>Request As Friend</button>';
$block_button = '<button disabled>Block User</button>';
// LOGIC FOR FRIEND BUTTON
if($isFriend == true){
$friend_button = '<button onclick="friendToggle(\'unfriend\',\''.$u.'\',\'friendBtn\')">Unfriend</button>';
}
else if($user_ok == true && $u != $log_username &&
$ownerBlockViewer == false){
$friend_button = '<button onclick="friendToggle(\'friend\',\''.$u.'\',\'friendBtn\')">Request As Friend</button>';
}
// LOGIC FOR BLOCK BUTTON
if($viewerBlockOwner == true){
$block_button = '<button onclick="blockToggle(\'unblock\',\''.$u.'\',\'blockBtn\')">Unblock User</button>';
} else if($user_ok == true && $u != $log_username){
$block_button = '<button onclick="blockToggle(\'block\',\''.$u.'\',\'blockBtn\')">Block User</button>';
}
?>
Opening up the console i see "Uncaught SyntaxError: Invalid or unexpected token"
The console issue is with lines 2 & 3 of your JavaScript code;
var conf = confirm("Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.");
You have a multi-line String which the console is not interpreting as one String value. In order to resolve, ECMAScript 6 (ES6) introduced template literals which can be utilized like below to handle multi-line Strings;
var conf = confirm(`Press OK to confirm the '"+type+"' action for user
<?php echo $u; ?>.`);
(i.e. use back-ticks rather than double quotes to start & end the multi-line String)
Or, if ES6 isn't supported you can use good old String concatenation like below;
var conf = confirm("Press OK to confirm the '"+type+"' action for user" +
"<?php echo $u; ?>.");
I've got myself a little script that checks the validity of a link supplied by the user, making it safe to store in the database (safer at least) and to confirm it's a link to facebook.
Now I want to roll this code out for another links, changing parameters as and when needed so that links to people user profile on these sites work, bit I dont want to copy and paste the code another 5 times and then try and adapt the Ajax to work with it, if theres a better way to approach this.
This is my code, it can been seen working at www.vwrx_project.co.uk/test.php. It hopefully only accepts facebook.com/(something here) .
link_checker.php
<?php
function check_url($dirty_url) {
//remove anything before facebook.com using strstr()
//clean url leaving alphanumerics : / . only - required to remove facebook link format with /#!/
$clean_url = strstr(preg_replace('#[^a-z0-9:/.?=]#i', '', $dirty_url), 'facebook.com');
$parsed_url = parse_url("http://www.".$clean_url); //parse url to get brakedown of components
$safe_host = $parsed_url['host']; // safe host direct from parse_url
// str_replace to switch any // to a / inside the returned path - required due to preg_replace process above
$safe_path = str_replace("//", "/", ($parsed_url['path']));
if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] != '' && $parsed_url['path'] != '/') {
echo "Facebook";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '') {
echo "missing_profile1";
} else if ($parsed_url['host'] == 'www.facebook.com' && $parsed_url['path'] == '/') {
echo "missing_profile2";
} else {
echo "invalid_url";
}
}
?>
Test.php
<?php
include_once ("includes/check_login_status.php");
include_once ("includes/link_checker.php");
// AJAX CALLS THIS LOGIN CODE TO EXECUTE
if(isset($_POST["L"])){
$dirty_url = $_POST["L"]; //user supplied link
//$dirty_url = "http://www.facebook.com/profile.php?id=4";
// if $dirty_url is blank
if($dirty_url == ""){
echo "no link supplied";
exit();
} else {
check_url($dirty_url);
}
exit();
}
?>
<html>
<head>
<title>testing</title>
<script type="text/javascript" src="js/main.js"></script>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function cleanURL(){
var user_url = _("user_link").value;
var func = _("hidden").value;
if(user_url == ""){
_("status").innerHTML = "Please provide a link before clicking submit";
} else {
_("submitbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "test.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "no link supplied"){
_("status").innerHTML = "Submitted blank form data.";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "invalid_url"){
_("status").innerHTML = "The url supplied is invalid";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile1"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else if(ajax.responseText == "missing_profile2"){
_("status").innerHTML = "Please supply a link to your profile";
_("submitbtn").style.display = "block";
} else{
_("status").innerHTML = ajax.responseText;
}
}
}
ajax.send("L="+user_url);
}
}
</script>
</head>
<body>
<p id="status"></p>
<form id="linkform" onSubmit="return false;">
<input type="text" id="user_link">
<input type="hidden" id="hidden" value="Facebook">
<button id="submitbtn" onClick="cleanURL()">Submit</button>
</form>
Why dont you add an additional parameter which is the website you want to allow?
function check_url($dirty_url, $websiteURL)
Then update your function to use the $websiteURL variable instead of the hardcoded 'facebook.com'
Then when you want to have several different urls you can do this
check_url($dirty_url, 'facebook.com');
or
check_url($dirty_url, 'twitter.com');
Or are you wanting to be able to check for multiple sites in the single function? such as facebook.com and twitter.com
this is changepassword.php file
<?php
include 'core/init.php';
if (empty($_POST) === false) {
if (md5($_POST['current_password']) === $user_data['password']) {
} else {
$errors[] = 'Your current psasword is incorrect';
}
}
if (empty($_POST) === false && empty($errors) === true) {
change_password($session_user_id, $_POST['password']);
} else if (empty($errors) === false) {
$error = output_errors($errors);
this variable
}
?>
this is the jQuery file
$('#save_pass').click(function(){
var current_password = $('#current').val();
var password = $('#new').val();
var password_again = $('#confirm').val();
if ((password == password_again) && (password.length >= 8)) {
$.post('changepassword.php', {current_password: current_password, password: password, password_again: password_again });
$('#show').html('password changed').fadeIn(500).delay(2000).fadeOut(500);
} else if ((current_password ==0) || (password_again.length == 0) || (password.length == 8)) {
$('#show').html('all fields are required').fadeIn(500).delay(2000).fadeOut(500);
} else {
$('#show').html('your password must be at least 8 characters').fadeIn(500).delay(2000).fadeOut(500); }
$('#current').val(null);
$('#new').val(null);
$('#confirm').val(null);
});
i want to echo out $error variable when a user enters an incorrect password and click on the change password button with id="#save_pass"
You cannot echo php variables within a javascript file. Instead, put the javascript in your php file and echo it there - eg:
<script>
function something() {
alert('<?php echo $error; ?>');
}
</script>
In order to get back the errors from your $.post() ajax call, you need to echo $errors in your php script. Then add a success/done function to your $.post():
$.post('changepassword.php', {current_password: current_password ...})
.done(function (data) {
alert(data);
}
This should be the basics for getting back the raw echo data, but look at $.post documentation for more guidance on how to refine this.
I want the user to fill at least 1 out of 3 fields in the search form is it possible?
here is the link
http://img.needforgaming.x10.mx/procurar.php
i dont want user to have empty fields and search to apper all the data...
In your procurar.php file you should apply the check condition.
Use the below code:
if(isset($_REQUEST['btn_procurar'])){
if(empty($_REQUEST["Cliente_procurar"]) && empty($_REQUEST["N24H_procurar"]) && empty($_REQUEST["NS24_procurar"])) {
echo "Please fill At least a field";
} else {
//your code to search and other
}
}
Above code is server side if you want to check it client side then use the javascript.
Use client side or server side validation for it. You just need to check if anyone of the three textboxes has a value or not. OR all the text boxes having empty values. In javascript, you can check it as follows:
if((document.getElementById('text1').value == '') && (document.getElementById('text2').value == '') && (document.getElementById('text3').value == ''))
{
alert('Enter any values for search');
return false;
}
You can do it using PHP
<?php
if(isset($_POST['submit'])){
if(!empty($_POST['search1'])||!empty($_POST['search2'])||!empty($_POST['search3'])){
echo "Do Search";
}
else{
echo "you mush fill at least one field";
}
}
?>
<form action="" method="post">
<input type="text" name="search1">
<input type="text" name="search2">
<input type="text" name="search3">
<input type="submit" value="Search" name="submit">
</form>
You should write javascript code to check:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function () {
$(document.forms[0]).submit(function () {
canSubmit = false;
$('form input:text').each (function () {
if($(this).val().length > 0)
canSubmit = true;
});
return canSubmit;
});
});
<script>
function verification()
{
var1= document.getElementById("formProcurar").value;
var2= document.getElementById("formProcurar").value;
var3= document.getElementById("formProcurar").value;
if((var1 != "") && (var2 != "") && (var3 != ""))
{
// do what ever you want here.
}
else
{
alert("Fill at least one field");
}
}
Use java script for the task this will be user friendly as the page does not need to refresh
I'm using bvalidator (jquery validation plugin) to check if a username exists in the database. They have an example on their documentation. However, I have no idea how it works. You can read more on that example here:
http://karmela.fsb.hr/~bmauser/bvalidator/documentation.html#serversidevalidation
I tried creating my own. However, It always tells me that the username is already taken no matter what... I'm a complete newbie when it comes to AJAX. I barely know it. So anyway, here's what I created so far...
index.php (the main page)
<script type="text/javascript">
$(document).ready(function () {
$('#register').bValidator(optionsRed);
});
function checkUsername(username) {
$.post("checkusername.php", { username: username }, function(data) {
if (data == 0) {
ret = true;
} else {
ret = false;
}
return ret;
});
}
</script>
<input type="text" name="username_register" id="textstyleid" data-bvalidator="checkUsername,required,rangelength[5:20]" data-bvalidator-msg="This username is not valid or already taken."/>
checkusername.php (checks if username exists)
<?php
require '../connect.inc.php';
if (isset($_POST['username'])) {
$username = mysql_real_escape_string($_POST['username']);
if (!empty($username)) {
$username_query = mysql_query("SELECT COUNT(uid) FROM users WHERE username='$username'");
$username_result = mysql_result($username_query, 0);
if ($username_result == 0) {
return 0;
} else if ($username_result == 1) {
return 1;
}
}
}
?>
Edit
I noticed a 404 error. I fixed that. The PHP and AJAX is working. It gives me a 0 or 1 depending on the text entered in the preview. However, the problem still exists. I think its because of this line of code. I don't really understand what it means. What is data?:
if (data == 0) {
ret = true;
} else {
ret = false;
}
return ret;
After looking at it further the problem is your php, you need to use mysql_num_rows around your result to compare with 0 recs returned, the result object itself will only give u a resource id if echo'ed out
Try this one
if (data == 0) {
echo json_encode(TRUE);
} else {
echo json_encode(FALSE);
}