client and server php sql bug - php

I just cant figure out what is wrong with this code.
I am just sending a username and password to the server, then server sending back a response. Server write to database with no problem, but in the client side sometimes it doesn't reach inside the if(xmlhttp.readyState==4 && xmlhttp.status==200). And after it execute the line alert('login5'), the jquery animation reset. I know it is the php problem, but I have no idea why it sometimes works but sometimes doesnt, any help is appreciated.
<script type = "text/javascript">
function sendLogin(){
var xmlhttp;
var getString;
var url = "login.php";
var username=document.getElementById('name').value;
var password=document.getElementById('pw').value;
var url= url+ "?username="+username+"&password="+password;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("get", url , true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
alert("reached inside");
getString = xmlhttp.responseText;
alert(getString);
}
}
xmlhttp.send();
alert('login5');
//problem here, have to wait a while
}
</script>
html code:
<form id="logInBoxes">
<input type="text" placeholder="username" id='name' size="15px">
<input type="password" placeholder="pw" id='pw' size="10px">
<input type="submit" value="Log In" onclick='sendLogin()'>
</form>
php code:
<?php
$username= $_GET['username'];
$password= $_GET['password'];
$salt = mcrypt_create_iv(32, MCRYPT_RAND);
$password = crypt($password, $salt);
$salt = mysql_real_escape_string($salt);
$password = mysql_real_escape_string($password);
$sql = mysqli_connect('localhost','root','','housescale');
// Check connection
if (mysqli_connect_errno()){echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($sql, "INSERT INTO user (username, password, salt)
VALUE
('$username', '$password','$salt')") or trigger_error(mysql_error());
mysqli_close($sql);
echo $username;
?>
edit: it works if I do alert('login5') 9 more times in a loop. What exactly does this delay fix imply?

Here's the code I used that worked on my end:
test.html
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function sendLogin() {
var xmlhttp;
var getString;
var url = "login.php";
var username = document.getElementById( 'name' ).value;
var password = document.getElementById( 'pw' ).value;
url = url + "?username=" + username + "&password=" + password; //Don't Need to Re-Declare url Variable
if( window.XMLHttpRequest ) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );
}
xmlhttp.open( "get", url , true );
xmlhttp.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
xmlhttp.onreadystatechange = function() {
if( xmlhttp.readyState == 4 ) {
if( xmlhttp.status == 200 ) { //Separated readyState and Status
alert( "reached inside" );
getString = xmlhttp.responseText;
alert( getString );
}
}
}; //Missed Semi-Colon Here
xmlhttp.send();
alert( 'login5' );
}
</script>
</head>
<body>
<form id="logInBoxes">
<input type="text" placeholder="username" id='name' size="15px">
<input type="password" placeholder="pw" id='pw' size="10px">
<input type="submit" value="Log In" onclick='sendLogin()'>
</form>
</body>
</html>
login.php
<?php
$username= $_GET['username'];
$password= $_GET['password'];
$salt = mcrypt_create_iv( 32, MCRYPT_RAND );
$password = crypt( $password, $salt );
$sql = mysqli_connect( 'localhost', 'root', '', 'housescale' );
$salt = mysqli_real_escape_string( $sql, $salt );
$password = mysqli_real_escape_string( $sql, $password );
// Check connection
if ( mysqli_connect_errno() ){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query( $sql, "INSERT INTO user ( username, password, salt ) VALUE ( '$username', '$password', '$salt' )" )
or trigger_error(mysql_error());
mysqli_close( $sql );
echo $username;
?>
I use Mozilla Firefox 23 on Windows 7. My stack is Uniform Server 8.8.2 (PHP 5.4.14 / MySQL 5.5.30).
I set all the fields in my table to varchar(255) just to be quick. It worked for me with only one issue, sometimes the salt/crypt turned up empty in my database, but that's probably a charset issue because it was able to echo several different combinations just fine.

Related

AJAX autopopulate using PHP

I am trying to populate two fields 'dep' and 'arr' when field 'flightnumber' is written into and 'onpointermove'.
Here is the form code:
<input type="text" name="flightnumber" id="flightnumber" onpointermove="showUser(this.value)" style="width: 70px;" maxlength="4">
<input type="text" name="dep" id="dep" style="width: 70px;">
<input type="text" name="arr" id="arr" style="width: 70px;">
Here is the AJAX
<script>
function showUser(str) {
if (str.length=="") {
document.getElementById("dep").innerHTML="";
document.getElementById("arr").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("arr").innerHTML = myObj.dep;
document.getElementById("dep").innerHTML= myObj.arr;
}
}
xmlhttp.open("GET","getdata.php?q=" + str,true);
xmlhttp.send();
</script>
And here is the php, which i have tested and does return correct results...
<?php
//look up the record based on email and get the firstname and lastname
$host_name = 'db5000091260.hosting-data.io';
$database = 'dbs85930';
$user_name = 'dbu68420';
$password = '';
$connect = mysqli_connect($host_name, $user_name, $password, $database);
$q = $_GET['q'];
$myObj->dep = "";
$myObj->arr = "";
$sql = "SELECT dep, arr FROM flights WHERE flightnumber = {$q}";
$result = mysqli_query($connect, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$myObj->dep = $row['dep'];;
$myObj->arr = $row['arr'];
$myJSON = json_encode($myObj);
echo $myJSON;
}
} else {
echo "0 results";
}
?>
I can only assume that the issue here is within the AJAX coding, as the PHP as mentioned is working.

DB Connection in html using php

I have a HTML page index2.html. In this page, I have a DIV which I am using to call a PHP page. The Php page has DB connection parameters, an SQL to fetch values from the DB.
However, when the PHP is called from the HTML, I am getting redirected to the PHP page. All I want is to use this stored procedure to get the data from the database.
HTML Code Snippet
</head>
<body>
<div id="background">
<div id="Layer0"><img src="images/Layer0.png"></div>
<div id="Layer2"><img src="images/Layer2.png"></div>
<div id="parceldeliveryservic"><img src="images/parceldeliveryservic.png"></div>
<div id="Layer10">
<form action="insert4.php" method="post">
<input type="image" src="images/Layer10.png"/>
</form>
</div>
The PHP Code Snippet:
<?php include("connect.php");
//$q = intval($_GET['q']);
try {
$proc_rate ='rtPreston';
$proc_price = 0.0;
$conn = new PDO("mysql:host=$servername;dbname=testdb", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$sql = "GetPrice(?, ?)";
$sql = "Call GetPrice(:input, #output_price)";
$stmt = $conn->prepare($sql);
echo $proc_price;
$stmt->bindParam(':input',$proc_rate, PDO::PARAM_INT);
$stmt->execute();
$stmt->closeCursor();
$proc_price = $conn->query("SELECT #output_price AS output_price")->fetch(PDO::FETCH_ASSOC);
if ($proc_price) {
echo sprintf('Price for %s is %lf', $proc_rate, $proc_price['output_price']);
}
} catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
//$conn = null; ?>
can you please let me know what needs to be done to display the result in the calling HTML page?
Many thanks
HTML
<div onclick="callPHP();">Click me!</div>
Javascript
<script>
function callPHP() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// xmlhttp.responseText contains the result of the PHP
alert( xmlhttp.responseText );
}
};
// Call the PHP
xmlhttp.open("GET", "insert4.php", true);
xmlhttp.send();
}
</script>

Why does not insert these values in database using Ajax

I used tutorialspoint to guide me to insert the values from input text into the db, but unfortunately, it will not insert to the database. Is this correct implementation for AJAX?
Here's my index.php
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var gen = document.getElementById('gen').value;
// var queryString = "?age=" + age ;
queryString += "&fname=" + fname + "&lname=" + lname+ "&gen=" + gen;
ajaxRequest.open("GET", "ajax.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
First Name: <input type='text' id='fname' /> <br />
Last Name: <input type='text' id='lname' /> <br />
Sex:
<select id='gen'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
ajax.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "my_db";
$con = new mysqli($dbhost, $dbuser, $dbpass,$dbname);
$query="INSERT INTO table1 (fname, lname, gender)
VALUES
('$_GET[fname]','$_GET[lname]','$_GET[gen]')";
$qry_result = $con->query($query);
?>
change your code to the bellow
var queryString;
queryString = "fname=" + fname + "&lname=" + lname+ "&gen=" + gen;
ajaxRequest.open("GET", "ajax.php?" + queryString, true);
and make sure ajax.php is in the same folder as index.php
Try this in ajax.php:
$fname=$_GET['fname'];
$lname=$_GET['lname'];
$gen=$_GET['gen'];
$query="INSERT INTO table1 ('fname', 'lname', 'gender')
VALUES('$fname','$lname','$gen')";
Declare Form method="POST"
and
$query="INSERT INTO table1 (fname, lname, gender) VALUES
('".$_POST['fname']."','".$_POST['lname']."','".$_POST['gen']."')";

PHP INSERT to hosting database

I have this PHP code that inserts id, firstname and lastname:
<?php
header('Access-Control-Allow-Origin: *');
$conn = mysql_connect('localhost', 'happy', '***');
$db = mysql_select_db('dbtest');
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
mysql_query("INSERT INTO tbltry (firstname, lastname) VALUES('$firstname', '$lastname')");
?>
And I have this HTML with AJAX:
<script>
function save(){
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", " **url** ", true);
console.log("added");
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
}
}
}
</script>
</head>
<body>
Firstname: <input type="text" name="firstname" id="firstname">
Lastname: <input type="text" name="lastname" id="lastname">
<button onclick="save()">Save</button>
</body>
This two are working fine, it insert a new row in database, but the only data that is inserted is the id on id column and column firstname and lastname is blank.
Can someone tell what am I missing? Any help would be appreciated.
Try this
<script>
function save(){
var xmlhttp;
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var data = {firstname:fname,lastname:lname};
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", " **url** ", true);
console.log("added");
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(data);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
}
}
}
Try something like this,
function save(){
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var data = "firstname="+fname+"&lastname="+lname;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","url?"+data,true);
xmlhttp.send();
}
your test file should be like
<?php
$conn = mysql_connect('localhost', 'happy', '***');
$db = mysql_select_db('dbtest');
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
mysql_query("INSERT INTO tbltry (firstname, lastname) VALUES('$firstname', '$lastname')");
?>
Instead of using old xmlhttp its better to use jQuery.Ajax, Also mysql functions are deprecated use PDO.
You should use any mysql escape function for security.
Hope it helps..

error in json function saving data into database

I have tried a lot but I have not been able to find out what is wrong with this function to save two values into database. It has been working fine for another function to save one value. It behaves very strange here. Sometimes send 'parent' value & sometimes stop sending it but never send msg value. Here is function. It works fine for one input i.e. parent but problems start with the addition of 2nd input.
<script>
function ADDLISITEM(form)
{
var parent = form.txtInput.value;
var msg = form.msgInput.value;
form.txtInput.value = "";
form.msgInput.value = "";
var url = "send_mysql.php"
var request = null;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
request=new XMLHttpRequest();
}
else
{// code for IE6, IE5
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("Connection", "close");
request.onreadystatechange = function(){
if (request.readyState == 4) {
if (request.status == 200) {
//alert('POST');
} else {
alert(request.status); // fails here
}
}
}
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" +
encodeURIComponent(msg).replace(/%20/g, '+'));
}
</script>
This is send.php
$username = "babar";
$password = "k4541616";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect
to MySQL");
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
//die(var_export($_POST,TRUE));
$parent = $_POST['parent'];
$msg = $_POST['msg'];
$name = 'Akhtar Nutt';
//$parent2 = json_decode($parent);
$msg_ID = '2q7b2sfwwe';
//$msg2 = json_decode($msg);
$query = "INSERT INTO msg2_Qualities(id,name,msg,msg_id,parent) VALUES
('','$name','$msg','$msg_ID','$parent')";
if(!mysql_query($query, $dbh))
{die('error:' .mysql_error())
;}
?>
Alter
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
to:
request.send("parent=" + encodeURIComponent(parent).replace(/%20/g, '+')+"&msg=" + encodeURIComponent(msg).replace(/%20/g, '+'));
You're missing the argument separator & in your query string...
You also might want to refrain from using values in $_REQUEST as they aren't reliable. If your script expects data from a POST then retrieve these values from $_POST.

Categories