I have a form that posts to a script via ajax, the script inserts the form data into a database and using ajax i the refresh the div on the original page which then shows the form as well as a list of records in the database (from the form input)
I hope that makes sense.
My issue is that sometimes, maybe 1 time in 20, the div refreshes too quickly and doesn't pick up on the new data if i refresh the page its there and if i submit a new record both records are then in the list.
I guess i just need to delay the refreshing but i don't know how.
thanks,
php
echo '<div id="cuttingListDiv">';
$sql = "SELECT * FROM `cuttingList` WHERE jobRef = '".$_SESSION["jobRef"]."' ORDER BY pieceMaterialName, pieceThickness ASC";
$results = $dbconn->query($sql);
if ($results->num_rows > 0) {
echo '<h3>Cutting List:</h3>';
echo '<div align="center">';
while($row = $results->fetch_assoc()) {
echo '<br />';
echo '<div class="row">';
echo '<div class="col" align="center">';
echo '<h5>'.$row["pieceMaterialName"] . ' - ' . $row["pieceLength"] . ' x ' . $row["pieceWidth"] . ' x ' . $row["pieceThickness"] . 'mm</h5>';
echo '<br />';
echo '</div>';
echo '</div>';
}
echo '</div>';
}
echo '</div>';
ajax script
session_start();
include '_script_sqlConnection.php';
$pieceLength = strip_tags($_POST['pieceLength']);
$pieceWidth = strip_tags($_POST['pieceWidth']);
$thickness = strip_tags($_POST['thickness']);
$material = strip_tags($_POST['material']);
$materialName = strip_tags($_POST['materialName']);
$sheetID = strip_tags($_POST['sheetID']);
// Swap width & length id width bigger
if ($pieceWidth > $pieceLength) {
$tmpDimm = $pieceLength;
$pieceLength = $pieceWidth;
$pieceWidth = $tmpDimm;
}
$sql = "INSERT INTO `cuttingList`(`orderRef`, `pieceMaterialName`, `pieceThickness`, `pieceLength`, `pieceWidth`, `sheetID`, `pieceWeight`, `qty`) VALUES ('".$_SESSION["quoteRef"]."', '".$materialName."', '".$thickness."', '".$pieceLength."', '".$pieceWidth."', '".$sheetID."', '".$pieceWeight."', '1')";
if ($dbconn->query($sql) === FALSE) {
echo "Error Adding Pieces To Cut List.<br />";
}
javascript
$("#cuttingListForm").submit(function(){
$.ajax({
type: "POST",
url: "_script_ajax_addToCuttingList.php",
data: $('form.cuttingListForm').serialize(),
success: function() {
$("#cuttingListDiv").load(location.href + " #cuttingListDiv");
}
});
});
Use the JS function setTimeout
// example of usage for setTimeout:
setTimeout( function(){
$("#cuttingListDiv").load(location.href + " #cuttingListDiv");
}, 2000 );
In the example you have 2000 milliseconds for 2 second wait before fired the call.
Thanks for you help but i went a different way as i was still having trouble with both of these methods.
At the very top of the div that refreshes I used the php sleep command to wait 1 second, now it works perfectly.
Thanks,
Related
I'm stuck on my project for college, I've been working on a small time microblog, this may seem silly but I have no idea on how to make the feed auto refresh without killing my monthly bandwidth, here is the code I'm using atm,
Data.php
<?php
// connect to the database
require_once 'script/login.php';
//show results
$query = "SELECT post, PID, fbpic, fbname, fblink, post_date, DATE_FORMAT(post_date, 'Posted on %D %M %Y at %H:%i') AS pd FROM `posts` WHERE 1\n"
. "ORDER BY `post_date` DESC LIMIT 0, 30 ";
$result = #mysql_query ($query);
if ($result) { //If it ran ok display the records
echo '<div id="feed">';
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo '<a name="' . $row['PID'] . '"></a><div id="postsint"><a target="_blank" href="http://www.facebook.com/' . $row['fblink'] . '"><img id="dp" title="' . $row['fbname'] . '" src="https://graph.facebook.com/' . $row['fbpic'] . '/picture"/></a><div id="posttext">' . base64_decode($row['post']) . '<blockquote>' . $row['pd'] . '</blockquote>Share</div></div><br />';
};
echo '</div>';
mysql_free_result ($result);
} else { //if it did not run ok
echo '<h2 id="error">Wisprs could not be retrieved. We apologise for any inconvienience.</h2>'; //public message
echo '<p id="error">' . mysql_error() . '<br /><br /> Query: ' . $query . '</p>'; //debugging message
}
mysql_close(); // Close database connection
?>
content.php
<div id="postlist"> FEED GOES HERE.</div>
All im trying to do is check for updates every 2 seconds and if there is updates then show them in #postlist
It's been a 3 week struggle and I don't know any JavaScript, it's annoying me and I just want to finish this project so I can go to University and maybe learn to do this myself =/
Cheers in advance.
PS - I'm only guessing that it's Ajax but my tutor recommended this site for an answer if I get stuck
Hopefully you are allowed to use jQuery.
Add to content.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
function getFeed(){
$.post('Data.php',function(data){
$("#postlist").html(data);
});
setTimeout("getFeed();",2000);
}
window.onload = getFeed();
</script>
getFeed() is called on page load, then calls itself every 2000 milliseconds and appends the data received from Data.php into your postlist element.
This is brute forcing it, making it constantly delete the old html in the postlist div and create all new html every 2 seconds. If you have images that you are loading you will need a more complex solution.
If you use KnockoutJS and jQuery, this might be a good starting point:
http://jquery.com/
http://knockoutjs.com/
content.php
<script type="text/javascript">
$(function() {
// Define our view model that we will feed to KnockoutJS.
var viewModel = {
posts: []
};
// We'll use this variable to keep track of the last post we
// received. When we send our GET request, our php script will be
// able to see $_GET['last_post_date'] and only return the posts
// that come after that.
var last_post_date = null;
// This is the function that will get called every 2 seconds to
// load new data.
var getData = function() {
$.ajax({
url: "/data.php",
data: {
last_post_date: last_post_date
}
}).done( function( data ) {
// We'll assume data.php will give us a JSON object that looks
// like: { posts: [] }
// Append the new posts to the end of our 'posts' array in our
// view model.
viewModel.posts.concat( data.posts );
// Tell KnockoutJS to update the html.
ko.applyBindings( viewModel );
// Store the date of the last post to use in our next ajax call.
last_post_date = viewModel.posts[ viewModel.posts.length - 1 ].post_date;
});
// In 2 seconds, call this function again.
setTimeout( getData, 2000 );
};
// grab the first set of posts and start looping
getData();
});
</script>
<!-- We're telling KnockoutJS that for each 'row' in our 'posts' array, apply
the template named 'row-template'. -->
<div id="postlist"
data-bind="template: { name: 'row-template', foreach: posts }"></div>
<!-- This is the KnockoutJS template that we referenced earlier. Of course,
you don't have to use KnockoutJS to do this. There are plenty of other ways
to do this. Do keep in mind that you'll minimize your bandwidth usage if you
send JSON and use an HTML template rather than loading the same HTML over
and over again. -->
<script type="text/html" id="row-template">
<a data-bind="attr: {name: PID}"></a>
<div id="postsint">
<a target="_blank" data-bind="
attr: {
href: 'http://www.facebook.com/' + fblink
}
">
<img id="dp" data-bind="
attr: {
title: fbname,
src: 'https://graph.facebook.com/' + fbpic + '/picture'
}
" />
</a>
<div id="posttext">
<!--ko text: post--><!--/ko-->
<blockquote data-bind="text: pd"></blockquote>
<a data-bind="
attr: {
href: 'https://www.facebook.com/dialog/feed?' +
'app_id=505747259483458&' +
'link=http://www.wisp-r.com/share.php?' +
'id=' + PID + '&' +
'picture=http://www.wisp-r.com/images/app-icon.png&' +
'name=Wispr by ' + fbname + '&' +
'caption=' + pd + '&' +
'description=' + post + '&' +
'redirect_uri=http://www.wisp-r.com/share.php?id=' + PID
}
">
Share
</a>
</div>
</div>
<br />
</script>
data.php
<?php
// ... do sql stuff ...
// Remember to add a WHERE statement to filter out posts that are earlier than
// or equal to $_GET['last_post_date'].
$posts = array();
if ( $result ) {
while ( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) ) {
array_push( $posts, $row );
}
}
echo json_encode( array( 'posts' => $posts ) );
I'm making a travelguide. I'm displaying data(activity) from a database(mysql). Each activity has his own button. When you push this button you add that specific activity to your travelguide. This all works, but i must refresh the page to display the activities that are added to the guide. Now i have made a working javascript script, but it's not dynamic.
function MakeRequest()
{
var test = 1;
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "get_test.php?q="+test, true);
xmlHttp.send(null);
}
You see de variable: "var test = 1;"
The number 1 stands for the ActivityID 1. So now if you push the button it shows the activity with the ActivityID = 1. If i change the number to 2, is shows the activity with the ActivityID = 2.
I want to change the variable: "var test = 1;" The number must automaticly be inserted, it must be the same number as the ActivityID of the activity where is push the button.
<?php
$sql = "SELECT * FROM activity";
$stm = $db->prepare($sql);
$result = $stm->execute(array());
while($row = $stm->fetch(PDO::FETCH_ASSOC))
{
echo '<div id="activity'.$row['ActivityID'].'">';
echo '<img src="data:image/jpeg;base64,' . base64_encode( $row['ActivityIMG'] ) . '" >', '<br>';
//echo $row['Activityname'], '<br>';
//echo $row['Activitydescription'];
echo '<input type="button" class="addActivity" onclick="MakeRequest();" value="Activiteit toevoegen" data-activity="' . $row['ActivityID'] . '">';
echo '</div>';
}
?>
This is the php file:"get_activity". This is the code that displays the data en display the button. This button gets automaticly the ActivityID from the specific activity. This way i only need one script for all the activities. I want to do the same with the javascript, but i don't know how?
If I understand you want to give var test the correct id depending on the button you press.
Why don't you just pass a parameter to your js function?
function MakeRequest(test){
...............
}
$test = $row['id'];//your id field
<input type="button" class="addActivity" onclick="MakeRequest(<?=$test?>);" value="Activiteit toevoegen" data-activity="' . $row['ActivityID'] . '">
I am using jQuery sortable to manipulate image order and write to a DB. That functionality works well.
PHP
echo "<div class='revisionNum'>";
echo "<ul id='sortable_" . $count ."'>";
while($row = mysql_fetch_array($result)) {
$sortImageName = $row['OrgImageName'];
$sortPath = "../data/gallery/" . $galleryID . "/images/album/" . $sortImageName;
echo "<li class='sortPhotos' id='item_{$row['id']}' >";
echo '<img class="sortImage" src="'. $sortPath .'"/>';
echo "<p>" . $sortImageName . "</p>";
echo "</li>";
}
echo "</ul>";
echo "</div>";
jQuery
//make sortable
$(".revisionNum").each(
function(e) {
num = e + 1;
$("#sortable_" + num).sortable(
{stop:function(i) {
serial = $("#sortable_" + num).sortable("serialize");
$.ajax({
type: "GET",
url: "../albumUploader/queries/sort.php",
data: serial
});
},
opacity:1.0,
//cursor: move
});
});
MYSQL
foreach($_GET['item'] as $key=>$value) {
mysql_query(" UPDATE galleryimage
SET sort = '{$key}'
WHERE id = '{$value}'
");
}
The issue is when I have multiple <div class=''revisionNum> i am only grabbing the serial = $("#sortable_" + num) of the last UL if the [.revisionNum], not the actual UL that I am sorting. Thanks for the help on this. Let me know if further clarification is needed.
I am not sure I fully understand your question, but I think you are looking for the following:
The variable num will change every loop you make in the each-loop. But at the end it will have the value of the last loop. Because num seems to be a global variable you can't call it in the stop function. Then it will just use the last value it had. The value of the last loop. (Explains your problem)
To solve this I recommend to change your code to:
$(".revisionNum").each(
function(e) {
$(this).children("ul").sortable(
{stop:function(i) {
num = $(this).children("ul").attr("id").replace("sortable_", "");
serial = $(this).children("ul").sortable("serialize");
...
$(this) refers to the $(".revisionNum") you are looping through and it will be remembered, also in the stop function.
I am unsure of what path I should take for what I am wanting to do. The page loads some data from a mysql database with php. I made it so that a check box is generated with an incremented value starting wit 0 and so on for every value it finds in the database. What I am wanting to do is have that check box be so that when it is checked and they push the trashcan icon it will delete that row from the database. Where I am unsure is how to go about deleting it on button click and then reload the page. What would be the best way to do this? I am not needing the code or anything I just cant think of the best path to take to accomplish this.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Print Run</title>
<style type="text/css">
.openRun{
width:500px;
}
.openRun th{
text-align:center;
background-color:#CCC;
}
</style>
</head>
<body>
<div>
<?php
$totals = 0;
$i = 0;
$companyName = "";
$quantity = "";
$cardSize = "";
$dateAdded = "";
require("serverInfo.php");
$printRun = mysql_query("SELECT * FROM `printRun` WHERE status = 'Open'");
$row = mysql_fetch_array($printRun);
echo 'Print Run #: ' . $row['Run'];
$result = mysql_query("SELECT * FROM `printRun` WHERE status = 'Open'");
while($row = mysql_fetch_array($result)){
$companyName[$i] = $row['Company'];
$quantity[$i] = $row['Quantity'];
$cardSize[$i] = $row['Size'];
$dateAdded[$i] = $row['Date'];
$totals = intval($row['Quantity']) + $totals;
$i++;
}
$arraySize = count($companyName);
echo '<table class="openRun">';
echo '<tr><th>Company</th><th>Quantity</th><th>Size</th><th>Date Added</th><th></th></tr>';
for($i = 0; $i < $arraySize; $i++){
echo '<tr>';
echo '<td>' . $companyName[$i] . "</td>";
echo '<td>' . $quantity[$i] . "</td>";
echo '<td>' . $cardSize[$i] . "</td>";
echo '<td>' . $dateAdded[$i] . "</td>";
echo '<td><input type="checkbox" name="box'. $i .'" value="'. $i .'" /></td>';
echo '</tr>';
}
echo '<tr>';
echo '<td style="font-weight:bold; border-style:solid; border-top-width:1px;">Totals</td>';
echo '<td style="font-weight:bold; border-style:solid; border-top-width:1px;">' . $totals . "</td>";
echo '<td></td>';
echo '<td></td>';
echo '<td><img src="images/trash.png" /></td>';
echo '</tr>';
echo '</table>';
mysql_close($link);
?>
<br />
</div>
</body>
</html>
There's two ways of doing this. If you're not familiar with AJAX, or are scared about engaging with it, I'd suggest having a quick read of this tutorial just to get an overview.
With AJAX
If you don't want the page to reload, you're going to need to use AJAX to asynchronously send and receive data from the server. A typical example would be:
$('.trash_link').on('click', function() {
$.ajax({
url: 'path/to/script.php',
data: 'variable='+$('.input_class').val(),
dataType: 'html',
success: function(response) {
$('.container').html(response);
}
});
});
The crucial thing I'd advise is to put all of your layout logic in a controller or model function so that you don't repeat yourself. When data is sent to your server it can use this function to send back all your layout via the AJAX function. You can then insert the HTML inside your container element.
Without AJAX
All you do here is submit a form and your page reloads. For that reason you need to make sure you've already specified tags on your page. It really depends on what style you want your page to have - some people prefer reloads, some prefer the seamlessness of AJAX. Here is what you'd need if you chose to omit AJAX:
$('.trash_link').on('click', function() {
$('form').submit();
});
You can also add a pop-up confirmation if you want to:
$('.trash_link').on('click', function() {
if(confirm("Are you REALLY sure?") {
$('form').submit();
}
});
If you have an identifier in the table structure, you can just put
<input type='checkbox' name='ids[]' value='<?php echo $row['id']; ?>' />
Against every line of your table. Wrap the whole table in a form, make a submit button, in your script put something along these lines
if (isset($_POST['ids']) && is_array($_POST['ids'])) {
// some input sanitizing required.
$ids = array();
foreach ($_POST['ids'] as $id) if (intval($id) > 0) $ids[] = intval($id);
// $ids now hold the identifiers for the records to be deleted
if (count($ids)) $query = mysql_query("DELETE FROM `printRun` WHERE id IN (" . implode(', ', $ids) . ")");
// Then make a page refresh via HTTP 303 or otherwise to keep
// to the POST-redirect-GET policy.
header("HTTP/1.1 303 See Other");
header("Location: http://whate.ver/your_page_is.php");
}
If you just want a trash can that when clicked on, reloads the page and deletes the item, then just have that image in a link that passes along the id or whatever unique identifier the row has.
Delete
Have it hit a new php file that handles pulling off the unique identifier and deleting the record, then forwards back to the listing page.
$recordToDelete = is_numeric($_GET['id']) ? $_GET['id'] : null;
if($recordToDelete != null) {
$sql = "DELETE FROM `printRun` WHERE id = " . $recordToDelete;
//execute sql
}
//redirect back to listing page
header('Location: /yourpage.php');
I have a page that has a list of items. On the bottom of the page is a "view more" button. When someone clicks this button, the page needs to add more items. The var is $displayedquestions, and the page is coded right now to refresh when the "view more" button is clicked, but we'd like to have it do it live. How can this be done?
Here is code:
<?php
include "db_connect.php";
db_connect();
function tags($tags)
{
$tagarray=explode(",",$tags);
$i=0;
$finished='false';
while($finished=='false') {
if (empty($tagarray[$i])=='true') {
$finished='true';
} else {
$taglist = $taglist . '<a class="commonTagNames" href="">' . $tagarray[$i] . '</a> ';
$i++;
}
}
return $taglist;
}
function formattime($timesince)
{
$strsince=number_format($timesince,0,'','');
$nodecimals=intval($strsince);
if ($nodecimals<1){
return "Less than a minute ago";
} elseif ($nodecimals>=1&&$nodecimals<60) {
return $nodecimals . " min ago";
} elseif ($nodecimals>60&&$nodecimals<1440){
$hourssince=$nodecimals/60;
$hoursnodecimals=number_format($hourssince,0);
return $hoursnodecimals . " hours ago";
} elseif ($nodecimals>1440){
$dayssince=$nodecimals/1440;
$daysnodecimals=number_format($dayssince,0);
return $daysnodecimals . " days ago";
}
}
$submitbutton=$_REQUEST['viewmore'];
$numquestions=intval($_REQUEST['questions']);
if($numquestions!=0) {
$displayedquestions=$numquestions;
} else {
$displayedquestions=10;
}
$sql="SELECT * FROM `Questions` ORDER BY `Questions`.`ID` DESC LIMIT 0, " . $displayedquestions;
$questions=mysql_query($sql);
while($row = mysql_fetch_array($questions))
{
$id = $row['ID'];
$user = $row['userAsking'];
$question = $row['question'];
$tags = $row['tags'];
$timestamp = $row['timestamp'];
$time=strtotime($timestamp);
$secondssince=(date(U)-$time)/60;
$timesince=formattime($secondssince);
$responses=mysql_query("SELECT * FROM `answersToQuestions` WHERE `idOfQuestion`= '$id'");
$comments=mysql_num_rows($responses);
$likes=mysql_query("SELECT * FROM `likesOfQuestions` WHERE `idOfQuestion`= '$id'");
$numlikes=mysql_num_rows($likes);
$userprofileq = mysql_query("SELECT `ID`,`avatar` FROM `Users` WHERE `username` = '$user'");
$userprofileresult = mysql_fetch_row($userprofileq);
$linktoprofile = $userprofileresult[0];
$avatar = $userprofileresult[1];
$taglist=tags($tags);
echo "</li>";
echo '<li class="questionsList" onclick="showUser(' . $id . ')">
<div id="questionPadding">
<img class="askerImage" width=50 height=50 src="../Images/userimages/' . $avatar . '.png"/>
<div class="questionFirstRow"><h1 class="questionTitle">' . $question . '</h1></div>
<span class="midRow">
<span class="askerSpan"><a class="askerName" href="">'. $user .'</a></span>
</span>
<span class="bottomRow">
<img src="../Images/comment.png"/>
<span class="comments">' . $comments . '</span>
<img src="../Images/likes.png"/>
<span class="likes">' . $numlikes . '</span>
' . $timesince . '
</span>
</div>
</li>';
}
?>
<center><img class="moreQuestions" src="../Images/viewMoreBar.png" alt="More" /></center>
Without doing a lot of work you can add ajax to this. Use this function:
First, (I am assuming you are including the code above into another file) create a container around it. Ex:
<div id='container'>...</div>
Second, add this javascript to the page that includes the code you have above:
<script type="text/javascript">
$(function(){
$("#container img.moreQuestions").parent().live('click', (function (e) {
e.preventDefault();
$("#container").load($(this).attr("href"));
});
});
});
</script>
This will load into #container the script you already have without refreshing the rest of the page.
Note the selector for the More link (slash button) in my example is $("#container img.moreQuestions").parent() because you don't have a class or id on it. You should give a class or id to the More link and use that for the selector.
like #diEcho mentioned, jQuery would be a great help: You could easily refresh your list of items by ajax (retrieving the complete list from a php file for example) as well as update your DOM elements with newly added values. Give it a try.
In addition you should think about getting you initial items by ajax as well. Data logic /display /UI functionality were seperated cleanly this way.