PHP & AJAX & MySQL integration - javascript

I'm trying to get the code below working so that it will call a JS function to pass a value to my PHP file which will return a number of values from a MySQL database. This is part of an assignment I thought would be quite straightforward but I think my problem is with the JavaScript event handler - how to reference the input value maybe?
The HTML:
<form>
<input type="text" name="users" onkeydown="showUser(this)"/>
</form>
<div id="txtHint">
<p id="responder"><b>Person info will be listed here.</b></p>
</div>
The showUser() function:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("responder").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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("responder").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","php/student_query.php?q="+str,true);
xmlhttp.send();
}
</script>
The PHP:
<?php
$q=$_GET["q"];
// Step 1
$conn = mysql_connect("localhost", "root");
// Step 2
mysql_select_db("collegeData", $conn);
//Step 3
$sql="SELECT * FROM studenttable WHERE studentID = '".$q."'";
$result = mysql_query($sql);
// Step 4
while ($row = mysql_fetch_array($result))
{
// Step 5
echo "Hello $row[firstName] $row[lastName]<br/>";
echo "Your two course modules are $row[moduleNo1] and $row[moduleNo2]<br/>";
echo "<tr><td> $row[firstName]</td><td> $row[lastName] </td> <td> $row[studentID] </td> </tr>";
echo "<br/>";
}
// Step 6
mysql_close($conn);
?>
Like I said, i think my problem is in the event handler, I'm not great with JS. I'd appreciate any help.

Looks like you're sending the input element to your function, not it's value. Try
<input type="text" name="users" onkeydown="showUser(this.value);" />
Also, you should protect your database query from protection by changing your PHP to
$q = mysql_real_escape_string(trim($_GET["q"]));
if($q == "")
{
echo "";
exit;
}

Related

How to get <span id= var

I’m working at a web GUI for an audio mixer. Therefor I have lot of repetitive faders. All looking the same, just differing by ID. The ID is a three digit number. The first digit is provide by the main php page, the other are repetitive in each fader section. I’m trying to get the result back from the server and posting it into a span field. The problem is that the span id depends on the full id.
The span id should be “result111”.Not hardcoded as it is but dynamically generated by the provide id followed by the identifier 11.
GUI php
<script>
function transfer(value,id)
{
if (window.XMLHttpRequest)
{
// AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
xmlhttp=new XMLHttpRequest();
}
else
{
// AJAX mit IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result"+id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","backEnd.php?v="+value+"&id="+id,true);
xmlhttp.send();
return;
}
</script>
backEnd.php
<?php
$id = 10;
$value = 7;
$result = 6;
if ( isset($_GET['id']) )
{
$id = $_GET['id'];
}
if ( isset($_GET['v']) )
{
$value = $_GET['v'];
$result = $value;
}
echo ("$id + $result");
?>
GUI.php
<?php
$id = 1;
include 'fader.php';
?>
fader.php
<script>
var id = <?php echo "$id"; ?>;
function setName (id2){
var fullId =""+ id + id2;
return fullId;
}
function setNameReturn (id2){
var fullIdReturn =""+ id + id2;
return fullIdReturn;
}
</script>
<form oninput="transfer(auswertung.value,setName(11))">
<input type="range" name="auswertung" min="0" max= "63" value="30" orient="vertical">
<br>
<span id="setNameReturn (11)">n.a.</Span>
</form>
You passing value to your function in next way
transfer(auswertung.value,setName(11))
11, while expecting 111
is this your problem?
Update:
Just to be clear, everything you generated in PHP stays in PHP, you need to geenrate JS assignment to pass value to JS. You currently have hardcoded value of 11 at your transfer function, and span result111.
This might work or it might not. It is just an attempt, because you asked me for it in the comments. Have a try and see, what happens.
GUI.php
<?php
$id = 1;
function getSpanId($addedid){
$spanid = $id + $addedid;
return $spanid;
}
?>
<script>
function transfer(value,id)
{
if (window.XMLHttpRequest)
{
// AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
xmlhttp=new XMLHttpRequest();
}
else
{
// AJAX mit IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result"+id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","backEnd.php?v="+value+"&id="+id,true);
xmlhttp.send();
return;
}
</script>
<?php
include 'fader.php';
?>
fader.php
<form oninput="transfer(auswertung.value,<?php getSpanId(11); ?>)">
<input type="range" name="auswertung" min="0" max= "63" value="30" orient="vertical">
<br>
<span id="<?php getSpanId(11); ?>">n.a.</Span>
</form>

php/sql/html: Data dont show in the option field

I'm sorry if this question may sound stupid, but i have one problem with my code that i don't know how solve even though i think it really easy for other people.
I'm making some form when user enter their info (example: username) then the output will shown in the option field (example:responsibility). For your information every username have many responsibility.
The problem is the output is creating many option field and not only one.
below is my php code that related with option field:
<?php
// 3.php is my config file
require("3.php");
$link = mysqli_connect($h,$u,$p,$db);
//if ($link)
//echo "Connection OK";
//else echo "connection failed";
$q = $_GET['q'];
$query="SELECT resp_name FROM view_ss_user_responsibility WHERE user_name ='".$q."'";
$result = mysqli_query($link,$query)
or die("Error: ".mysqli_error($link));
while ($row = mysqli_fetch_array($result)){
$fn=$row[0];
echo "<br>";
//echo "<td>$row[0]</td>";
echo "<tr><td>Responsibility:</td>
<td align=center><form><select><option value='$row[0]'>$fn</option></select></form></td></tr>";
}
echo "</table>";
?>
And also this is the output (i'm using ajax, so no submit button)
if you want to see my html/javascript file:
<html>
<head>
<script>
function showResult(str) {
if (str.length==0) {
document.getElementById("search").innerHTML="";
document.getElementById("search").style.border="0px";
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) {
document.getElementById("search").innerHTML=this.responseText;
document.getElementById("search").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","2.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
username <input type="text" size="30" name ='pass' onkeyup="showResult(this.value)"><br>
<div id="search"></div>
</form>
</body>
</html>
so, base from this i hope someone can tell me on how to do it, thank you.
(why is this getting downvote?.its not like i'm forcing you all to answer it)
Hope it will work fine..
Change this to:
while ($row = mysqli_fetch_array($result))
{
$fn = $row[0];
echo "<br>";
//echo "<td>$row[0]</td>";
echo "<tr><td>Responsibility:</td>
<td align=center><form><select><option value='$row[0]'>$fn</option></select></form></td></tr>";
}
echo "</table>";
This:
echo "<table><tr><td>Responsibility:</td><td><select>";
while ($row = mysqli_fetch_array($result))
{
$fn = $row[0];
echo "<option value='$row[0]'>$fn</option>";
}
echo "</select></td></tr></table>";

AJAX, PHP and multiple variables (Not JQuery)

I have a PHP file that has some radio inputs on them which I wish to use to create a two variables (text string and a integer) via an AJAX (Not JQuery) call which I can use in the PHP file. I can work with a single variable which out puts to "getElementById" but as soon as I add a second, the code fails.
1/ How do I get more than one variable back from the AJAX?
2/ I can work with "getElementById" for collecting the new PHP variables but as I just want to set a couple of PHP variables for use later, I'm not sure this is the best method of collecting the response.
After reading around the web and Stackoverflow, I have got as far as the code below but no success.
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("Div1").innerHTML="";
document.getElementById("Div2").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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var response = (ajaxRequest.responseText).split(';',2);
var intVariable = response[0];
var StringVariable = response[1];
document.getElementById("Div1").innerHTML=xmlhttp.intVariable;
document.getElementById("Div2").innerHTML=xmlhttp.StringVariable;
}
}
xmlhttp.open("GET","ajax_info.php?bookingstate="+str,true);
xmlhttp.send();
}
</script>
<form name='users'>
<radiogroup>
<input type="radio" name="user" value="1" onclick="showUser(this.value)" <?php if ($select_state == '1') echo 'checked="checked"'; ?> >1
<br>
<input type="radio" name="user" value="2" onclick="showUser(this.value)" <?php if ($select_state == '2') echo 'checked="checked"'; ?> >2
<br>
<input type="radio" name="user" value="3" onclick="showUser(this.value)" <?php if ($select_state == '3') echo 'checked="checked"'; ?> >3
<br>
</radiogroup>
</form>
And my ajax_info.php file
<?php
if ($bookingstate == "1") {
$select_state_name = "Booking state: 1";
$select_state1 = "1";
} elseif ($bookingstate =="2") {
$select_state_name = "Booking state: 2";
$select_state1 = "2";
} elseif ($bookingstate == "3") {
$select_state_name = "Booking state: 3";
$select_state1 = "3";
}
echo '$select_state1;$select_state_name;';
?>
you are settings those variables locally so
document.getElementById("Div1").innerHTML=xmlhttp.intVariable;
document.getElementById("Div2").innerHTML=xmlhttp.StringVariable;
should just be
document.getElementById("Div1").innerHTML=intVariable;
document.getElementById("Div2").innerHTML=StringVariable;

Passing a string variable through ajax

The variable is passed through ajax and it is a database name. When the link is clicked it's supposed to retrieve a data from the the database. the link and the variable is on the same page. Here is the code for the link:
$x = strval($_GET['x']);
echo ''.$seatid.'';
The $x variable contains the table name of the database. And here is the code for ajax:
function showInformation(str)
{
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)
{
document.getElementById("txtInfo").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getinfo.php?x="+str,true);
xmlhttp.send();
}
Here is the getinfo.php:
<?php
session_start();
$_SESSION['login']="1";
$x = strval($_GET['x']);
$con = mysql_connect('localhost','root','Newpass123#','seatmapping');
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db('seatmapping');
$sql="SELECT name, seatid FROM $x WHERE seatid = 1";
$result = mysql_query($sql) or die("Query Error " . mysql_error());
...
...
?>
I can't get it to work when i click the link it does not display the data from the table.
Please help me. Any kind of help is appreciated. Thanks in advance..
Can you please try this:
Replace the line
echo ''.$seatid.'';
With the below:
echo ''.$seatid.'';
This will solve your problem.
You are not passing the ID of the expected element.
echo ''.$seatid.'';
Replace this line, instead
echo ''.$seatid.'';

PHP and Ajax using onchange event

I have the following Code in cat.php file:
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsub.php?q="+str,true);
xmlhttp.send();
}
</script>
<select name="users" onchange="showUser(this.value)">
<option value=""></option>
<?php
$query = "SELECT cat from category GROUP BY cat";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num=mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row=mysql_fetch_assoc($result);
echo "<option value=''>".$row['cat']."</option>";
}
echo "</select>";
<div id="txtHint"></div>
And after Calling the function - getsub.php
<?php
require_once('connect_db.php');
//get the q parameter from URL
$q=$_GET["q"];
$query = "SELECT sub from category WHERE cat = '".$q."'";
$result = mysql_query($query);
if(!$result){
mysqli_error();
}
while ($row = mysql_fetch_assoc($result)){
?>
<select name="sub">
<?php
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
echo "<option value='".$row['sub']."'>".$row['sub']."</option>";
}
?>
<select>
<?php
}
I'm looking forward to have a relation between Main Category and Sub Category. I want to Select the Main category and then calling the javascript function in order to show another select input for the Sub Category . The above code outputs nothing and I can't seem to find why?
Please Help
Your code looks fine but you have just a php tag in the end of the while loop that needs to be closed.
Code looks fine. Try using the firebug extension for Firefox.
Open net panel in firebug and then see what data are you sending and what response in actually generating.
This will definitely help.
Also in cat.php, instead of using plain AJAX, try using jQuery as this will reduce large line of code as
// Just incude jQuery beforehand
script>
function showUser(str)
{
$.get("getsub.php",{q:str},function(data){
$("#txtHint).html(data);
});
}
</script>

Categories