So I'm trying to understand this whole AJAX/jQuery thing. Right now, when I run this PHP script alone, I would have to wait and watch the wheel spin until it's done with the loop and then it will load.
while ( $row = mysql_fetch_array($res) ) {
postcode_to_storm( $row['Test'] );
$dom = new DOMDocument();
#$dom->loadHTML($result);
$xPath = new DOMXPath($dom);
$failInvite = 'Rejected';
$findFalse = strpos($result, $failInvite);
if ( $findFalse == true ) {
$array[$i] = $row['Test'];
$i++;
echo $array[$i]};
}
}
Now, how do I use AJAX/jQuery to show echo $array[$i]}; everytime it is invoked instead of waiting for the whole process to complete?
The way AJAX works is that with the first request you write the basic HTML of your web page, including some javascript that calls back to the server and asks for more data. Depending on how you plan to send your data, it may make one or more requests after the page is rendered to get more data. Using AJAX will require that you rethink about how you're delivering your data. For example, you'll need one "script" to load the page, then another "script" to get the data -- of course, they could be the same, just with different parameters. I'll add a simple example to demonstrate since refactoring your example would require more understanding of your data and how it's delivered. This example is from w3schools.com.
HTML:
<script type="text/javascript">
$(function() {
$('#users').change(function() {
// here's the AJAX bit
$.get( '/users/load.php?q=' + $(this).val(),
function(html) {
$('#txtHint').html(html);
});
});
});
</script>
</head>
<body>
<form>
<select name="users">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</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>
</body>
</html>
PHP
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ajax_demo", $con);
$sql="SELECT * FROM user WHERE id = '" . mysql_real_escape_string( $q ) . "'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>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['Hometown'] . "</td>";
echo "<td>" . $row['Job'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
This is similar to COMET. Take a look at the differences here: http://ajaxian.com/archives/comet-a-new-approach-to-ajax-applications
Here's a post that talks about the difficulties in PHP in particular with a LAMP stack: http://www.phpclasses.org/blog/post/58-Responsive-AJAX-applications-with-COMET.html - may be a little dated as it was posted in 2006, but you get the point.
Typically when you talk about vanilla "ajax," you are talking about a client initiated request for some finite information (the http request completes), without an explicit page reload.
So, you want server to send every piece of data separately, once it's produced? I'm afraid, there is no such feature with http requests. You have to close it and then response is sent to the browser.
You may consider sending several requests, with some kind of pagination.
Related
I have a database witch contain users information and (with user name from database) and I have to show all information from database for user name selected.
<select name="user[]" id="user" multiple="multiple" tabindex="1" onchange="showUser(this.value)">
<?php while($row = mysqli_fetch_array($result)){
?>
<?php
foreach($result as $row){
?>
<option value ="<?php echo $row['username']; ?>"> <?php echo $row['username'];?></option>
<?php }
?>
<?php }?>
</select>
I can only display data for one user even if I select two or more
edit :
this is my script function and display function:
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","123.php?q="+str,true);
xmlhttp.send();
}
}
</script>
123.php :
<!DOCTYPE html>
<html>
<head>
<?php
session_start();
$q = $_REQUEST["q"];
require 'conectare.php';
mysqli_select_db($conectare,"users");
$sql = "Select * from users where username = '{$q}'";
$result = mysqli_query($conectare, $sql);
echo "<table>
<tr>
<th>Id</th>
<th>Username</th>
<th>Password</th>
<th>email</th>
<th>Telefon</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['telefon'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($conectare);
?>
</body>
</html>
enter image description here
It looks like this, I want to display 2 or more users and it only shows me one
Here's I am trying to show how you can achieve it. To display tabular data without.
I am not answering the exact solution, because i want you learn the basics. this code
is for example only.
$connection = mysql_connect('localhost', 'root', '');
//The Blank string is the password
mysql_select_db('hrmwaitrose');
$query = "SELECT * FROM employee"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table>"; // start a table tag in the HTML
while($row = mysql_fetch_array($result)){
//Creates a loop to loop through results
echo "<tr><td>" . $row['name'] . "</td><td>" . $row['age'] . "</td></tr>";
//$row['index'] the index here is a field name
}
echo "</table>";
//Close the table in HTML
mysql_close();
//Make sure to close out the database connection
You can open your browser tools, go to network and send the request, select the XHR pill and observe your request in the preview/response tab of the request. Also a good practice is to use parameterized queries. This web page is actually asking for someone to perform an SQL Injection.
The preview of your actual data will be really helpful in loading the page data to see what is the error that you are getting.
I was following this example found in the w3schools regarding php, mysql, and ajax. I edited the code to fit my needs, but I am unable to display information pulled from mysql. In all honesty, I'm not even sure if anything is being pulled from mysql. I do not receive any errors. The mysql database contains the id, name, and rating.
Here is my html page called results.html
<html>
<head>
<script>
function showName(str) {
if (str=="") {
document.getElementById("info").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("info").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","phpresults.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
<select name="Name" onchange="showName(this.value)">
<option value="">Select a Book:</option>
<option value="Book 1">Book One</option>
<option value="Book 2">Book Two</option>
<option value="Book 3">Book Three</option>
<option value="Book 4">Book Four</option>
</select>
</form>
<br>
<br>
<div id="info"><b>Select from above</b></div>
</body>
</html>
Here is my php page called phpresults.php
<?php
$q = strval($_GET['q']);
$con = mysqli_connect ("localhost","username","userpw");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db("dbname");
$sql="SELECT * FROM tablename WHERE name = '".$q."'";
$result = mysqli_query($sql);
echo $q;
echo "<table border='1'>
<tr>
<th>BOOK NAME</th>
<th>RATING</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["rating"] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
As of right now, when I make a selection, I am only displayed with BOOK NAME and RATING and nothing underneath it. When I echo $q I am shown the value of what I selected in the dropdown. I am trying to display the name and rating of a book based on the value selected in the dropdown.
EDIT:
I believe there is something wrong with this part of the code.
$sql="SELECT * FROM tablename WHERE name = '".$q."'";
$result = mysqli_query($sql);
When checking for errors, by using this
if (!$result) {
die('Could not query: ' . mysqli_error($result));
}
I receive "Could not query:" but no error.
Your PHP code is mixing mysqli_ and mysql_ function calls.
Don't do that, because that will cause errors.
Replace those mysql_ function calls with references to the appropriate mysqli_ functions.
(And I'm not at all surprised that the w3fools site would have examples with mixed calls like this.)
I removed the $sql variable and entered the select statement directly into the mysqli_query. I also made sure that all of my function calls were mysql_ since mysqli_ was not displaying the results.
Here is my working php code.
<?php
$q = strval($_GET['q']);
$con = mysql_connect ("localhost","username","userpw");
mysql_select_db("dbname");
$result = mysql_query("SELECT * FROM tablename WHERE name = '".$q."'") or die(mysql_error());
echo $q;
echo "<table border='1'>";
echo "<tr>";
echo "<th>Name</th>";
echo" <th>Rating</th>";
echo "</tr>";
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row["name"] . "</td>";
echo "<td>" . $row["rating"] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
I'm trying to limit the number of rows that the page shows according to the users selection from a drop down(think like a store page "show number of items per page")
At the moment I'm using php to call MySql and then echo out my results. I know that php cant do anything after the page loads. The next thing that comes to mind is java script.
However I have no experience with java script, I'm fair normal with java.
What are other options that you would suggest?
note: I want to limit my while loop not the mysql result.
Here is my code as it stands now:
<form name="input" action="EditPartyP.php" method="post">
<tr>
<td>Party ID</td><td>Party Name</td>
<td>Start Date</td><td>End Date</td><td>Sales</td><td>VIEW:
The drop down selection options that are being offered.
<select>
<option value="10">10</option>
<option value="20">20</option>
<option value="40">40</option>
<option value="80">80</option>
</select>
</td>
The results from the query being displayed, I under stand that I will have to change this because the php is done when the user sees the output html.
<?php
$ID = $_SESSION['ID'];
$result = PartyData::PartyLookupByID($_SESSION['ID'], "DESC");
This loop now just runs until the result runs out of data.
I need to make it stop when the users number is reached as well.
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo '<form name="input" action="EditPartyP.php" method="post">';
echo "<td>" . $row['PartyID'] . "</td>";
echo "<td>" . $row['PartyName'] . "</td>";
echo "<td>" . $row['sDate'] . "</td>";
echo "<td>" . $row['eDate'] . "</td>";
echo "<td>" . $row['PartyOrderTotal'] . " </td>";
echo '<input type="hidden" value=" ' . $row['PartyID'] . '" name="PartyID">';
echo "<td>" . '<button type="submit" value="Edit" name="Action">Edit</button>' . "</td>";
echo '</form>';
echo "</tr>";
}
?>
</table>
Thank you for reading and a comment helps more than a down vote.
You might want to look into https://datatables.net if you want features such as per page row diaplay or so called pagination.
Based on the selected page (via a $_GET['var'] and the users choice of number of records per page, you have to adjust your query with the limit statement.
SELECT * FROM table LIMIT 10, 50
Would start at the 10th record and will select 50 records max.
You can use SQL Limit command to retrieve specific number of data.
SELECT column_name(s) FROM table_name LIMIT number;
I am able to pass the server name to PHP which runs the query successfully. In the html file I want the rating option to change depending on what value was returned from the PHP file. In my file I set it to D but I need to change that to relflect what is being returned from PHP.
server.html
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
var id = $('#existingserver').val();
$('#assetCenter').click(function(){
var id = $('#textfield').val();
$.get('servertest.php',{q:id}, function(htmlData){
$('#txtHint').html(htmlData);
var rating = $(htmlData).find("td[data-col=rating]").text();
alert(rating);
});
});
});
</script>
</head>
<body>
<form>
<label>Existing Server</label><input type="text" name="existingserver" id="textfield" maxlength="15"/>
<input type="checkbox" id="assetCenter" >Select to Pull Asset Center Data<br>
<br />
<br />
Rating
<select name="rating" id="rating" >
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
</form>
<br />
<div id="txtHint"><b>Server info will be listed here.</b></div>
</body>
</html>
servertest.php
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'assignip', 'assignip');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ipreservation", $con);
$sql="SELECT * FROM acdata WHERE servername = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Servername</th>
<th>Contact</th>
<th>Classification</th>
<th>Rating</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['servername'] . "</td>";
echo "<td>" . $row['contact'] . "</td>";
echo "<td>" . $row['classification'] . "</td>";
echo "<td>" . $row['rating'] . "</td>";
echo "</tr>";
echo "<td data-col='rating'>" . $row['rating'] . "</td>";
}
echo "</table>";
mysql_close($con);
?>
database fields: servername, contact, classification, rating
Data: Server1, Ray, Production, A
In your PHP code, change the output so it displays the value you want to show, without any html tags.
Next in your html code, change your $(document).ready callback so that 'D' is replaced with the response text of the call (that is what PHP will return).
The short answer is to use a JQuery selector to get the rating:
// get the text of the 4th td
var rating = $(htmlData).find("td").eq(3).text();
$("#rating").val(rating);
However, you might notice this approach is kind of brittle (aka tightly coupled) -- if something changes in the UI, say you re-order the columns, then the above logic will break.
I'd suggest returning the data from the server as JSON, and then applying a client-side template to get the HTML table. At the very least, give the columns a name like this:
echo "<td data-col='rating'>" . $row['rating'] . "</td>";
And then you can select on the client side by referencing the name:
var rating = $(htmlData).find("td[data-col=rating]").text();
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I simply just want a button in my table to delete the specific row but everything I search for ends up being some completely different way compared to how I have set it up.
<?php
// Connects to your Database and if it cant it dies
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// this selects the db
mysql_select_db("test", $con);
// this passes the query into the variable result
$result = mysql_query("SELECT * FROM items");
echo "<table border='1'>
<tr>
<th>ID</th>
<th>Name</th>
<th>Quantity</th>
<th>Delete</th>
<tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "<td>" . 'Delete' . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
//end php
?>
<html>
<body>
<form action="insert.php" method="post">
Name: <input type="text" name="Name" />
Quantity: <input type="text" name="Quantity" />
<input type='submit' name='add' value='add' />
</form>
</body>
</html>
i would like the hyperlink to delete the row is contained in.
You need to add the ID of the record you want to delete to the delete url, e.g.:
echo "<td>Delete</td>";
Then, in your delete.php script, you'd do:
<?php
$id = intval($_GET['id']);
$sql = "DELETE FROM yourtable WHERE id=$id";
$result = mysql_query(sql);
Of course, that's not a full script, but shows you the basics of what needs to be done. Be careful with using the passed-in value in your query - don't want to let an SQL injection hole ruin your day.
However, be aware that using a 'GET' type query for this sort of thing is generally a bad idea. If this page gets spidered by Google (for one), you'll find that the simple act of spidering has nuked ALL of your records.
You need to pass the ID of the row as paramter to the delete.php script
echo "<td>" . 'Delete' . "</td>";
you can use the id of the current row and send it to delete.php:
echo "<td>" . 'Delete' . "</td>";
then in delete.php get the id by $deleteId = $_GET['id'] and use it...
Try changine the URL to something like echo '<a href="delete.php?ID=' . $row['ID'] . '">'
BTW - Not a good idea to use root!