Ajax. Sending data to php file - javascript

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.

Related

Use a document.getElementById into a query or another way to do this

I need to insert a value got from a document.getElementById into a sql query.
I need to do this because i'm trying to autofill a second input box depending on the result of the first (i.e. if i type Rome in the first one i would like the second one to autofill with the related country found in my db, like Italy)
Here is the code:
<?php
echo (" <form NAME='Form1' id='Form1' method=post class=statsform action=page.php > " );
echo (" <input type=text name=city id=city size=50 class=formfield value='$city' onBlur='Assigncode();' > " );
echo (" <input type=text name='Country' id='Country' size=12 value='$Country' > " );
?>
<script>
function Assigncode() {
var elemento = document.getElementById("city");
var elementoCod = document.getElementById("Country");
if (elemento != null && elemento.value != '') {
var city = elemento.value;
if (elementoCod == null || elementoCod.value == '') {
<?php
$query2 = "SELECT * FROM table WHERE city = 'put here the getElementById of the city' ";
$result2 = MYSQL_QUERY($query2);
$i2 = 0;
$country = mysql_result($result2,0,"T_Country");
?>
eval( "document.Form1. Country").value = '<?php echo($country)?>';
}
}
}
</script>
Any suggestion?
Thanks
Here is a slightly modified version of an AJAX example script found on Wikipedia. It should give you the basic idea on how to proceed. If you use jQuery then a lot of this JavaScript could be reduced to just a few lines.
// This is the client-side javascript script. You will need a second PHP script
// which just returns the value you want.
// Initialize the Http request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php?city=' + elemento.value);
// Track the state changes of the request.
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
document.Form1.Country.value = xhr.responseText; // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
send-ajax-data.php:
<?php
$city = $_GET['city'];
$query2 = "SELECT * FROM table WHERE city = '$city'";
$result2 = MYSQL_QUERY($query2);
$country = mysql_result($result2,0,"T_Country");
echo $country;
By the way, the $city variable should be validated and escaped prior to using it in an SQL query.

Session variable not being updated after being used

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.

If Else Condition with Ajax responseText from PHP

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).

AJAX not passing variable to PHP for MySQL query

I am trying to get the below AJAX script to pass a dropdown ID to PHP to run a query on, however it doesnt appear that the variable is actually being passed. When I hardcode the PHP file the query runs correctly, but when I try to do it dynamically the query returns "undefined" or nothing at all.
AJAX code
function ajax_post(){
var request = new XMLHttpRequest();
var id = document.getElementById("editorginfo").value;
alert (id);
request.open("POST", "parse.php", true);
request.setRequestHeader("Content-Type", "x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
document.getElementById("orgeditname").value = return_data;
document.getElementById("orgeditphone").value = return_data;
}
}
request.send("id="+id);
}
PHP Parse Code
<?php
include_once('../php_includes/db_connect.php');
$searchid = $_POST['id'];
//$searchid = 1;
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
$user_query = mysqli_query($db_connect, $sql) or die("Error: ".mysqli_error($db_connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$orgid = $row["id"];
$orgname = $row["orgname"];
$orgphone = $row["orgphone"];
echo $orgname, $orgphone;
}
?>
Not really sure where the information is getting lost. When I alert the id out it is capturing the right information, so I assume the issue is in my send portion, but I can't figure out what I'm doing wrong. Any help would be appreciated.
Thanks in advance.
Your request header is wrong. Change this line -
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
^^^^^^^^^^^^

Debugging MySQL query in PHP when called from other page

Page1 has an input form. I validate the input field with a JavaScript:
<input type="text" name="frmBrand" size="50" onkeyup="BrandCheck();" maxlength="100" id="frmBrand" />
<span id="frmBrand_Status">Enter existing or new brand</span>
In the JavaScript I then call a PHP script:
function BrandCheck()
{
var jsBrandName = document.forms["AddPolish"]["frmBrand"].value;
if (jsBrandName !==null || jsBrandName !== "")
{
document.getElementById("frmBrand_Status").textContent = jsBrandName
// alert(jsBrandName);
var xmlhttp = new XMLHttpRequest();
var url = "CheckBrand.php";
var vars = "jsBrandName="+jsBrandName;
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var return_data = xmlhttp.responseText;
document.getElementById("frmBrand_Status").innerHTML = return_data;
}
}
xmlhttp.send(vars);
document.getElementById("frmBrand_Status").innerHTML = "processing.....";
}
}
So far so good. I do get results from the CheckBrand.php because it changes the frmBrand_Status. But I can't get any database results from the PHP page.
<?php
if(mysqli_connect_errno()) { //if connection database fails
echo("Connection not established ");
}
//by now we have connection to the database
else
{
if(isset($_POST['jsBrandName']))
{ //if we get the name succesfully
$jsBrandName = $_POST['jsBrandName'];
$dbBrandName = mysql_real_escape_string($jsBrandName);
if (!empty($dbBrandName))
{
$dbBrandName = $dbBrandName . "%";
$sqlQuery = "SELECT `BrandName` FROM `Brand` WHERE `BrandName` like '$dbBrandName' ORDER BY `BrandName`";
$result = mysqli_query($con, $sqlQuery);
$NumRows = mysqli_num_rows($result);
// $BrandName_result = mysql_fetch_row($BrandName_query);
echo "Result " . $dbBrandName . " ----- ". $jsBrandName . "Number rows " .$NumRows. " BrandName = " .$result. " SQL " .$sqlQuery;
if( $BrandName_result = mysql_fetch_row($BrandName_query))
{
While ($BrandName_result = mysql_fetch_row($BrandName_query))
{
echo "Brand = " .$BrandName_result[0];
}
}
}
else
{
echo "dbBrandName = empty" . $dbBrandName;
}
}
}
?>
When doing this, the html page shows the constant change of the normal variables. For example when the input field holds "Clu" I get the following output the span ID frmBrand_Status:
Result Clu% ----- CluNumber rows BrandName = SQL SELECT `BrandName` FROM `Brand` WHERE `BrandName` like 'Clu%' ORDER BY `BrandName`
Which looks good as the brandname gets the % appended, but the Number of rows is not shown (empty field?), the SQL Query is shown and looks good, but I don't get any results.
And the if( $BrandName_result = mysql_fetch_row($BrandName_query)) section will not be reached, so there definitely is something going wrong in calling the query.
When I run that same query through PHPMyAdmin, i do get the result I expect, which is 1 row with a brandname.
I'm using firebug to try and troubleshoot the SQL Query, but I can't find where I can check this and I probably can't since PHP is serverside. correct? But how should I then trouble shoot this?
Found what was wrong.
The $con string I was using to open the database was no longer available. On other pages in the site, the $con is available, I load the database using an include script on my index page. But it seems that the variable gets lost when it is called through the XMLHttpRequest(). Which is logical now I think of it, since this can also be a call to a remote server. So my CheckBrand.php page was just missing the $con var to connect to the database.

Categories