I have a Ajax code snippet that has a bug that I cannot find.
The code worked a while back perfectly but now I cannot locate it, all seems to be correct.
I have tried to check my db codes, all good.
Tried to eliminate excessive code to bring it to basics, no result.
I have a text line that say "there are reviews" yet they are not shown. I have no MariaDB errors visible.
pagination_parser.php in directory 'includes'
<?php
// Make the script run only if there is a page number posted to this script
if(isset($_POST['pn'])){
$rpp = preg_replace('#[^0-9]#', '', $_POST['rpp']);
$last = preg_replace('#[^0-9]#', '', $_POST['last']);
$pn = preg_replace('#[^0-9]#', '', $_POST['pn']);
// This makes sure the page number isn't below 1, or more than our $last page
if ($pn < 1) {
$pn = 1;
} else if ($pn > $last) {
$pn = $last;
}
// Connect to our database here
require("db_connect.inc.php");
// This sets the range of rows to query for the chosen $pn
$limit = 'LIMIT ' .($pn - 1) * $rpp .',' .$rpp;
// This is your query again, it is for grabbing just one page worth of rows by applying $limit
$sql = "SELECT * FROM reviews WHERE status='1' ORDER BY reg_date DESC $limit";
$query = mysqli_query($db_conx, $sql);
$dataString = '';
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$stars = $row["stars"];
$comment = $row["review"];
$itemdate = strftime("%b %d, %Y", strtotime($row["reg_date"]));
$dataString .= $stars.'|'.$comment.'|'.$itemdate.'||';
}
// Close your database connection
mysqli_close($db_conx);
// Echo the results back to Ajax
return $dataString;
exit();
}
?>
index.php in folder 'texts'
<?php
// Connect to our database here
require "../includes/db_connect.inc.php";
// Create connection
$db_conx = new mysqli($host, $user, $password, $database);
// Check connection
if ($db_conx->connect_error) {
die("Connection failed: " . $db_conx->connect_error);
}
// This first query is just to get the total count of rows
$sql = "SELECT COUNT(id) FROM review WHERE status='1'";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
// Here we have the total row count
$total_rows = $row[0];
// Specify how many results per page
$rpp = 5;
// This tells us the page number of our last page
$last = ceil($total_rows/$rpp);
// This makes sure $last cannot be less than 1
if($last < 1){
$last = 1;
}
// Close the database connection
mysqli_close($db_conx);
?>
<!DOCTYPE html>
<html>
<head>
<script>
var rpp = <?php echo $rpp; ?>; // results per page
var last = <?php echo $last; ?>; // last page number
function request_page(pn){
var results_box = document.getElementById("results_box");
var pagination_controls = document.getElementById("pagination_controls");
results_box.innerHTML = "loading results ...";
var hr = new XMLHttpRequest();
hr.open("POST", "pagination_parser.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var dataArray = hr.responseText.split("||");
var html_output = "";
for(i = 0; i < dataArray.length - 1; i++){
var itemArray = dataArray[i].split("|");
html_output += "stars: "+itemArray[0]+" - date "+itemArray[2]+" - comment <b>"+itemArray[1]+"</b><hr>";
}
results_box.innerHTML = html_output;
}
}
hr.send("rpp="+rpp+"&last="+last+"&pn="+pn);
// Change the pagination controls
var paginationCtrls = "";
// Only if there is more than 1 page worth of results give the user pagination controls
if(last != 1){
if (pn > 1) {
paginationCtrls += '<button onclick="request_page('+(pn-1)+')"><</button>';
}
paginationCtrls += ' <b>Page '+pn+' of '+last+'</b> ';
if (pn != last) {
paginationCtrls += '<button onclick="request_page('+(pn+1)+')">></button>';
}
}
pagination_controls.innerHTML = paginationCtrls;
}
</script>
</head>
<body>
<div id="pagination_controls"></div>
<div id="results_box"></div>
<script> request_page(1); </script>
</body>
</html>
I do expect to have the html table with data, but just get the "loading results ..." .. but no data.
And mysql user and settings are checked, mysql direct query works fine, but I just don't get it on my development site.
I use development subsection to find bugs, but here I am about to give in.
My Ajax knowledge is just not good enough. Oh, it's not real ajax but XMLHttpRequest code.
Wouldn't mind to update to proper Ajax.
Looks like a simple mistake to me:
// Echo the results back to Ajax
return $dataString;
return will not echo your result like the comment says. Use one of the following:
echo construct:
echo $dataString;
exit();
print construct
print $dataString;
exit();
die function:
die($dataString);
exit function:
exit($dataString);
Related
am creating my flash project that accepts 4 variables i.e. name, school, score and date. However the connection between FLASH, PHP and MYSQL works fine and i can send data to MySQL database via flash with no problem. Now my problem is that i can't retrieve and view the data back to flash. I created a textfield named highscores for retrieving data in flash. And am sure my php code for retrieving is fine since i can view data in browser. So is there a way to retrieve my data in flash? here is my coding for flash:
str.text = "";
myschool.text = "";
myscore.text = "";
//Here i declared a textfield named highscores
//var text:String = highscores.text;
btn_submit.addEventListener(MouseEvent.CLICK, submitted);
function submitted(e:MouseEvent)
{
if(!str.length) {
status_txt.text = "Please enter your name";
}
else if (!myschool.length) {
status_txt.text = "Please enter your school name";
}
else if (!myscore.length) {
status_txt.text = "Please enter your score";
}
else {
var myrequest:URLRequest = new URLRequest("http://127.0.0.1/Y/sendscore.php");
myrequest.method = URLRequestMethod.POST;
var variables:URLVariables = new URLVariables();
variables.name = str.text;
variables.school = myschool.text;
variables.score = myscore.text;
myrequest.data = variables;
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, dataOnLoad);
loader.load(myrequest);
}
}
function dataOnLoad(evt:Event)
{
trace("Data submission complete");
var returnVars = evt.target.data;
trace("***********************");
for (var myVars in returnVars) {
trace(myVars + ": " + returnVars[myVars]);
}
trace("***********************");
MC_success.alpha=100;
//status is a custom flag passed from back-end
}
btn_scores.addEventListener(MouseEvent.CLICK, loadScores);
function loadScores(e:MouseEvent):void {
var fileLoader:URLLoader = new URLLoader();
fileLoader.addEventListener(Event.COMPLETE, scoresLoadComplete);
fileLoader.load(new URLRequest("http://127.0.0.1/Y/scores.php"));
}
function scoresLoadComplete(evt:Event):void {
try {
var returnVars = evt.target.data;
highscores.htmlText = returnVars;
trace("Data retrieved successfully");
for (var myVars in returnVars) {
trace(myVars + ": " + returnVars[myVars]);
}
trace("***********************");
//highscores.htmlText = returnVars.scores;
} catch (err:Error) {
trace("Can't parse loaded file: " + err.message);
}
}
HERE IS MY PHP CODE FOR RETRIEVING DATA
<?php
//Include database connection details
require_once('config.php');
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Create INSERT query
$qry = "SELECT * FROM highscores ORDER BY score DESC LIMIT 5";
$result = #mysql_query($qry);
$num=mysql_numrows($result);
if($num > 10)
{$num = 10;}
//echo "writing=Ok";
echo "<b><center>Best Times:</center></b><br /><table>";
//echo "scores=<b><center>Best Times:</center></b><br /><table>";
$i=0;
$i2=1;
while ($i < $num) {
$name=mysql_result($result,$i,"user");
$school=mysql_result($result,$i,"school");
$score=mysql_result($result,$i,"score");
$date=mysql_result($result,$i,"date");
echo "<tr><td align=left valign=top>$i2.</td><td align=center valign=top><b>$name</b> <b> | $school</b> | $score | $date</td></tr><tr><td colspan=2><hr></td></tr>";
$i2++;
$i++;
}
echo "</table>";
//$urlRefresh = "scores.php";
//header("Refresh: 15; URL=\"" . $urlRefresh . "\"");
exit();
mysql_close();
?>
As I mentioned in my previous answer, a textfield in Flash won't play well with HTML tables.
In your PHP file, you need to replace everything between the first and last echo with the following:
echo "scores=<b>Best Times:</b><br />";
$i = 0;
$i2 = 1;
while ($i < $num) {
$name = mysql_result($result,$i,"user");
$school = mysql_result($result,$i,"school");
$score = mysql_result($result,$i,"score");
$date = mysql_result($result,$i,"date");
echo "$i2. <b>$name</b> | <b>$school</b> | $score | $date <br />";
$i2++;
$i++;
}
Note that I have added back the scores= variable. This shouldn't cause any issues, as long as you're using the following line in AS3:
highscores.htmlText = returnVars.scores;
Separating your variables into name/value pairs means that you can pass other variables from PHP if you need to.
Update:
Having taken a look at your files, the whole thing runs perfectly; it successfully submits to the database and loads data back. However:
I think the issue you're having is with Flash caching your scores.php file.
This is fairly common when doing a URLRequest() on a file you've previously loaded. The most straightforward way to deal with this is to change this line:
fileLoader.load(new URLRequest("http://127.0.0.1/Y/scores.php"));
To this:
fileLoader.load(new URLRequest("http://127.0.0.1/Y/scores.php?rand=" + Math.random() * 999999));
All that does is add a random number to the end of your load as the 'garbage' variable rand. Flash sees this as you loading a different file, and so makes a fresh request rather than pulling it from the cache.
Other than that, everything in your files seems to run exactly as it should.
There is ALOT of code, but most of it is irrelevant, so i will just post a snippet
$error_message = "";
function died($error) // if something is incorect, send to given url with error msg
{
session_start();
$_SESSION['error'] = $error;
header("Location: http://mydomain.com/post/error.php");
die();
}
This works fine, sends the user away with a error session, which displays the error on the error.php
function fetch_post($url, $error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
This also works fine, checks if the "post" exists in the database, if it does, it adds the error the variable $error_message
while ($current <= $to) {
$dom = file_get_html($start_url . $current); // page + page number
$posts = $dom->find('div[class=post] h2 a');
$i = 0;
while ($i < 8) {
if (!empty($posts[$i])) { // check if it found anything in the link
$post_now = 'http://www.somedomain.org' . $posts[$i]->href; // add exstension and save it
fetch_post($post_now, &$error_message); // send it to the function
}
$i++;
}
$current++; // add one to current page number
}
This is the main loop, it loops some variables i have, and fetches posts from a exsternal website and sends the URL and the error_message to the function fetch_posts
(I send it along, and i do it by reference couse i asume this is the only way to keep it Global???)
if (strlen($error_message > 0)) {
died($error_message);
}
And this is the last snippet right after the loop, it is supposed to send the error msg to the function error if the error msg contains any chars, but it does not detect any chars?
You want:
strlen($error_message) > 0
not
strlen($error_message > 0)
Also, call-time pass-by-reference has been deprecated since 5.3.0 and removed since 5.4.0, so rather than call your function like this:
fetch_post($post_now, &$error_message);
You'll want to define it like this:
function fetch_post($url, &$error_message) {
$sql = "SELECT * FROM inserted_posts WHERE name = '$name'";
$result = mysqli_query($con, $sql);
$num_rows = mysqli_num_rows($result);
if ($num_rows > 0) {
$error_message .= $url . " already exists in the database, not added";
return $error_message;
}
}
Although as you're returning the error message within a loop it would be better to do this:
$error_messages = array();
// ... while loop
if ($error = fetch_post($post_now))
{
$error_messages[] = $error;
}
// ... end while
if (!empty($error_messages)) {
died($error_messages); // change your function to work with an array
}
I have following issue. I am parsing an xml feed with multiple pages and there is no way to understand how many they are (I have a variavle set in the xml url, so for each variable there are random number of pages). All I know is that the number can not exceed 50. Now I have a script that autoincrement the variable for the page number starting at 1 and up to 50.
Let's say, that the link has total of 26 pages. With my script I will continue to send requests until the scripts gets to page 50. Than it changes the first variable and starts again from 1 to 50. For the first link, from page 27 forward the xml will return followwing:
<response>
<status>error</status>
<code>400</code>
<message>Incorrect Request Headers</message>
</response>
How can I make so when the scipt receive this message, to stop the autoincrement and continue by changing the first variable and start again at 1? The code now is:
$query = "SELECT * FROM table_name ORDER BY id ASC";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
if($row['row_name'] == '') {
$variable1 = 0;
}
else {
$variable1 = $row['row_name'];
}
$page = 0;
do {
$page++;
$result = apiCall('option1', 'option2', array('option3' => $variable1, 'page' => $page));
usleep(1000);
$res = json_decode($result);
foreach ($res->node1->node2 as $item) {
//define variable for insertion in MySQL
$sql1 to insert the variables
if (!mysql_query($sql1,$con1))
{
die('Error: ' . mysql_error());
}
}
}
while ($page<=50);
}
In the above code, only the $variable1 and $page are variables. All options (1, 2 and 3) are predefined and stay the same. I.e. I need when the script gets the error message to start again from 1 with next value of $variable1.
OK. Here is the code I played around:
$query = "SELECT * FROM table_name ORDER BY id ASC";
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
if($row['row_name'] == '') {
$variable1 = 0;
}
else {
$variable1 = $row['row_name'];
}
$page = 1;
do {
$result = apiCall('option1', 'option2', array('option3' => $variable1, 'page' => $page));
usleep(1000);
$res = json_decode($result);
if ($res->status == 'error') {
break 2;
}
foreach ($res->node1->node2 as $item) {
//define variable for insertion in MySQL
$sql1 to insert the variables
if (!mysql_query($sql1,$con1))
{
die('Error: ' . mysql_error());
}
}
$page++;
}
while (0);
}
The problem is that it stops the script execution at some point. Can not understand why.
I am showing an image on my page from the db table like this:
<?php
if ($db_found) {
$SQL = "SELECT * FROM myTable where id='$posted_id'";
$result = mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)) {
echo '<img src="images/'.$db_field['image'].'" alt="" />';
}
mysql_close($db_handle);
}
?>
Next
How can I do so that if $posted_id is for example 1 ... when I click the "Next" link the image id = 2 appears and so on.
for that you need to either refresh page or use ajax.
you can pass variable posted_id in url like this.
Next
this way you can pass next id from database .. if your id falls in sequence.
you also need to programatically handle issue like what to do if record of next id does't exist in database..
You should work with the MySQL LIMIT and ORDER filters.
<?php
if (isset($_GET['current'])) {
$current = $_GET['current'];
} else {
$current = 0;
}
$request = "SELECT * FROM myTable ORDER BY id ASC LIMIT " . $current . ",1";
?>
And then, just to catch the next item, you can do something like that:
<?php
// make the last item point to the first one
$loop = true;
$count = "SELECT COUNT(*) FROM myTable";
if ($current < $count) {
$next = $current + 1;
} else if ($loop) {
$next = 0;
// no loop, then just stay at the end
} else {
$next = $current;
}
?>
Firstly, Thaks for taking a look at my question.
I have a function that works perfectly for me, and I want to call another function from within that function however I'm getting all kinds of issues.
Here are the functions then I'll explain what I'm needing and what I'm running into.
They are probably very messy, but I'm learning and thought I'd try get fancy then clean it up.
function GetStation($id){
$x_db_host1="localhost"; // Host name
$x_db_username1="xxxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
// SQL Query Setup for Station Name
$sql="SELECT * FROM stations WHERE ID = $id LIMIT 1";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){
$retnm = $rows['CallSign'];
}
mysql_close();
echo $retnm;
} // Closes Function
// List Delegates Function!!!!!!!!!!!!!!!!!!!
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_st_name = GetStation($StatNm);
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}
So I output ListDelegates() in a page and it displays a nice table etc.
Within ListDelegates() i use the GetStation() function.
This is because the table ListDelegates() uses contains the station ID number not name so I want GetStation($id) to output the station name
The problem I'm having is it seems GetStation() is outputting all names in the first call of the function so the first row in the table and is not breaking it down into each row and just one at a time :S
Here's what I think (I'm probably wrong) ListDelegates() is not calling GetStation() for each row it's doing it once even though it's in the loop. ??
I have no idea if this should even work at all... I'm just learning researching then trying things.
Please help me so that I can output station name
At the end of GetStation, you need to change
echo $retnm;
to
return $retnm;
You are printing out the name from inside the function GetStation, when you are intending to store it in a variable. What ends up happening, is that the result of GetStation is effectively echo'ed on the screen outside of any table row. Content that is inside a table but not inside a table cell gets collected to the top of a table in a browser. If you want to see what I mean, just view source from your browser after loading the page.
You don't need to connect to the database in each and every function. Usually you do the database connection at the top of your code and use the handle (in PHP the handle is usually optional) throughout your code. I think your problem is because when you call the function each time it makes a new connection and loses the previous data in the query.
My dear first of all you should place your code of connection with local host and database globally. It should be defined only once. you are defining it in both function.
something like this, and as suggested, you should have connection to database established somewhere else
function ListDelegates(){
$x_db_host1="xxx"; // Host name
$x_db_username1="xxx"; // Mysql username
$x_db_password1="xxxx"; // Mysql password
$x_db_name1="xxxx"; // Database name
// Connect to server and select databse.
mysql_connect("$x_db_host1", "$x_db_username1", "$x_db_password1");
mysql_select_db("$x_db_name1");
$q = "SELECT * FROM delegates";
$result = mysql_query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "There are no delegates to display";
return;
}
/* Display table contents */
echo "<table id=\"one-column-emphasis\" summary=\"Delegates\"><thead>";
echo "<thead><tr><th>ID</th><th>Name</th><th>Station</th><th>Spec Req</th><th>BBQ</th><th>DIN</th><th>SAT</th><th>SUN</th></tr>";
echo "</thead><tbody>";
for($i=0; $i<$num_rows; $i++){
$d_id = mysql_result($result,$i,"DID");
$d_name1 = mysql_result($result,$i,"DFName");
$d_name2 = mysql_result($result,$i,"DLName");
$d_name = $d_name1 . " " . $d_name2;
$d_spec1 = mysql_result($result,$i,"DSpecRe");
$StatNm = mysql_result($result,$i,"DStation");
$d_bbq1 = mysql_result($result,$i,"Dbbq"); // BBQ
$d_din1 = mysql_result($result,$i,"Dconfdinner"); // Dinner
$d_sat1 = mysql_result($result,$i,"DConfSat"); // Saturday
$d_sun1 = mysql_result($result,$i,"DConfSat"); // Sunday
//$d_st_name = GetStation($StatNm);
$sql="SELECT * FROM stations WHERE ID = $StatNm LIMIT 1";
while($rows=mysql_fetch_array($result)){
$d_st_name = $rows['CallSign'];
}
if ($d_spec1=="0"){ $d_spec = "-"; }
else {$d_spec = "YES"; }
if ($d_bbq1=="0"){ $d_bbq = "-"; }
else {$d_bbq = "NO"; }
if ($d_din1=="0"){ $d_din = "-"; }
else {$d_din = "NO"; }
if ($d_sat1=="0"){ $d_sat = "-"; }
else {$d_sat = "NO"; }
if ($d_sun1=="0"){ $d_sun = "-"; }
else {$d_sun = "NO"; }
echo "<tr><td>$d_id</td><td><strong>$d_name</strong></td><td>$d_st_name</td><td>$d_spec</td><td>$d_bbq</td><td>$d_din</td><td>$d_sat</td><td>$d_sun</td></tr>";
}
echo "</tbody></table></br>";
}