Live username Checking is not working - javascript

I am trying to make register page with jquery and php where user put his username and while he is inserting in text box his username, my website check immediately if it is available or not and show! But my code is not working.
Here is my js code :
$(".r74re").keyup(function (e){
var user_name = $(this).val();
if(user_name.length >= 4)
$.post('liveusername.php', {'username':user_name}, function(data) {
$('.step1 input.usrname:focus').css({
'background': '#fff url("images/loader.gif") 275px no-repeat',
'background-size':'10px 20px'
});
setTimeout(function (){
if(data.success){
console.log("in positive " + data);
$('.step1 input.usrname:focus').css({
'background-color': 'lightgreen',
'background-size':''
});
}else{
console.log("in negative " + data);
$('.step1 input.usrname:focus').css({
'background-color': 'red',
'background-size':''
});
}
}, 1000);
});
Here is my php code that $.Post call when keyup event is :
include ("dbcon.php");
include ("funchuge.php");
if(isset($_POST["username"]))
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
//sleep(1);// for animating
if(strlen($_POST["username"]) > 3){
selfValidator($_POST["username"]);
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW|FILTER_FLAG_STRIP_HIGH);
$statement = $conn->prepare("SELECT username FROM users WHERE username=:usname");
$statement->bindparam(':usname', $username);
$statement->execute();
if($statement->fetch()){
$message = "ItExists";
echo json_encode(['success' => true, 'messages' => $message]);
}else{
$message = "NotExists";
echo json_encode(['success' => false, 'messages' => $message]);
}
}
}
I test a lot and i found problem in js code in line if(data.success) this condition is not working.. it always show me else condition if user allso exists.. i dont know why happening this ? Someone can help me found out my problem.

You need to parse the returned PHP string into JSON before you can access it like an object. Add this line above your setTimeout.
data = JSON.parse(data);

Related

Passing js variable to php using ajax does not work

I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution
$('#add-review').click(function(){
var user_name = $('#reviewer-name').val();
var user_review = $('#review').val();
console.log(user_name);
console.log(rating_index);
console.log(user_review);
if(user_name == '' || user_review == '')
{
alert("Please Fill Both Field");
return false;
}
else
{
$.ajax({
url:"rating-data.php",
method:"GET",
data:{
rating_index: rating_index,
user_name: user_name,
user_review: user_review
},
success:function(data)
{
$('#review_modal').modal('hide');
load_rating_data();
console.log(data);
}
})
}
});
This is my php code when I can get the variable and send them to the database:
<?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
$data = array(
':user_name' => $_GET["user_name"],
':user_rating' => $_GET["rating_index"],
':user_review' => $_GET["user_review"],
':datetime' => time()
);
$query = "
INSERT INTO review_table
(user_name, user_rating, user_review, datetime)
VALUES (:user_name, :user_rating, :user_review, :datetime)
";
$query_run = mysqli_query($conn, $query);
if($query_run){
echo "Your Review & Rating Successfully Submitted";
} else{
echo '<script type="text/javascript"> alert("Something went wrong") </script>';
echo mysqli_error($conn);
}
}
?>
When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions
Instead of echo ($rating_index); try echo ($_GET["rating_index"]); reason being you didn't actually declared $rating_index
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.
var x = " < ? php echo"$name" ? >";
you can pass your PHP variable like this but in only the .php file not in the .js

Data Not inserting to DB - PHP MYSQL

Trying to get together the sign up validation with PHP and Ajax. Not sure what is wrong but the submission does not happen. If I don't add the validation part everything looks fine and i am able to insert the data to mysql.
<script type="application/javascript">
$("#submit").submit(function (event) {
event.preventDefault();
var datatopost = $(this).serializeArray();
console.log(datatopost);
$.ajax({
url: "signupregister.php",
type: "POST",
data: datatopost,
success: function (data) {
if (data) {
$("#signupmessage".html(data));
}
},
error: function () {
$("#signupmessage").html("<div class = 'alert alert-danger'></div>")
}
});
});
</script>
_
<?php
session_start();
include('mysqlconnection.php');
include('index.php');
function customError($errors, $errorslevel)
{
}
set_error_handler("customError", E_ALL);
if (isset($_POST['submit'])) {
if ($_POST($first_name) == "") {
$errors .= $first_nameError;
} else {
$first_name =
filter_var($_POST["first_name"], FILTER_SANITIZE_STRING);
}
}
if ($errors) {
$resultMessage = '<div class="alert alert-danger">' .
$errors . '</div>';
echo $resultMessage;
exit;
}
$first_nameError = '<p>first name required</p>';
First up, in your validation PHP script, you won't need to include 'index.php'
Try redirecting the form to an empty page where you only include your validation data, while setting a session variable for the first error encountered.
At the end of your validation, if your error variable contains an error, you can redirect to the form and display your said error at a convenient location. Keep in mind you will have to save form data in session variables if you want to preserve all user input (thus removing the hassle of refilling the form over and over again).
If it doesn't, you can proceed to insert the data in your db then redirect to your desired landing page.
Here's a sample code based on your input:
<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['fname'] = $_POST['fname'];
//so on for your other variables
if($_SESSION['fname'] == ""){
$_SESSION['err'] = "First Name Required";
}
if(//insert your format validation for first name){
$_SESSION['err'] = "First Name Invalid";}
}
//end of validation
if isset($_SESSION['err']){
header('Location: myform.php');
}
else{
//save all your variables into normal ones, i.e $fname-$_POST['fname'];
//insert into database;
//check correct insertion;
//redirect to landing page;
}
}
?>

Comparing strings in JQuery not working

Alright so here's the situation. I have the following code block in my php file, and for some reason, whenever it comes to check data, it doesn't accept. I've printed out the value of data, and it is indeed "accepted" (without quotes obviously). Am I comparing these wrong somehow? Running basically the exact same code in another section of my website and it works fine.
$(document).ready(function () {
$("#sign").click(function () {
jQuery.ajax({
url: "loginConfirm.php",
data: { // Correct
username: $("#username").val(),
password: $("#password").val()
},
type: "POST",
success: function (data) {
if ($("#username").val() === "") {
//Do nothin
} else if (data === "accepted") {
alert("Here");
redirectSignIn();
} else {
alert("There");
$("#signInTitle").html(data);
}
},
error: function () {}
});
});
});
EDIT: php code I'm calling in the url below
<?php
// The global $_POST variable allows you to access the data sent with the POST method
// To access the data sent with the GET method, you can use $_GET
$username = htmlspecialchars($_POST['username']);
$userpassword = htmlspecialchars($_POST['password']);
require_once("dbcontroller.php");
$db_handle = new DBController();
$result = mysql_query("SELECT count(*) FROM loginInfo WHERE userName='" . $username . "' AND password='" . $userpassword . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0)
echo "accepted";
else
echo "denied";
?>
You cant validate if ($("#username").val() === "") { in success function. For that you are suppose to validate it before making Ajax call.
I would like to give some advice here that first you have to validate the inputs of the user if validate then you can call ajax.
and then you not required to check the value of the username in AJAX process.
Like....
if($("#username").val() === "" && $("#passoword").val() === "")
{
//AJAX call
}
else
{
//alert to enter the valid inputs
}
hope you get it my concept...

How to get div content that was echoed by PHP

I need to get a value inside a div content. After a button click and doing stuff on the server side, my PHP function does:
echo "0";
or
echo "1";
depending on what my function does. So let's say if it's 0, the AJAX response will be $("div#divResult").html(data); where I put the 0 in the div divResult.
What I am trying to do now is I want to execute a js function to read whether it's 0 or 1 in divResult.
This is how I execute it:
<div id="divResult"><script>getDivResult();</script></div>
And my js function:
function getDivResult()
{
var result = $("div#divResult").text();
if(result === "0")
{
alert("Badge Number already exists, please check again.");
}
else if(result === "1")
{
alert("Your details have been entered!")
ADD_USER_POPUP.close;
}
}
Somehow the getDivResult function is not executing. The 0 and 1 does display on in the div though. Any help on this? I've tried .html too by the way.
EDIT:
Here's the AJAX that I use for the button click and return the response from PHP which is either 1 or 0:
$.post(page, {
name : name,
badge_number : badge_number,
category : category,
priviledge : priviledge,
action : "insert"
}, function(data) {
$("div#divResult").html(data);
});
2nd EDIT:
function insertRow($name, $badge_number, $priviledge, $category)
{
$table_info = "TBL_USER_LOGIN";
$query_string = "select badge_number from $table_info where badge_number = $badge_number";
$result = #mysql_query($query_string) or die (mysql_error());
$checkBadge = mysql_num_rows($result);
if($checkBadge>0)
{
//echo "Badge Number $badge_number already exists. Please check again.";
echo "0";
}
else
{
$query_string = "insert into $table_info(name, badge_number, priviledge, category) values('$name', '$badge_number', '$priviledge', '$category')";
$result = #mysql_query($query_string) or die (mysql_error());
//echo "Your details have been entered! Please click on 'View Users' to display all users.";
echo "1";
}
?>
<?php
$action = rtrim($_REQUEST['action']);
if($action=="delete")
{
$id = rtrim($_REQUEST['id']);
$order = $_REQUEST['order'];
echo deleteRow($id);
echo selectAll($order);
}
elseif($action=="insert")
{
$name = $_REQUEST['name'];
$badge_number = $_REQUEST['badge_number'];
$priviledge = $_REQUEST['priviledge'];
$category = $_REQUEST['category'];
echo insertRow($name, $badge_number, $priviledge, $category);
}
elseif($action=="update")
{
$order = $_REQUEST['order'];
echo selectAll($order);
}
?>
You shouldn't need to append the return data to the page at all. Why don't you run your function immediately after the AJAX request completes, like so:
$.ajax({
success: function(data) {
if(data === "0") {
alert("Badge Number already exists, please check again.");
}
else if(data === "1") {
alert("Your details have been entered!")
ADD_USER_POPUP.close();
}
}
});
place getDivResult() to onclick in which button you click like
< button onclick="getDivResult()">Click me< /button>"
i think it will be work with you.
enclose the echo with a div then trying getting the value by the id.
or
try echoing via json enconde
json_encode
then fetch the value by using AJAX
i think, this script <script>getDivResult();</script> was replaced the content of #divResult by ajax code $("div#divResult").html(data);. Instead of that, place the script inside head section rather than inside #divResult to execute that.
Where is your ajax? How do you do it?
It looks like you're using jQuery. Try reading the documentation
https://api.jquery.com/jquery.get/
You can try something like this:
$.get( "ajax/test.html", function( data ) {
if(data === "0")
{
alert("Badge Number already exists, please check again.");
}
else if(data === "1")
{
alert("Your details have been entered!")
ADD_USER_POPUP.close;
}
});
data should be your 0 or 1
When you do .html(data) all the existing elements wipedoff and replaced by new content:
$("div#divResult").html(data);
I guess you should do this:
$("div#divResult").html(data);
getDivResult(); // call after it. and put the function globally.
Run your function
getDivResult();
after
$("div#divResult").html(data);
in ajax

AJAX not returning a variable from php

I know there is a few questions like this on here. but I have done a lot of researching and bug fixing all day to try work out why my ajax does not return a response from the php file. All I want is for it to tell me a user has been registered so I can let the user move on with the signing up process. And I just need someones wise guidance to tell me what I am doing wrong!!
so I wont bore you with the validation part of the js file just the ajax
if(ValidationComplete == true){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(register, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url:url,
type:type,
data: data,
dataType: 'json',
success: function(result){
alert(result.status);
console.log(result.data);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
return false;
} else {
return false;
}
currently with this, if I remove the dataType bit the alert bit happens but currently with it there nothing does.
again I will just skip to the chase on the php file
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password',
'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
echo json_encode(array("response"='true'));
Any help would be amazing!!!!!
updated code:
<?php
if( isset($_POST['firstname']) &&
isset($_POST['surname']) &&
isset($_POST['email']) &&
isset($_POST['day']) &&
isset($_POST['month']) &&
isset($_POST['year']) &&
isset($_POST['password']) &&
isset($_POST['re_type_password'])){
$first_Name = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$re_type_password = $_POST['re_type_password'];
$emailCode = md5($_POST['$first_Name'] + microtime());
if(!empty($first_Name)&&
!empty($surname)&&
!empty($email)&&
!empty($day) &&
!empty($month) &&
!empty($year) &&
!empty($password)&&
!empty($re_type_password)){
if(strlen($firstname)>30 || strlen($surname)>30 || strlen($email)>50){
echo 'the data enetered is to long';
} else {
if($password != $re_type_password){
echo 'passwords do not match, please try again.';
} else{
$query = "SELECT email FROM person WHERE email ='$email'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run)==1){
echo 'Email address already on databse';
} else{
if($day>31 || $month>12){
echo 'date of birth wrong';
} else{
$dob= $year.'-'.$day.'-'.$month;
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password'
,'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
email($email, 'Email Confirmation', "hello ". $first_Name." ,
\n\n you need to activate your account so click the link ");
$return_data['status'] = 'success';
echo json_encode($return_data);
} else {
echo #mysql_error();
}
}
}
}
}
} else {
echo "<p id='error'> All fields are required. Please try again.</p>";
}
}
?>
<?php
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
?>
</body>
</html>
the last line it should be
echo json_encode(array("response"=>'true'));
see the added > in the array declaration, that is used to assign arrays with keys.
also in general you should put a error capture in your ajax statement, see this answer for more info
EDIT: Ok wow, that's some spaghetti code you have there, but after a little clean-up your problem is too many closing braces } you have to remove the } just before the following line also get rid of the closing and opening tags around this line, they serve no use.
} // <------- THIS ONE!
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
I should also mention two other issues with your code
You are accepting input from the user without cleaning it up and testing it properly. This is no no read here to find out more
You are using mysl_ functions, these are old and depreciated they are also security risks. Check out PDO instead
EDIT:
Add ini_set('error_reporting',1); to the top of your php script.

Categories