Variable not working in PHP [closed] - php

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I am retrieving data from database using AJAX and PHP. In database one of the columns contains path of an image folder. I am saving the value of path in a PHP variable named as $folder. This can be seen in getuser.php code. I want this variable to be visible/available in one.php so that my images using this variable could be populated. How would i do this. I have tried including php as well but no use.
getuser.php
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'san', '123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("holidayNet", $con);
$sql="SELECT * FROM image WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Picture</th>
</tr>";
while($row = mysql_fetch_array($result))
{
$folder = $row['FirstName'];
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
/*echo "<td>" . $row['Job'] . "</td>";*/
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
one.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
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","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Sn Qb</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div><br />
<img src="<?php echo $folder;?>/pic1.jpg" />
<img src="<?php echo $folder;?>/pic2.jpg" />
<img src="<?php echo $folder;?>/pic3.jpg" />
<img src="<?php echo $folder;?>/pic4.jpg" />
</body>
</html>

Hey you are creating a variable name $folder in the PHP file (getuser.php) which is getting called by AJAX. But its not available in the file name one.php.
Only what you echo from getuser.php will be available in the JS variable xmlhttp.responseText
So you will get all the Person Info echoed in the getuser.php, but wont get the $folder variable.
Since you have specifically hardcoded 4 images. I suggest you to echo the img tags too in the getuser.php along with the other information from the database of the person selected.
while($row = mysql_fetch_array($result))
{
$folder = $row['FirstName'];
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
/*echo "<td>" . $row['Job'] . "</td>";*/
echo "</tr>";
}
echo "</table>";
for($i = 0; $i < 4; $i++)
{
echo '<img src="'.$folder.'/pic'.($i+1).'.jpg" />';
}
And remove those image tags from the one.php page
The other Solution:
Suggestion which I can give is to add some separator to differentiate between the 2 things. One is the table which you want to print and the $folder variable value.
For eg: consider separator ####
Step 1:
So now your code from the getuser.php will be
while($row = mysql_fetch_array($result))
{
$folder = $row['FirstName'];
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
/*echo "<td>" . $row['Job'] . "</td>";*/
echo "</tr>";
}
echo "</table>####".$folder;
Step 2:
Changes in the one.php to separate the 2 values
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// split is the function which breaks the string with the value provided and then creates an array of the parts.
var arrResponse = (xmlhttp.responseText).split("####");
// added || below to validate the index 1 of arrResponse. if xmlhttp.responseText does not have #### it wont break the string and hence wont have the folderName part, in such cases javascript will give undefined value, by adding || we tell if value is present take the present value otherwise take it as an empty string ''
var folderName = arrResponse[1] || ''
document.getElementById("txtHint").innerHTML=arrResponse[0];
// we will fetch all the image tags from your html page
var arrImgs = document.getElementsByTagName('img');
var imgCount = arrImgs.length;
for(i = 0; i < imgCount; i++)
{
arrImgs[i].setAttribute('src', folderName+'/pic'+(i+1)+'.jpg');
}
}

What you are doing wrong is that you are mixing things together, specially PHP and HTML, I can explain better if you would like, but for the moment I will only try to explain a solution to your problem, I hope this would be okay for you.
1/ the $folder will not be reachable from the one.php
2/ to get the information from the $folder you would better get it within the Ajax Query, and then you can use Javascript function to change the attribute
3/ another solution is, since you are generating the the html code for the table in the getuser.php, you can also generate some more lines with the images tages included
Did I explain well ? please if not, I'm ready to try again :)
Best of luck

Upon your request, I will tell you a possible solution using the same way you did it before
first of all, you will need to change your both files
1/ go to getuser.php and remove all the echo, store the strings in a variable instead
2/ than, after the loop create an indexed array with your both variables ($folder and the new variable which contains the html string)
3/ after that you can encode the array in json format, with the "json_encode" function (available since PHP5)
4/ all what you still have to do, is in the one.php page, when getting the result you need to decode the string you get with the "eval" function (a native Javascript function), this function will return an indexed array (with the same indexs) and put the html string in the "txtHint" div, use the content of other variable in your images tags (using javascript functions)
was that clear enough to follow ? (sorry my english is not that good :( )

Related

Getting the drop-down menu selected item and using it in php

I have the following drop-down list that fetches a list coalitions from the database (this list is populated as expected)
<form style = "display: inline-block;" >
<select class="form-control" name ="coalition_select" onchange = "showCandidates(this.value)" method="GET">
<option id = "coalition_id" value="coalition">Coalitions</option>
<?php
include_once 'connection.php';
$sql_coalition = mysqli_query($conn, "SELECT coalition FROM candidates");
while ($row = $sql_coalition->fetch_assoc()) {
echo "<option value=\"coalition\">" . $row['coalition'] . "</option>";
}
?>
</select>
</form>
The problem begins here. Here I'm trying to first get the selected value (which is on of the coalitions) from the drop-down list and second use the value to display users with similar coalition attribute.
here is the script to get the value from the drop-down:
<script>
function showCandidates (str) {
if (str.length == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","includes/admin.users.list.inc.php?q="+str,true);
xmlhttp.send();
}
}
</script>
and here is the admin.users.list.inc.php file
<body>
<?php
$q = $_GET['q'];
$conn = mysqli_connect('localhost','root','','voting');
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
mysqli_select_db($conn,"osako_Voting");
$sql="SELECT * FROM candidates WHERE coalition = '".$q."'";
$result = mysqli_query($conn,$sql);
echo "<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Coalition</th>
<th>Email</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['coalition'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
</body>
The problem seem to be that I'm unable to set the variable $q so that it captures the selected value. right now as it is set it seems to capture the index instead of the value itself. How can this be correctly done? If it is of any help, I'm using this tutorial as a guideline
https://www.w3schools.com/php/php_ajax_database.asp
IN SUMMERY:
If we have a drop-down list that has been populated dynamically using php script. How can be get the selected value using ajax and use the said value in another php script.
Thanks
It seems the problem is in this row:
echo "<option value=\"coalition\">" . $row['coalition'] . "</option>";
You're passing the select value to showCandidates(), to be passed via AJAX but you're setting the option value to be always static "coalition" and not the dynamic values you're fetching from DB.
Maybe you should change the row to
echo "<option value=\"" . $row['coalition'] . "\">" . $row['coalition'] . "</option>";
your not setting value to value attribute . your just setting constant string for all option values coalition
while ($row = $sql_coalition->fetch_assoc()) {
echo "<option value=\"$row['coalition']\">" . $row['coalition'] . "</option>";
}
I know you have accepted an answer but i am puzzled as to this;
in your function you have this
document.getElementById("txtHint").innerHTML = "";
But you don't have any form element with the id "txtHint"
So what element is being sort with that ID?

Ajax refine search

I have a table for a sports day where there are 4 columns name, house, event, result. I have no problem creating and displaying the database but i want to be able to search in a bar and to use AJAX to automatically search all 4 columns for whats in the search bar. I am using PHPmyadmin to store the database with mySQLI. i am able to display the database on the page that i want. I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search. I have never used Ajax before so sorry for my bad code as it is all from w3schools site. the DB is called sports_day and the table is called full_results. here is my current code.
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","results_query.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
and on a page called results_query.php is this code
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql="SELECT * FROM full_results WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
at the moment what happens is none of the table is shown and when i type anything in the search box the whole table appears along with in plain text at the bottom the title and all the contents of the table in a long line.
any suggestion to get my code to work would be greatly appreciated!
thanks!
The solution would be like this:
Keep your HTML search form as it is.
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
... I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search.
See this <div> section here,
<div class="col-sm-12">
...
</div>
You didn't put anything in this <div> section. First of all, you have to display your entire table in this section, which you can later filter out using the AJAX request. Also, assign an id to this <div> section so that it could be easier for you put the AJAX response in this <div> section. So the code for this <div> section would be like this:
<div class="col-sm-12" id="pupil-info">
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</div>
Change your Javascript/AJAX code in the following way,
<script>
function showUser(str){
var str = str.trim();
var xmlhttp;
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("pupil-info").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","results_query.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
</script>
Please note that you should encode the user inputted str value using encodeURIComponent() function before passing it to the results_query.php page.
Finally, on results_query.php page process your AJAX request like this:
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
if(isset($_GET['q']) && !empty($_GET['q'])){
$sql .= " WHERE CONCAT(id, NAME, HOUSE, EVENT, RESULT) LIKE '%".$_GET['q']."%'";
}
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
}else{
echo "<tr>";
echo "<td colspan='4' style='text-align:center;'>No records found</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.
If you use your 'results_query.php' file only for getting the data from database, then you don't need to create a <body> tag. If you use only PHP then you can easily skip any plane HTML. That's just a digression :)
But to the point.
You can change the way you return your data from database. I think, instead of doing a lot of echo's it is better to add result to the variable and echoing the variable at the end.
$data = '<tr>' . '<th>NAME</th>' . '<th>HOUSE</th>' . '<th>EVENT</th>' . '<th>RESULT</th>' . '</tr>';
while($row = mysqli_fetch_array($result)) {
$data .= '<tr>';
$data .= '<td>' . $row['NAME'] . '</td>';
$data .= '<td>' . $row['HOUSE'] . '</td>';
$data .= '<td>' . $row['EVENT'] . '</td>';
$data .= '<td>' . $row['RESULT'] . '</td>';
$data .= '</tr>';
}
$data .= '</table>';
mysqli_close($con);
echo $data;
See if this changes something.
What about showing entire table after the page's loaded, you will have to change both PHP and JavaScript code a little bit.
You can change your JS so it gets everything from your full_results table after page is loaded.
There are several ways to do this and you can read about them here:
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
The easiest way would be to do this this way:
<script>
function showUser(str) {
var url;
var xmlhttp;
if (str == "") { //if empty string - get all data
url = "results_query.php";
} else { //get particular data otherwise
url = "results_query.php?q="+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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
<script>
//calling your function with empty string because we want to get all data
showUser("");
</script>
and in the PHP file you can do something like this:
<?php
$q = 0;
//check if 'q' parameter was passed
if(isset($_GET['q'])) {
$q = intval($_GET['q']);
}
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results";
Now your JavaScript function will be called after loading your page.
It will call your PHP script with AJAX and this script should return all data from your table.
In line ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results"; there is a simple check if $q is different from 0. Our variable will be set to 0 if no argument was passed, so whenever $q is equal to '0', we just want to get all the data from full_results and specific data otherwise.
I also added var xmlhttp because it is only local variable.
You can read more about that in here:
https://stackoverflow.com/a/1471738/7301294
I hope it will help you.
Let me know if you have any other problems and never be afraid to ask.
Good luck!

retrieve data using Ajax and mysql

I'm trying to retrieve data from multiple table. So when the user clicks and select an item php file to retrieve the data from the corresponding table.
this is my first try on Ajax used w3 school code and trying to modify, I guess the way I'm using if condition is the problem? Before I try with the multiple table it worked.
My Script
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "Please Select type of users to view";
return;
} else {
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","get_users.php?q="+str,true);
xmlhttp.send();
}
}
</script>
My Form
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Staff</option>
<option value="2">Admin</option>
<option value="3">Customers</option>
</select>
</form>
My PHP Page
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','X','X','X');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con);
if ($q='Admin')
{
$sql="SELECT * FROM admin";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Email</th>
<th>Name</th>
<th>Mobile</th>
<th>Address</th>
<th>Password</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['mobile'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
}
echo "</table>";
else if ($q='Staff')
{
echo "This is from Database B
}
else
{
echo "This is from database C";
}
mysqli_close($con);
?>
You're using $q = intval($_GET['q']); with a string value for your assignments.
intval() "Get the integer value of a variable"
<option value="1">Staff</option>
<option value="2">Admin</option>
<option value="3">Customers</option>
and using an assignment rather than a comparison for both if ($q='Admin') and else if ($q='Staff') both being strings, as opposed to integers in your options.
which should read as and with 2 equal signs if ($q=='2') and else if ($q=='1') in order to match your select's numerical value options.
Or, change them accordingly with your options to read as Staff and Admin (and Customers) in the values, while removing the intval() from the GET array; the choice is yours.
You also don't need mysqli_select_db($con); since you've declared your 4 parameters in your initial connection and would fail for another reason; technically you didn't select a database for it.
You're also missing a quote and semi-colon in (a parse syntax error)
echo "This is from Database B
which should read as
echo "This is from Database B";
Footnotes:
The page which I believe you based yourself on, seems to be http://www.w3schools.com/php/php_ajax_database.asp
If so, then I suggest you follow their example completely and modify it slowly to fit your needs. I myself have used that demo (in the distant past) before with success.
Their example uses a WHERE clause also.
$sql="SELECT * FROM user WHERE id = '".$q."'";
Edit: Just for the record, there is a missing brace for this condition:
if ($q='Admin')
{

Error when using drop menu to change database value

When i select a drop menu option to change a value in my database to the selected value it gives this error:
SyntaxError: missing ) after argument list changeGroup("email#email.com")
Basically what im trying to do is I have an app that stores contacts, in the ungrouped contacts section it has the drop menu and when u select a value from it it submits the values and uses the value to update the database. I use the:
action='javascript:changeGroup(".$contactDetails.")
to tell the update statement which contact to update.
my code:
<!--Include Database connections info-->
<?php include('config.php'); ?>
<!--Links to CSS file for formatting-->
<link href="Contacts.css" rel="stylesheet" type="text/css"/>
<!--Links to Javascript file for the for action to change the group of a contact-->
<script src="ajax.js" language="javascript"></script>
<?php
$contactDetails = $_GET['contactDetails'];
$cdquery="SELECT * FROM `contacts` WHERE `newEmail` = '$contactDetails'";
$cdresult=mysql_query($cdquery) or die ("Query to get data from first table failed: ".mysql_error());
while ($row = mysql_fetch_assoc($cdresult))
{
echo "" . $row['newFname'] . " " . $row['newLname'] . "'s " . "Details:";
echo "<table>";
echo "<tr>";
echo "<th>Name:</th>";
echo "<th>Email Address:</th>";
echo "<th>Phone:</th>";
echo "<th>Postal Address:</th>";
echo "<th>Group:</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['newFname'] . " " . $row['newLname'] . "</td>";
echo "<td>" . $row['newEmail'] . "</td>";
echo "<td>" . $row['newPhone'] . "</td>";
echo "<td>" . $row['newAddress'] . "</td>";
echo "<td>" . $row['group'] . "</td>";
echo "</tr>";
}
echo "</table>";
echo "<form action='javascript:changeGroup(".$contactDetails.")' method='get'> Add contact to
<select id='group' name='group' onchange='this.form.submit(value=this.options[this.selectedIndex].value)'>
<option>Select a group...</option>
<option value='Family'>Family</option>
<option value='Friends'>Friends</option>
<option value='Colleagues'>Colleagues</option></select>
group.</form>";
mysql_close($link);
?>
ajax function:
function changeGroup(str)
{
document.getElementById("content02").innerHTML="";
if (str=="")
{
document.getElementById("content02").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("content02").innerHTML=xmlhttp.responseText;
document.getElementById("content02").innerHTML = "";
}
}
xmlhttp.open("GET",'getChangeGroup.php?contactChange='+contactChange+'&group='+group,true);
xmlhttp.send();
xmlhttp.onreadystatechange = changeReload;
xmlhttp.send(null);
}
php:
<!--Include Database connections info-->
<?php include('config.php'); ?>
<!--Links to CSS file for formatting-->
<link href="Contacts.css" rel="stylesheet" type="text/css"/>
<?php
$contactChange = $_GET['contactChange'];
$group = $_GET['group'];
$cdquery="UPDATE `contacts` SET `group` = '$group' WHERE `newEmail` = '$contactChange'";
$cdresult=mysql_query($cdquery) or die ("Query to get data from first table failed: ".mysql_error());
mysql_close($link);
?>
I don't really know what your code does, nor do I have the patience to completely replicate it on my end, but as it stands you are passing a variable to your function, instead of a string, on this line:
echo "<form action='javascript:changeGroup(".$contactDetails.")' method='get'> Add contact to
To fix that, you need to quote your string as an actual string:
echo "<form action='javascript:changeGroup(\'".$contactDetails."\')' method='get'> Add contact to
I would assume this is your main issue. Without those quotes, javascript treats your echoed variable as a js variable, instead of a string.
In regards to your db interaction...
Also, you are using a deprecated.. and soon to be removed database interaction API. I recommend PDO to replace it, it prevents injection attacks and won't be removed in the near future, learn more about it here.

dojo1.8 - Not sure how to read the selected value and post to php file, using dojo/request

Hi I have problem getting the value of select node posted and get nothing.
I am using dojo/request. And the getuser1.php at the server is working when I tested with simple ajax file.
At the request line, the values for data may not be correct
Please advise... Thanks
Following are two scripts:-
main.php file -
require(["dojo/parser", "dojo/ready","dijit/form/Select",
"dojo/request","dojo/on","dojo/domReady!"],
function(parser, ready, Select, request, on){
ready(function(){
console.debug('Rendering...');
var selectX = new Select({
name:'select_test',
options:[
{label:"<span class='NotinUse'><b>&nbsp&nbsp&nbsp. . .</b></span>", value:'0', selected:true},
{label:"<span class='inUse'><b>&nbsp&nbspPeter Griffin</b></span>", value:'1'},
{label:"<span class='inUse'><b>&nbsp&nbspLois Griffin</b></span>", value:'2'},
{label:"<span class='inUse'><b>&nbsp&nbspJoseph Swanson</b></span>", value:'3'},
{label:"<span class='inUse'><b>&nbsp&nbspGlenn Quagmire</b></span>", value:'4'},
],
style:{width:'150px'}
},"select");
on(formNode2, 'Change', function(evt){
evt.stopPropagation();
evt.preventDefault();
request.post('getuser1.php',{
data:{select_test:this.value},
timeout:2000
}).then(function(response){
dom.byId('line2').innerHTML=response;
});
});
});
});
getuser1.php file:-
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = $q";
$result = mysql_query($sql);
// use stored function to return one result instead later. Write here after stored procedure has been stored.
echo "<table border='1'>
<tr>
<th width=100>Firstname</th>
<th width=100>Lastname</th>
<th width=100>Age</th>
<th width=100>Height</th>
<th width=100>Hometown</th>
<th width=100>Job</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "<td>" . $row['Age'] . "</td>";
echo "<td>" . $row['Height'] . "</td>";
echo "<td>" . $row['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Remember to use your browser's error console when developing, it will often notify you of simple typos etc in your code.
In this case, there are a few things wrong. It seems you've mixed up selectX and formNode2. It should presumably be:
on(selectX, 'Change', function(evt){
Now, if you get this to work, you'll notice that when you change selectX's value, you'll get an error in your console:
evt.stopPropagation is not a function
This is because the evt argument is not actually an event object here. From select elements, you only get the new value, not the event. Change it to something like this, and you should see what I mean in the console:
on(selectX, 'Change', function( newValue ){
console.debug('The new value is', newValue);
//evt.stopPropagation();
//evt.preventDefault();
I made a few changes to make it work in jsfiddle, but it should give you an idea: http://fiddle.jshell.net/AmxKv/

Categories