Autocomplete Textbox results based from SQL database - php

I'm trying to create an auto-complete function into a textbox but the result should come from my SQL database.
Here's the code that i'm trying to configure:
index.php:
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Autocomplete - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var availableTags = [
"autocomplete.php"; ];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
EDIT: I changed the content of variable availableTags and made it into var availableTags = <?php include('autocomplete.php') ?>;
Variable availableTags is the source of words, so I try to change it and instead put a file name where fetching of words from my database is happening.
Here's my autocomplete.php file:
<?php
include('conn.php');
$sql="SELECT * FROM oldemp";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
while($row=mysqli_fetch_array($result))
{
echo "'".$row['name']."', ";
}
?>
EDIT: Also changed the content of the while loop and made it into
$name=mysqli_real_escape_string($con,$row['name']);
$json[]=$name;
How can I insert the fetched words from autocomplete.php into availableTags variable?
EDIT/UPDATE: There's a list showing up whenever I type something on the textbox, but it has no text in it. I know it's fetching, but the word itself is not showing on the list.

The jQuery UI autocomplete can take 3 different types of values of the source option:
An array containing the list of things to fill in the auto complete with
A string containing the URL of a script that filters a list and sends us the results. The plugin will take text typed into it and send it as a term parameter in a query-string appended to the URL we provided.
A function that retrieves the data and then calls a callback with that data.
Your original code uses the first, an array.
var availableTags = [
"autocomplete.php";
];
What that tells the autocomplete is that the string "autocomplete.php" is the only thing in the list of things to autocomplete with.
I think what you were trying to do is embed it with something like this:
$(function() {
var availableTags = [
<?php include("autocomplete.php"); /* include the output of autocomplete as array data */ ?>;
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
That would probably work okay assuming that the list of things that are being returned from the database will always remain short. Doing it this way is kind of fragile though since you are just shoving raw output from PHP into your JS. If the returned data contains " you might have to use addSlashes to escape it correctly. You should however change the query to return a single field rather than *, you probably only want one field as the label in the autocomplete not the entire row.
A better approach, especially if the list could potentially grow very large, would be to use the second method:
$(function() {
var availableTags = "autocomplete.php";
$( "#tags" ).autocomplete({
source: availableTags
});
});
This will require you to make a change to the back-end script that is grabbing the list so that it does the filtering. This example uses a prepared statement to ensure the user provided data in $term doesn't open you up to SQL injection:
<?php
include('conn.php');
// when it calls autocomplete.php, jQuery will add a term parameter
// for us to use in filtering the data we return. The % is appended
// because we will be using the LIKE operator.
$term = $_GET['term'] . '%';
$output = array();
// the ? will be replaced with the value that was passed via the
// term parameter in the query string
$sql="SELECT name FROM oldemp WHERE name LIKE ?";
$stmt = mysqli_stmt_init($mysqli);
if (mysqli_stmt_prepare($stmt, $sql)) {
// bind the value of $term to ? in the query as a string
mysqli_stmt_bind_param($stmt, 's', $term);
mysqli_stmt_execute($stmt);
// binds $somefield to the single field returned by the query
mysqli_stmt_bind_result($stmt, $somefield);
// loop through the results and build an array.
while (mysqli_stmt_fetch($stmt)) {
// because it is bound to the result
// $somefield will change on every loop
// and have the content of that field from
// the current row.
$output[] = $somefield;
}
mysqli_stmt_close($stmt);
}
mysqli_close($mysqli);
// output our results as JSON as jQuery expects
echo json_encode($output);
?>
It's been a while since I've worked with mysqli, so that code might need some tweaking as it hasn't been tested.
It would be good to get into the habit of using prepared statements since when properly used, they make SQL injection impossible. You can instead use a normal non-prepared statement, escaping every user-provided item with mysqli_real_escape_string before you insert it into your SQL statement. However, doing this is very error-prone. It only takes forgetting to escape one thing to open yourself up to attacks. Most of the major "hacks" in recent history are due to sloppy coding introducing SQL injection vulnerabilities.
If you really want to stick with the non-prepared statement, the code would look something like this:
<?php
include('conn.php');
$term = $_GET['term'];
$term = mysqli_real_escape_string($mysqli, $term);
$output = array();
$sql = "SELECT name FROM oldemp WHERE name LIKE '" . $term . "%';";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
while($row=mysqli_fetch_array($result))
{
$output[] = $row['name'];
}
mysqli_close($mysqli);
// output our results as JSON as jQuery expects
echo json_encode($output);
?>

When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data.
source: "autocomplete.php"
Therefore you need to return a JSON object.
$json = false;
while($row=mysqli_fetch_array($result))
{
$json[] = array(
'name' => $row['name']
);
}
echo json_encode($json);

Your autocomplete.php file,
include('conn.php');
$sql="SELECT * FROM oldemp";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
//Create an array
$arr = Array();
while($row=mysqli_fetch_array($result))
{
array_push($arr,$row['name']);
}
header('Content-Type: application/json');
echo json_encode($arr)
?>
The result of this will be an JSON array which can be directly used in JavaScript.
Hence, the script will be something like -
var availableTags = [];
$.ajax({
url:"autocomplete.php",success:function(result){
availableTags = result
}});

Solved my problem.
Have the script like this:
<!-- WITHOUT THESE THREE BELOW, THE AUTOCOMPLETE WILL LOOK UGLY OR WILL NOT WORK AT ALL -->
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#tags" ).autocomplete({
source: "autocomplete.php"
});
});
</script>
And autocomplete.php (where we will get the data to fill the autocomplete input field):
<?php
include("conn.php"); /* ESTABLISH CONNECTION IN THIS FILE; MAKE SURE THAT IT IS mysqli_* */
$stmt = $con->prepare("SELECT description FROM table"); /* START PREPARED STATEMENT */
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->bind_result($description); /* BIND THE RESULT TO THIS VARIABLE */
while($stmt->fetch()){ /* FETCH ALL RESULTS */
$description_arr[] = $description; /* STORE EACH RESULT TO THIS VARIABLE IN ARRAY */
} /* END OF WHILE LOOP */
echo json_encode($description_arr); /* ECHO ALL THE RESULTS */
?>

Just a suggestion for the autocomplete file. Sorry, I would have added a comment above, but I don't have enough rep as of writing this.
After successfully implementing Useless Code's suggestion I was noticing my server overhead was going through the roof. It seemed bots were some how initiating the script, even though there was no letters being typed in the input area. I did a little test on the autocomplete file and found it would query my database even if the term was empty.
So, I just encpsulated the whole autocomplete script with an if statement... like so...
<?php
if(!empty($_GET['term']))
{
include('conn.php');
$term = $_GET['term'];
$term = mysqli_real_escape_string($mysqli, $term);
$output = array();
$sql = "SELECT name FROM oldemp WHERE name LIKE '" . $term . "%';";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error());
while($row=mysqli_fetch_array($result))
{
$output[] = $row['name'];
}
mysqli_close($mysqli);
// output our results as JSON as jQuery expects
echo json_encode($output);
}
?>
... and now my server is back to normal.

Related

PHP & jQuery - Create two different textfields with autocomplete having different lists of data retrieved from the database

Customer textfield with autocomplete from database
I succeeded to create one Customer textfield with autocomplete to display customers which start by the text being typed.
index.php for one textfield
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#customer" ).autocomplete({
source: "../phpfiles/search.php",
});
});
</script>
<div class="ui-widget">
<!-- action='./../customer_report_request' -->
<form id="customer_report_request" name="customer_report_request" method="post">
<table>
<tr>
<th colspan='2'>Search Customer</th>
</tr>
<tr>
<td>
<label>Customer: </label>
<input name="customer" id="customer" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_customer_request">
</td>
</tr>
</table>
</form>
</div>
<?php
//Display the list of customer details
if(isset($_POST['send_customer_request']))
{
include 'db.php'; //connection
$query = "SELECT * FROM customer WHERE Company_Name = '".$_POST['customer']."'";
$customer_result = $db->query($query);
$count_customer = $customer_result->num_rows;
if($count_customer>0)
{
echo"<div>";
echo "<table>";
echo"<tr>";
echo"<th>Company_Name</th>";
echo"<th>VAT_Registration</th>";
echo"<th>Contact_First_Name</th>";
echo"<th>Contact_Last_Name</th>";
echo"<th>Email</th>";
echo"</tr>";
while ($row = $customer_result->fetch_assoc())
{
echo"<tr>";
echo"<td>".$row['Company_Name']."</td>";
echo"<td>".$row['VAT_Registration']."</td>";
echo"<td>".$row['Contact_First_Name']."</td>";
echo"<td>".$row['Contact_Last_Name']."</td>";
echo"<td>".$row['Email']."</td>";
echo"</tr>";
}
echo "</table>";
echo"</div>";
}
$db->close();
}
?>
Search.php for one textfield
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from customer table
$query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with
while ($row = $query->fetch_assoc()) {
$data[] = $row['Company_Name'];
}
//return json data
echo json_encode($data);
?>
The problem is I want to use a single search php file to cater for other queries.
For example:
If a word is typed in the Contact textfield, the query will be
"SELECT * FROM Contact...."
If a word is typed in the Customer textfield, the query will be
"SELECT * FROM Customer...."
Both index.php and search.php were modified to achieve this.
Modified part in index.php
A jQuery variable, component_name was defined. On change from the index.php file, the customer texfield will send the variable to search.php file using a POST method so that it can be identified and used for query purposes.
The contact textfield can be either in the same form in the index.php file or in another php file.
<script>
$(function() {
$( "#customer" ).autocomplete({
var component_name= "customer";
source: "../phpfiles/search.php",
minLength: 1,
change: function(event, ui)
{
$.post("../phpfiles/search.php", data{post_data: component_name});
}
});
});
</script>
Modified search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query="";
if($_POST['post_data']=="customer")
{
$query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with
while ($row = $query->fetch_assoc())
{
$data[] = $row['Company_Name'];
}
//return json data
echo json_encode($data);
}
?>
Can anyone help me to achieve this?
I used these links for the jquery-ui and jquery api parts:
api.jquery.com
jqueryui.com
This may be a little complicated ad I hope it helps. Your example does not provide any example data or schema to your DB, so I had to make a number of guesses. You'll need to adjust.
Consider if you have different input fields, you could have:
HTML
<div class="ui-widget">
<form id="customer_report_request" name="customer_report_request" method="post">
<table>
<tr>
<th colspan='2'>Search Customer</th>
</tr>
<tr>
<td>
<label>Customer: </label>
<input class="entry-field" name="customer" id="customer" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_customer_request">
</td>
</tr>
<tr>
<td>
<label>Contact: </label>
<input class="entry-field" name="contact" id="contact" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_ccontact_request">
</td>
</tr>
</table>
</form>
</div>
JavaScript
$(function() {
$(".entry-field").autocomplete({
source: function(req, resp) {
// determine which field we're working with
var type = $("this").attr("id");
// collect the entry in the field
var term = req.term;
// Prepare our response array
var responses = [];
// PErform POST Request to our Search and accept JSON results
$.ajax({
url: "../phpfiles/search.php",
data: {
t: type,
q: term
},
type: "POST",
dataType: "JSON",
success: function(results) {
$.each(results, function(key, val) {
responses.push(val);
});
}); resp(responses);
},
minLength: 1
}
});
$("#customer_report_request").submit(function(e) {
e.preventDefault();
if ($("#customer").val().length) {
// perform POST to a PHP search for that specific customer details
} else {
// performn a post to a PHP search for that specific contact details
}
// populate result DIV on page with resulting data from POST
});
});
PHP: search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
// get search query
$searchTerm = $_POST['q'];
// get search type
$searchType = $_POST['t'];
//get matched data from customer table
if($searchType == "customer"){
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT * FROM customer WHERE Company_Name LIKE '?%'");
} else {
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT * FROM customer WHERE Contact_Name LIKE '?%'");
}
/* bind parameters for markers */
$stmt->bind_param("s", $searchTerm);
/* execute query */
$stmt->execute();
/* instead of bind_result: */
$result = $stmt->get_result();
while ($row = $results->fetch_assoc()) {
if($searchType == "company"){
$data[] = $row['Company_Name'];
} else {
$data[] = $row['Contact_Name']
}
}
//return json data
header('Content-Type: application/json');
echo json_encode($data);
?>
So there is a lot going on. Will start with your PHP. It was vulnerable to SQL Injection, so I made use of MySQLi Prepare to protect things. We are expecting data to be posted to this script, and we're expecting to conditions: query and type. If we do not get a type, we can set defaults. Might want to add a check for query, but it should always have 1 character.
We get this data to our Search script using the function method for the source option. See more: http://api.jqueryui.com/autocomplete/#option-source
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
So with this, we can add to our $.ajax() call and make use of the error callback. Basically, we've end up sending an empty array back to response.
So we send a send a search term to PHP, we get JSON array data back, we pipe this into our own array to send back to response, and the user will get a list of results.
It's still a little clunky and that's ok if that's what you're users are used to. You can slim it down and also categorize your results. This way you can have one search field. Also once something is selected or the field is change, you can then use AJAX again to pull those details from another PHP that harvests all the data from the DB. This would result in not having to wait for the page to load again etc.
I hope this answer your question and I suspect it will raise more too. Keep searching around, there are lots of answers. Sometimes it's easier to break a big problem down into smaller single questions than to tackle the whole.

Get value from dropdown list to use in MySQL query

So I'm having this issue with geting a value from a dropdown list in HTML into a variable so that I can do the mysql query. This will be a little tricky to explain but I will do my best. (Do not be shy in correcting my english or my expressions so that the question becomes more concrete and easy to understand).
So I have this dropdown list that gets his values from a mysql query.
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
This "connects" with this query:
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'");
$result4 = mysql_query($sql4, $link);
This query will populate the dropdown list with values. What I'm seeking to do is to populate another dropdown list. For examples I select a list of countrys, and when I select on country it should appear all it's citys in the other dropdown list.
I have been searching guys. Belive me I have.
P.s: Please do not get mad if I change the question a couple of times when I see that you guys show me a way to explain it better. Sorry if my english isn't perfect. Thank you guys for the help.
You can do it with ajax and jquery. I try to write little example
<!-- index.php -->
<select name="desig_act" id="desig_act">
<?php while ($row2 = mysql_fetch_assoc($result4)): ?>
<option value="<?=$row2['new_name_freg']?>">
<?=$row2["new_name_freg"]?>
</option>
<?php endwhile; ?>
</select>
<!-- select tag for countries -->
<select name="country" id="country"></select>
write a little script to return countries as json
<?php //ajax-countries.php
$link = mysql_connect(); // connect as usual
$query = ("SELECT * FROM countries");
$result = mysql_query($query, $link);
$json = array();
while ($row = mysql_fetch_assoc($result)) $json[] = $row;
echo json_encode($json);
?>
Then you can have some sort of script like:
// script.js
$("#desig_act").change(function(){
$.getJSON( "ajax-countries.php", function( data ) {
$.each( data, function(key, val) {
$("#desig_act").append("<option val='" + key + "'>" + val + "</option>");
});
});
I hope it can be useful
1: Create a PHP script to return the data
Essentially just generate the value based off the $_GET input.
2: Create a json request in jquery
Calls the PHP file which will return the data and you will use that data to add more values to the select.
<?php
//Step 1 - The posted ajax data that will return our json request.
if(isset($_GET['fetchrow'])) //Is our ajax request called on page load? If yes, go to this code block
{
//Other stuff like DB connection
$pesq = mysql_escape_string($_GET['fetchrow']); //Put our variable as the variable sent through ajax
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'"); //Run our query
$result4 = mysql_query($sql4, $link); //Please change from mysql_* to mysqli
$data = array(); //The array in which the data is in
while($row = mysql_fetch_assoc($result4)) //Look through all rows
{
array_push($data, $row); //Put the data into the array
}
echo json_encode($data); //Send all the data to our ajax request in json format.
die; //Don't show any more of the page if ajax request.
}
?>
<html>
<head>
<script type='application/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js'></script> <!--Include jquery -->
<script>
//Step #2:
//The jquery script calls ajax request on change of the first select
$( "#desig_act" ).change(function() {
$.getJSON('thisfilename.php', {fetchrow:$("#desig_act").val()}, function(data){ //Get the json data from the script above
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) { //Loop through all results
html += '<option value="' + data[i].new_name_freg + '">' + data[i].new_name_freg + '</option>'; // Add data to string for each row
}
$('#otherselect').html(html); //Add data to the select.
});
});
</script>
</head>
<body>
<!-- Your html code -->
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
</td>
<!-- The new select -->
<select name='otherselect' id='otherselect'>
</select>
<!-- Rest of html code -->
</body>
</html>

URlencode with php dynamic drop downs

I'm working to try and establish a "safe" dynamic form using php/jquery. I am trying to figure out how to encode a query result in the URL, but also being able to display the query correctly in the browser. Ive tried wrapping a urlencode around the data in each of the for loops but it outputs the encoded data and disables the ability to populate the second drop down.
<!-- Populate First Dropdown -->
<select id="first-choice" name="cardset">
<?php foreach ($data as $row): ?>
<option><?=htmlentities($row["name"])?></option>
<?php endforeach ?>
</select>
<br />
<!-- Populate Second Dropdown -->
<select id="second-choice" name="card">
<option>Please choose from above</option>
</select>
<!-- Jquery to Populate second and Produce image -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language=JavaScript >
$(document).ready(function(){
$("#first-choice").change(function() {
$.get("getter.php", { choice: $(this).val() }, function(data) {
$("#second-choice").html(data);
});
});
$("#second-choice").change(function() {
var first = $("#first-choice").val();
var sec = $(this).val();
$("#image-swap").attr("src", (first !== "" && + sec !== "") ? "pics/" + first + "/" + sec + ".jpg" : "");
});
});
</script>
Here is the getter.php file I use to populate second drop down using above jquery:
$choice = $_GET['choice'];
$sth = $db->prepare("SELECT code FROM sets WHERE name='$choice'");
$sth->execute();
$choicecode = $sth->fetchColumn();
$stmt = $db->prepare("SELECT * FROM cards WHERE code='$choicecode'");
$stmt->execute();
$data2 = $stmt->fetchAll();
?>
<?php foreach ($data2 as $row): ?>
<option><?=$row["cardname"]?></option>
<?php endforeach ?>
Basically I want to encode the data that goes in the drop downs because they contain spaces and apostrophes. How can I still do this while at the same time output them correctly?
urlencode should be used when you're constructing the query parameters in a URL. When you're putting text into HTML, you should use htmlentities. Also, use the ID column as the value in your options.
<?php foreach ($data as $row): ?>
<option value="<?=$row["id"]?>"><?= htmlentities($row["name"]) ?></option>
<?php endforeach ?>
Also, you should use parametrized queries to prevent SQL injection and avoid other problems when constructing the query if it contains special characters:
$stmt = $db->prepare("SELECT * FROM cards
WHERE code = (SELECT code FROM sets WHERE id = :id)");
$stmt->execute(array(':id' => $_GET['choice']));
$data2 = $stmt->fetchAll();

jQuery looping only works on last row

I am trying to show the results of the status of a bidding item using jQuery every second on every row in MySQL table, however only the result of the last row of the table is returned.
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
?>
<script type=text/javascript>
function updatestatus(itemnum)
{
var url="updatestatus.php?auc=<?php echo $row['item_id']; ?>";
jQuery('#status' + itemnum).load(url);
}
setInterval("updatestatus(<? echo $z?>)", 1000);
</script>
<?
$z++;
}
?>
When I view source in the browser, the values for #status and auc for every row are correct. What am I missing here?
Here's the code for updatestatus.php
<?php
session_start();
require_once("connect.php");
$id = $_GET['auc'];
$getstatus = mysql_query("SELECT status FROM items WHERE item_id = '$id' ");
$row = mysql_fetch_array($getstatus);
echo"$row[status]";
?>
Everything looks good, save for the fact that it looks like you're creating multiple references to your updatestatus() function.
In Javascript, if you create multiple functions with the same name, calling them will only result in one of them running, usually the first or last one (depending on the implementation), so all the code you need to run in those functions needs to sit together in one function body.
If you're determined to use the code you've created, you'd need to throw all those update calls into one function body. There would be better ways to achieve what you need, but doing it with the code you've created, this would probably work better:
<?php
$query = "SELECT item, description, price, imageData, status, username, item_id FROM items";
$result = mysql_query($query) or die(mysql_error());
$javascript = "";
$z=0;
while($row = mysql_fetch_array($result))
{
//echo other columns here//
echo "<td><div id=status$z></div></td>";
// build the javascript to be put in the function later over here...
$javascript .= "jQuery('#status". $z ."').load('updatestatus.php?auc=". $row['item_id'] ."');";
$z++;
}
?>
...and then further down the page, create the javascript (modified slightly):
<script type=text/javascript>
function updatestatus()
{
<?php echo $javascript; ?>
}
setInterval(updatestatus, 1000);
</script>
So you're basically building up the Javascript that you'll need in your function, echoing it out inside the function body, and then setting the interval will call all that code, in this case, every second.
Like I said, there are definitely more efficient ways to achieve what you're trying to do, but this should work fine for now. I hope this makes sense, but please let me know if you need any clarity on anything! :)
I don't see that you're populating data using a incrementor. Is this supposed to be adding content to a page or replacing the content? from what it looks like it will just display one item, and then replace that one item with the next until it's done, which is why you see only the last row.
OR ...
the jquery update isn't being fed the $i variable .. change the function to
function updatestatus(itemnum) {
and then jquery echo to jQuery('#status' + itemnum).load(url);
then you can add the on-click/ or whatever to include the number
onclick='updatestatus("1")'
on the other hand you might be needing to pass the total number of items to the function and then creating an if there to cycle through them (not tested, but you get the idea i hope)
function updatestatus(numitems) {
var url = "";
var itemID = "";
for (i = 1; i <= numitems; i++) {
itemid = getElementById('#status'+numitems).getAttribute("itemID")
url="updatestatus.php?auc="+itemID;
jQuery('#status'+numitems).load(url);
}
}
setInterval("updatestatus()", 1000);
and the html element for "#status1" as created by the PHP should look like this:
<div id="status1" itemid="23455">
</div>

jQuery forms.js with multiple forms per page

I would like to submit information to a mySql database using php and ajax.
The page that the info is being sent from (form.php) has multiple forms that are generated from a "while()" loop.
On success, I would a response to update a div above the particular form from which the data was submitted.
I am currently using jQuery and the jquery form plugin.
I have been successful in getting the data to the database, however I am having trouble with the response being sent back to the proper div. I have been successful in getting a response back to a div that is outside of the while() loop. I have not, however, been successful in getting a response back to a div within the loop. I have placed in the code below a div called:
">
Where I would like the note to be placed.
I know that this has everything to do with my javascript function:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() { $('#noteReturn').fadeIn('slow'); }
});
});
</script>
The #noteReturn function does not specify which businesses div it should be placed in.
I hope that this makes sense.
Thank you for your help.
The code is below:
<!-- the form.php page -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/forms.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() {
$('#noteReturn').fadeIn('slow'); }
});
});
</script>
<?php
$query = mysql_query("SELECT * FROM businesses");
while( $row = mysql_fetch_assoc( $query ) ):
$b_id = $row['bid'];
?>
<div class='notes'>
<?php
// query the db for notes associated with business... return notes texts and notes dates
$notesQuery = mysql_query("SELECT business_id, notes, messageDate FROM notes WHERE notes.business_id = $b_id ORDER BY messageDate");
while( $NoteRow = mysql_fetch_assoc( $notesQuery ) ) {
extract($NoteRow);
echo "$notes<br/><span class='noteDate'>$messageDate</span><br />";
} // end while$notesQuery
?>
<!-- this is where i would like jQuery to return the new note -->
<div id="noteReturn<?php echo $b_id; ?>"></div>
<!-- begin note form -->
<form name="noteForm" action="notesProcess.php" method="post">
<input type="text" name="note" />
<input type="hidden" value="<?php echo $b_id ?>" name="bid" />
<input type="submit" class="button" value="Send" />
</form>
</div> <!-- end div.notes -->
<?php
endwhile;
?>
<!-- /////////////////////////////////////////////////////
The page that the form submits to is this (notesProcess.php):
///////////////////////////////////////////////////// -->
<?php
$note = $_POST['note'];
$id = $_POST['bid'];
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if( $result ) {
echo " $note"; }
?>
Change this code:
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() {
$('#noteReturn').fadeIn('slow');
}
});
To this:
jQuery('form').ajaxForm({
target: '#noteReturn',
dataType: 'json',
success: function(data) {
$('#noteReturn' + data.id).html(data.note).fadeIn('slow');
}
});
And this code:
<?php
$note = $_POST['note'];
$id = $_POST['bid'];
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if($result) {
echo " $note";
}
?>
To this:
<?php
$note = mysql_real_escape_string($_POST['note']);
$id = mysql_real_escape_string($_POST['bid']);
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if($result) {
print json_encode(array("id" => $id, "note" => $note));
}
?>
What happened?
The change to the PHP code is making use of PHP's json_encode function to print out the id of the business to which the note was added as well as the actual note text. In the javascript code, I added the dataType of 'json' to tell the script what format of response to expect. Once the request is received in the success callback, the data variable is an object with the values we passed through json_encode. So data.id has the business id and data.note has the new note. Using jQuery's html() manipulation function, the inner html of the div is updated to the latest note. The div selector uses the id we passed, so we can update the corresponding div.
Also, this is slightly off topic, but make sure you always use mysql_real_escape_string when putting values into a query like you are. If you do not use this, your queries will be vulnerable and susceptible to injection attacks, and they are not pretty. If a customer decided to enter a note value of ');DROP TABLE businesses; you'd really feel the pain. Preferably, switch to PDO or MySQLi and use prepared statements, as they are the 'correct' way of doing queries nowadays.

Categories