I'm sending a variable from a form using AJAX and this variable is proccess and sends to a PHP file that makes a MySQL query. The value of the input text is setting when I click in a row of one table. When I click the button to send the variable it returns the result of the mysql query. Well, if I click one more time in the button when the value of the input is other the query isn't modify, it returns me the first query. I need to refresh that query and I think that it's possible if I clear the variable.
I put here the code of all. Thanks.
HTML Code
<td><input type="hidden" id="prueba" name="prueba"/></td>
<script type="text/javascript">
var valor=document.getElementById("prueba").value;
</script>
<td><input type="button" name="ver" onclick="load(valor)" value="Ver linea seleccionada"/></td>
AJAX code
function load(str)
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mus").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","mostralle.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q="+str);
}
PHP Code (mostralle.php)
include"conexion.php";
$q=$_POST['q'];
mysql_connect($servidor, $usuario, $clave)or die (mysql_errno().mysql_error());
mysql_select_db($basedatos)or die (mysql_errno().mysql_error());
$result=mysql_query("SELECT Serie, Numeroas, Numlinea, Codart, Cant, Descripcion, Precio, Tipoiva, Subtotal FROM PRESUP_D WHERE Serie='$q' OR Numeroas='$q'");
while($row=mysql_fetch_row($result)){
echo "<tr>";
for($i=0;$i<mysql_num_fields($result);$i++){
echo "<td>$row[$i]</td>";
}
echo "</tr>";
}
mysql_close();
Related
I am actually creating a forum. So, there would be a "order by" dropdown box i.e a select tag in html. Where the user selects any order like by time or like, etc. An ajax function is called which dynamically brings content into the page from mysql database.
Select menu
<select name="orderby" onchange="showposts(this.value)">
<option value="1" selected>By Time</option>
<option value="2">By Genuine Count</option>
<option value="3">By Dubious Count</option>
</select>
showposts function
function showposts(str){
orderby=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("postsdiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showposts.php?q="+str,true);
xmlhttp.send();
}
Showposts.php page
$sql = "SELECT * FROM posts order by date desc ";
$result = $connection->query($sql);
$username=$_SESSION['username'];
while($row = $result->fetch_assoc()) {
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "-----------------------------------</br>";
echo "-----------------------------------</br>";
echo "Posted By: ".$row['user']."    ";
echo "Time: ".$row['date']."</br>";
echo "<span id=genuinecount".$row['id'].">Genuine Count: ".$row['genuine'].";
echo "<span id=dubiouscount".$row['id'].">Dubious Count: ".$row['dubious']."</span>";
echo "</br>------------------------ </br>";
echo "Subject: ".$row['subject']."</br>";
echo "Post: ".$row['post'].'<br />';
}
Problem
So, the problem here is, I want to use a continuous scroll option like the one which is used in facebook. All the javascripts and jquery libraries I saw use logic that when the user scrolls down to the page, the javascript then places some content after that. But, here I running a while loop which brings the data from database at a time. So, I couldn't implement the javascript code. So, is there any thing that I could do to achieve continuous scroll, like is there any possibility to break the while loop or retrieving entire data and display part by part or anything like that?
javascript for scrolling
function yhandler(){
var wrap=document.getElementById('postsdiv');
var contentheight=wrap.offsetHeight;
var yoffset=window.pageYOffset;
var y=yoffset+window.innerHeight;
if(y>=contentheight){
showposts();
}
}
window.onscroll=yhandler();
Use the PDO class built into php and the query from the database will return all the rows as an array of stdclass objects. Then use PDOStatement::fetchObject() to loop through the array
As you are retrieving the data from server using JavaScript, why don't you put the view with the help of JavaScript instead of PHP.
Try using Asynchronous Javascript Call (AJAX) instead of XMLHttpRequest. This will help you to load data asynchronously which means that even if the the result coming form server take time you can still execute your other javascript codes.
With AJAX implemented, let say you want to fetch 10 Posts at one time, then after fetching first 10 posts, you can print the data for those 10 using JavaScript and simultaneously make a call for another 10.
Prepare a successCallBack function, where you will parse the data received and put that as required for your HTML. You will need to append the posts, so that when the next AJAX returns the result, that gets appended after the last post.
http://www.jquery4u.com/demos/ajax/
You should look into MySQL LIMIT. The limit function takes 2 input variables, start and length. With these 2 variables you can create a paging system; that would go something among the lines of:
showposts function
//Add a global variable to save the current page:
var currentPage = 0;
var currentType = 0;
function showposts(str){
//ALL PREVIOUS CODE, UNCHANGED
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("postsdiv").innerHTML+=xmlhttp.responseText;
}
}
if(str != undefined){
currentType = str; //save the current type for later use
document.getElementById("postsdiv").innerHTML = "";
}
xmlhttp.open("GET","showposts.php?q="+currentType+"&p="+currentPage,true);
xmlhttp.send();
}
Showposts.php page
<?php
$currentPage = intval($_GET['p']);
$numPerPage = 30; //change this to the number of items you want each page
$sql = "SELECT * FROM posts order by date desc LIMIT ".($currentPage * $numPerPage).", ".$numPerPage;
$result = $connection->query($sql);
$username=$_SESSION['username'];
while($row = $result->fetch_assoc()) {
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "-----------------------------------</br>";
echo "-----------------------------------</br>";
echo "Posted By: ".$row['user']."    ";
echo "Time: ".$row['date']."</br>";
echo "<span id=genuinecount".$row['id'].">Genuine Count: ".$row['genuine']."</span>";
echo "<span id=dubiouscount".$row['id'].">Dubious Count: ".$row['dubious']."</span>";
echo "</br>------------------------ </br>";
echo "Subject: ".$row['subject']."</br>";
echo "Post: ".$row['post'].'<br />';
}
?>
Now you need to detect when a user has scrolled to the bottom of the page, then call the following function:
function nextPage(){
currentPage++;
showposts();
}
I want to make a autocomplete to my input field.
All the data is fetched from my database and handled with my autocomplete.php file - its works fine and is storing all the matching columns in a XML file which is sent back to the server.
Onkeyup i GET send with q= "the typed string" to the autocomplete.
Im having trouble handling the XML file when its received from the server. My plan is to append all the matching results to my datalist, which will work as a autocomplete?
Here is my code:
<input id="showCustomerId" name="customer" type="text" min="1" max="100" list="customerlist" required>
<datalist id="customerlist"></datalist>
script:
$("#showCustomerId").on('keyup', function(){
var str = document.getElementById('showCustomerId').value;
var xmlhttp;
if (str.length===0) {
document.getElementById("customerlist").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 docroot= xmlhttp.responseXML.documentElement;
var customers = docroot.getElementsByTagName('customer');
for(var i=0; i<customers.length; i=i++){
var option = customers[i].firstChild.nodeValue;
$("#customerlist").append("<option value=\"" +option+ "\">");
}
}
}
xmlhttp.open("GET","ini/search-customers.php?q="+str,true);
xmlhttp.send();
});
autocomplete.php
$q=$_GET['q'];
$result = // do query;
$xml = new SimpleXMLElement('<xml/>');
while($row = mysqli_fetch_assoc($result)){
$xml->addChild("customer",$row['customer_id']);
}
header('Content-type:text/xml');
print($xml->asXML());
Right now my problem is not getting the value, when i alert the result in xml handler function i get the right values, but when i do the code like i have here, my website freezes!
I got the values, but i just cant append them to my datalist the right way?
I guess Easiest way to build autocomplete is by jQuery Autocomplete or Twitter Typehead. So simple jquery is better suited for this situation. Add jQuery Latest version in head
Code is not tested.
$(document).ready(function(){
//Assuming #customerlist is the ID of the text box which you need to see autocomplete
//No need to get value also - by default
$("#customerlist").autoComplete({source:"ini/search-customers.php"});
// Same time autocomplete send term as default GET variable
});
At serverside - search-customers.php
$q=$_GET['term'];
$result = // do query;
$json = new Array();
while($row = mysqli_fetch_assoc($result)){
$json[] = $row['customer_id'];
}
header('Content-type:application/json');
echo json_encode($json);
I want to create a progress bar for a server-side task ( written in php )
For learning purposes the example and task would be very simplistic.
I would have a text field on the client page, read a number, pass it to the php script with ajax and make it calculate the sum of all numbers from 0 to number ( simplistic task that would take some time for big numbers, just to simulate some server-side work)
in the .html file I would create a timer that would call a function every n seconds getting the index that my for loop got to and update a progress bar.
My question is :
Is it possible to have in the same php file two functions , and how can I call a specific function with ajax : one that would block looping to number and another one I would call to get the current index the for-loop got to.
The code I have so far :
<!DOCTYPE html>
<html>
<head>
<script>
function myTimer()
{
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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("percentageDiv").innerHTML=xmlhttp.response;
alert(xmlhttp.response);
}
}
xmlhttp.open("GET","getter.php",true);
xmlhttp.send();
}
function loop(){
var loop_index = document.getElementById("loop_nr").value;
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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("sumDiv").innerHTML="Total sum = " + xmlhttp.response;
clearInterval(myVar);
}
}
xmlhttp.open("GET","server_side.php?nr="+loop_index,true);
xmlhttp.send();
var myVar=setInterval(function(){myTimer()},1000);
}
</script>
</head>
<body>
<div id="percentageDiv"> Percentage div</div>
<div id="sumDiv"></div>
<input type="text" id="loop_nr">
<input type="submit" onclick="loop()">
</body>
</html>
server_side.php
<?php
session_start();
$index=$_GET["nr"];
$progress = 0 ;
$sum = 0 ;
for ($i = 1; $i <= $index; $i++) {
$sum = $sum + $i;
$progress++;
$_SESSION['progress'] = $progress;
}
echo $sum;
?>
getter.php
<?php
session_start();
$progress = $_SESSION['progress'];
echo $progress;
?>
Thank You!
Not only one question in here
Your question would be two:
How can I do AJAX calls to specific functions in PHP?
How can I do a progress bar with AJAX?
How can I do AJAX calls to specific functions in PHP?
Your AJAX code is fine. The only thing you have to do in your PHP is receive this call.
Look at your request. You send a variable nr with your request:
server_side.php?nr="+loop_index
That will help us in the php code to determine that this is an AJAX call to do the sum operation. Now in the PHP:
<?php session_start();
//We look at the GET php variable to see if the "nr" is coming
if(isset($_GET['nr'])) {
//Its coming!. Now we procede to call our function to sum
sum($_GET['nr']);
}
function sum($nr) {
$progress = 0 ;
$sum = 0 ;
for ($i = 1; $i <= $nr; $i++) {
$sum = $sum + $i;
$progress++;
$_SESSION['progress'] = $progress;
}
echo $sum;
}
Thats it.
How can I do a progress bar with AJAX?
We need to make other AJAX call to request the progress to PHP.
First, we do another AJAX call to retrieve the progress with a timer!
var timer;
//try to delete duplications. Do a generic function that does the request to php
function makeRequest(toPHP, callback) {
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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
callback(xmlhttp.response);
}
}
xmlhttp.open("GET",toPHP,true);
xmlhttp.send();
}
function loop() {
var loop_index = document.getElementById("loop_nr").value;
makeRequest("server_side.php?nr="+loop_index, function(response) {
document.getElementById("sumDiv").innerHTML="Total sum = " + response;
clearInterval(timer);
});
timer=setInterval(makeRequest("getter.php", function(response) {
document.getElementById("percentageDiv").innerHTML=response;
}),1000);
}
Then in the php side we retrieve this call as we did before and echo the $_SESSION['progress'] (as you already have)
<?php
session_start();
$progress = $_SESSION['progress'];
echo $progress;
?>
And that's it!
Edit: Sessions must not be saved to a file (default PHP behaviour) because if you do that the "progress" AJAX will be blocked. You should store your sessions in a key-value database such as Redis to achieve parallelism and horizontal scalability.
Here is the solution to made progress bar in PHP without javascript only on server side:
echo "<div style=\"float:left;\">Start... </div>";
for ($i = 0; $i<20; $i++){
echo '<div style="float:left;background-color:red;height:20px;width:'.$i.'px"></div>';
ob_flush();
flush();
usleep(100000);
}
echo "<div style=\"float:left\"> Done!</div>.";
ob_end_flush();exit;
I have AJAX code here that pass multiple values to PHP. But the problem is that the PHP can't get the value pass by AJAX and nothing is added on the database. However in my submit button I have an onclick event that calls addAnnouncement() and I think it is working because I put an alert in my ajax code and everytime I click that button it says OK.
So I think the part of the problem is in the passing of the variables.
What do you think is the problem in my code?
AJAX CODE:
function addAnnouncement()
{
var subject = document.getElementById("subject").value;
var name = document.getElementById("name").value;
var announcement = document.getElementById("announcement").value;
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 (xmlhttp.readyState==4)
{
if(xmlhttp.status==200){
alert("OK");
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
}
var variables = "subject=SAMPLE&name=HARVEY&announcement=HELLO";
xmlhttp.open("POST", "addAnnouncement.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(variables);
return false;
}
This is the PHP code that gets the values pass by AJAX.
PHP CODE:
<?php
require_once("config.php");
$subject = $_POST['subject'];
$name = $_POST['name'];
$text = $_POST['announcement'];
$dateTimeNow = date("Y-m-d H:i:s");
$query = "INSERT INTO table_announcement(subject, name, text, dateTimePosted)".
"VALUES('$subject', '$name' , '$text', '$dateTimeNow')";
$data = mysql_query($query)or die(mysql_error());
if($data){
echo "ADDED!";
}
else{
echo "ERROR!";
}
?>
Just return false when exiting from the event handler to prevent the default behaviour of the submit button (i.e. submit the form):
function addAnnouncement() {
// …
return false;
}
Also check the status of your XMLHttpRequest when it reaches readyState 4 (it might be something different then 200) and properly encode query string parameters with encodeURIComponent. Last, but not least, your code is open to SQL injection. Fix that by using prepared statements (available in MySQLi and PDO. If you can't decide which, this article will help you. If you pick PDO, here is a good tutorial).
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;
}