Im building simple login system using Ajax XMLhttpRequest. PHP File and Javascript all working fine.. but when i use response test in IF Else Condition its not working as i expect.
Here My HTML
<div class="login-form">
<input type="username" name="username" id="username" class="text-input--underbar" placeholder="Username" value="">
<input type="password" name="password" id="password" class="text-input--underbar" placeholder="Password" value="">
<br><br>
<ons-button modifier="large" onClick="javascript:ajax_post();" class="login-button">Log In</ons-button>
<br><br>
<ons-button modifier="quiet" class="forgot-password">Forgot password?</ons-button>
</div>
<div id="status"></div>
Here my Javascript Code.
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "http://boost.meximas.com/mobile/login.php";
var fn = document.getElementById("username").value;
var ln = document.getElementById("password").value;
var vars = "username="+fn+"&password="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
if(return_data=="true"){
alert("Yes Login True");
}else{
alert("No Login False");
}
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
Here my PHP Code
if(isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
}
$sql = "SELECT * FROM member WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($con,$sql);
if(!$result){
echo "failed";
}else{
echo "true";
}
For the Wrong input also im getting Yes Login True and status inner HTML True that mean PHP file always returning True. but when i check php file alone it works fine.. there is no errors.
i meant using this.
while($row = mysqli_fetch_array($result)) {
echo "Hello" .$row['email']. "Thanks";
}
it gives correct output.
Im sorry if its unclear.. please let me know.
The function mysqli_query() will only return FALSE if your query produces an error in the database. Otherwise, it will always return TRUE. Giving that, you should check your results in another way, like using mysqli_num_rows().
Besides, it is very advisable that you sanitize user's inputs before running queries with them. Always remember Booby Tables(and how to prevent it in PHP).
Related
I'm having a really odd problem and iv'e been going at it for a while now, scouring the internet for answers and not finding any. I'm trying to parse a JSON object (which has been successful so far) but the problem I have is that when I link to my HTML file it opens a new tab after clicking submit on the HTML form part. Im sure that this is a stupid question but i really haven't found an answer to it. I'm using PHP to encode a simple JSON object. Here is my code for the HTML part:
<!DOCTYPE HTML>
<HTML>
<body>
<center>
<H1> Registration </H1>
<form action = "/Register.php" method = "post">
<h2>Username:</h2>
<input type = "text" name = "username"><br>
<h2>Name:</h2>
<input type = "text" name = "name"><br>
<h2>Password:</h2>
<input type = "password" name = "password"><br>
<h2>Age:</h2>
<input type = "number" name = "age"><br><br>
<input type = "submit" name = "Submit">
</form><br>
Back To Login
<p id = "demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.success;
}
};
xmlhttp.open("GET", "Register.php", true);
xmlhttp.send();
</script>
</center>
</body>
</HTML>
And here is the code for the php/json part:
<?php
$con = mysqli_connect("localhost", "id5137223_bellevueeast", "BEAST", "id5137223_users");
$name = $_POST["name"];
$age = $_POST["age"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO Users (name, username, age, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssis", $name, $username, $age, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
It's opening a new window/tab because you are not preventing the default behavior of the HTML form, which will submit to it's own location. Basically it sends a request to the page the form is on with the get/post data from the form attached. Your JavaScript function executes fine, but then the default action of the form causes a second window to open.
If you do not want this to happen, you have to break or stop the default behavior of the HTML form with prevent default.
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Judging from your code, I am guessing that you want to call a JSON from Register.php and display it on the same page. In this case, what you need to do is to encase you XMLRequest in a Javascript function like so
function showResult() {
//do your XMLRequest stuff here
//change the div accordingly
document.getElementById("placeholder").innerHTML=*prettified json here*;
}
Then what you need to do is create a div to show your results and act as a placeholder
<div id="placeholder">
Next up is to change the submit into a button and add onPress="showResult()" to it.
<button onPress="showResult()">
You don't need submit if you are using AJAX
WOW. I realized that I am, in fact, an idiot. I was diagnosing the problem completely wrong. I thought that the form was acting up when in fact it was doing exactly what it was supposed to: Showing the data in the tab after the form went through. I finally got to do what I wanted it to though by doing this:
<iframe id="invisible" name="invisible" style="display:none;"></iframe>
and then I made the form target the iframe so it would not display anything
-_- sorry for troubling you all.
Good day, I'm trying to use Ajax in my web application. But I have a little problem with it. I try to control a form if some username has already been registered or not. But my JavaScript seem does not send $_POST value to PHP. And responses that user in not defined on the line where I have $_POST['user'].
Here what I have.
PHP:
<?php
$opt = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$dsn ='mysql:dbname=someone;host=127.0.0.1;charset=utf8';
$user='someone';
$pswd='aaa';
$dbh = new PDO($dsn, $user, $pswd, $opt);
$query="SELECT 1 FROM users WHERE username = :username";
$query_p=array(':username' => $_POST['user']);
try
{
$statment = $dbh->prepare($query);
$result = $statment->execute($query_p);
}catch(PDOException $e)
{
echo "Can't run query: " . $e->getMessage();
}
$row = $statment->fetch();
if($row){
return 0;
}else {
return 1;
}
?>
So it opens a connection to database and runs a query
JavaScript:
function checkUser(e){
var state1 = document.getElementById("alert_text");
var u = document.getElementById("user").value;
if(u != ""){
state1.innerHTML = 'processing...';
var request = new XMLHttpRequest();
request.open("POST", "validation.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var result=request.responseText;
alert(result);
if(result==1){
state1.innerHTML="OK";
}else{
state1.innerHTML="Alredy exists!";
}
}
};
request.send(u);
var slova = request.responseText;
}
}
document.getElementById("user").addEventListener("blur",checkUser,false );
So technically it is ajax.
HTML:
<form id="check" name="signUp" method="post">
<p class="alert_text"></p>
<label for="user">Username:</label><br />
<input id="user" name="user" type="text" ><br />
</form>
I don't really see what's the problem...
You're not passing the username into the PHP script. Your PHP is looking for a POST variable, $_POST['user'] – in your JavaScript you make a GET request, so the PHP script has nothing to look up.
Based on the edited question: You are not sending any key-value pairs to the server, just a single value.
You need to change:
var u = document.getElementById("user").value;
to:
var u = 'user=' + encodeURIComponent(document.getElementById("user").value);
And then later on the pair will be sent correctly:
request.send(u); // sends a single key-value pair
Note that I have just added the encodeURIComponent function to make sure the value gets encoded correctly.
I am trying to check the result from a function and determine where on my page it should go by using the Session Variable "alernativeRD". It goes to the correct element on the first try, but after that it keeps going only to the first element regardless of whether its right or not. After some testing I've found that "alernativeRD" does get changed every time in the PHP function, but it doesn't change in the Javascript part.
PHP PART
function firstSignInDefault(){
global $con;
$clubUsername= $_SESSION['clubUsername'];
$_SESSION['alternativeRD']='false'; //sets it back to false to avoid having alternativeRD be true for next user
$lastName= mysqli_real_escape_string($con, $_POST['lastNameF']);
$firstName= mysqli_real_escape_string($con, $_POST['firstNameF']);
$memberID= mysqli_real_escape_string($con, $_POST['idNumberF']);
if(!(is_numeric($memberID))){
die("<h3> Student ID must be a number </h3>");
}
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
if(mysqli_num_rows($getMemberRow)==0){
$sql="INSERT INTO memberstable (MemberMadeID,FirstName,LastName,Club)
VALUES ('$memberID','$firstName','$lastName', '$clubUsername')";
$test=false; //checks to make sure sql statement runs fine
if(mysqli_query($con,$sql))
$test=true;
else {
echo "<h3> Error running sql </h3>";
}
$date=date("Y-m-d h:i:sa");
$getMemberRow= mysqli_query($con, "SELECT * FROM memberstable WHERE MemberMadeID='$memberID' AND Club='$clubUsername'");
$memberRowArray=mysqli_fetch_array($getMemberRow);
$memberPanID=$memberRowArray['UniquePanDBID'];
$sql2="INSERT INTO signinstable (TimeOfSignIn, UniquePanDBID, ClubUsername, FirstName, LastName) VALUES ('$date','$memberPanID','$clubUsername', '$firstName', '$lastName')";
//THE FOCUS OF THIS QUESTION IS BELOW THIS COMMENT
if(mysqli_query($con, $sql2) && $test==true){
$_SESSION['alternativeRD']='true';
echo " <h2 id='signedInPeople' >".$date. " ".$firstName ." ". $lastName ."</h2>";
}
}
else {
echo "<h3> ID Number already in use</h3>";
}
}
JAVASCRIPT/AJAX PART
function processFSIF(){
var xmlHttp= makeXMLHTTP();
// Create some variables we need to send to our PHP file
var url = "signInDataPlace.php";
var idNumberF = document.getElementById("idNumberF").value;
var lastNameF = document.getElementById("lastNameF").value;
var firstNameF = document.getElementById("firstNameF").value;
var typeSignIn="first";
var vars = "idNumberF="+idNumberF +"&lastNameF="+lastNameF +"&firstNameF="+firstNameF +"&typeSignIn=" +typeSignIn;
xmlHttp.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var return_data = xmlHttp.responseText;
//AREA OF PROBLEM BELOW
<?php
if($_SESSION['alternativeRD']=='true'){ ///YOU ARE HERE, alternativeRD is acting stupid
?>
document.getElementById("serverInputList").innerHTML = return_data;
<?php
}else{
?>
document.getElementById("serverInputFSIF").innerHTML = return_data;
<?php
}
?>
}
}
// Send the data to PHP now... and wait for response to update the status div
xmlHttp.send(vars); // Actually executes the request
document.getElementById("serverInputFSIF").innerHTML = "processing...";
}
Your Javascript was printed only once, before you use AJAX. You can return the session value together with response, or you can set the cookie in PHP, than use it in javascript.
I can't seem to work this one out. Been a few days and still no progress after re-writing it more times than I can count on my hands.
Here is the Javascript (On same page as html)
Summary: User types text into the input box. That gets sent off to be processed, which then gets sent back and displayed on the screen in the box ID'd as DisplayText on the html page.
<script type="text/javascript">
function SendText() {
if (document.getElementById("Text").innerHTML == "") {
return;
} else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("DisplayText").innerHTML = xmlhttp.responseText;
}
}
Text = document.getElementById("Text").value;
xmlhttp.open("GET", "php/Test.php?Chat=" + Text, true);
xmlhttp.send();
}
}
</script>
Here is the HTML (Same page as the script)
<div>
<p>
<span id="DisplayText">
TEXT GOES HERE
</span>
</p>
</div>
<form action="" onsubmit="SendText();">
<input type="" name="" id="Text" />
<input type="submit" value="Send" name="Send" />
</form>
The PHP code is here
<?php
session_start();
include ("Connect.php");
$Connection = mysqli_connect("localhost", "root", "", "chatsystem");
$Create = "CREATE TABLE " . $_SESSION["Username"] . "Chat(Username VARCHAR(255), Chat VARCHAR(255))";
////////////////////////////////////////////////////////////////////////////////
$DatabaseExist = $Connection->query("SELECT 1 FROM " . $_SESSION["Username"] . "Chat");
if ($DatabaseExist !== false) {
echo "Database exists";
doSomething();
} else {
echo "Database does not exist";
mysqli_query($Connection, $Create);
doSomething();
}
////////////////////////////////////////////////////////////////////////////////
function doSomething() {
// Get the sent chat
$Input = $_REQUEST["Chat"];
// Insert into the database the new chat sent
mysqli_query($Connection, "INSERT INTO " . $_SESSION["Username"] . "chat (`Username`, `Chat`) VALUES ('$_SESSION[Username], '$Input')");
// Select everything from the database
$Result = $Connection->query("SELECT * FROM " . $_SESSION["Username"] . "Chat");
// Display everything from the database in an orderly fashion
// --
// For the length of the database
// Append to a variable the next table row
// --
while ($Row = $Result->fetch_array()) {
// Make Variable accessable
global $Input;
// Append username to the return value
$Input = $Input . $Row["Username"] . " : ";
// Append chat to the return value
$Input = $Input . $Row["Chat"] . "<br />";
}
}
// Will return the value
echo $Input;
?>
My connection to the Database is fine. I'm using it on other pages that work.
So lets assume that's not the problem. :P
Any help or insight from anyone who knows or can think of something that is wrong, I would be very grateful for.
I'm new to AJAX.
You do a wrong test with
if (document.getElementById("Text").innerHTML == "")
It should be the same way you use to get the text for sending in the AJAX
if (document.getElementById("Text").value == "")
So check its value property and not its innerHTML as input elements do not have html content..
Be careful though because your code is wide-open to SQL injection attacks.
1st : use input's value property instead innerHTML
eg. use
if (document.getElementById("Text").value == "")
instead of
if (document.getElementById("Text").innerHTML == "")
2nd : use return false; at the form's onsubmit event; to prevent current page to be refreshed as you are using ajax. Otherwise the page will get refreshed and it wont display the php page's output,
eg. use
onsubmit="SendText(); return false;"
instead of just
onsubmit="SendText();"
Try AJAX Long Polling technique for chat application. Here is example
http://portal.bluejack.binus.ac.id/tutorials/webchatapplicationusinglong-pollingtechnologywithphpandajax
I'm stuck on this problem. I've been trying to use http() but doesn't seem to do anything.
Here's the form (It calls ajax_request when I submit, this works fine):
<form name='form-main'>
<input id='host' type='text' placeholder='Host' />
<input id='user' type='text' placeholder='Username' />
<input id='db' type='text' placeholder='Database' />
<input id='pass' type='password' placeholder='Password' />
</form>
and here's ajax_request part:
function ajax_request() {
var host = document.getElementById('host').value;
var user = document.getElementyById('user').value;
var db = document.getElementById('db').value;
var pass = document.getElementById('pass').value;
var submitTo = 'DB.php';
//alert(submitTo);
http('POST', submitTo, ajax_response, 'Host='+host);
}
Here's ajax_response:
function ajax_response(data) {
document.getElementById('web').value = data;
}
Finally, here's the PHP DB.php I'm trying to call:
<?php
$Host = $_POST['Host'];
$User = $_POST['User'];
$DB = $_POST['DB'];
$Pass = $_POST['Pass'];
$iDB = new mysqli($Host, $User, $DB, $Pass);
if($iDB->connect_errno) echo "no";
else echo "yes";
?>
What I'm trying to achieve here is to get the response either "yes" or "no" from the PHP and have it output on ajax_response
Would you clearly and precisely describe the problem you're having?
At quick glance, I see you're performing an HTTP POST, but your PHP is looking for HTTP GET data. Changing your Javascript to perform an HTTP GET or your PHP to look at $_POST instead of $_GET may help or prevent additional problems.
PHP has the following variables: $_GET, $_POST, and $_REQUEST. $_GET contains HTTP GET data. $_POST contains HTTP POST data. $_REQUEST contains both HTTP GET and POST data.