Dynamic Row Only Added on First Click - php

I have an application that seems to work pretty well except for one small glitch that I can't seem to figure out. I am hoping for some help here.
I have a table that I can dynamically add rows to. There are two ways to add rows, some with a checkbox that loads pre-determined data, or an image, which adds a blank row to the table.
The checkbox works great, but the image link only works the first time, and not the next.
This is the image line:
<img src="img/plus.png" width="25" height="25" id="btnAddRow" title="Add New Row" class="idfirst alternativeRow" />
alternativeRow is generated from code from here: http://www.examplet.buss.hk/jquery/table.addrow.php (example #10, but much more complex) and that line is this:
$(".alternativeRow").btnAddRow({oddRowCSS:"oddRow",evenRowCSS:"evenRow"});
The "idfirst" block of jquery code is this:
$(document).ready(function(){
$(".idfirst").click(function(){
result = 0;
id = 0;
jQuery.ajax({
url: 'getItemID.php?q=<?php echo $q; ?>',
success: function(result) {
id = result;
if(result.isOk == false)
alert(result.message);
},
async: false
});
window.location.href='page.php?q=<?php echo $q; ?>&id=<?php echo $id; ?>';
});
});
I do the reload because I want the new number created in getItemID.php to dynamically load. This is important because it also is added to a link that is created within the new row. The code in getItemID is as follows:
$q = $_GET['q'];
$description = $_GET['description'];
$rate = $_GET['rate'];
$hours = $_GET['hours'];
$query = "INSERT INTO items (q, description, hours, rate) VALUES ('".$q."','".$description."','".$hours."','".$rate."')";
$results = mysql_query($query) or die(mysql_error());
$nextId = mysql_insert_id();
echo $nextId;
So my problem is that when I click the image link the first time, everything works great, and I get my blank row, the links in the dynamic row work properly, life is good.
But the moment I press it a second time, the page will reload, but I don't get my new row. It will only return the existing rows before the refresh.
I am wondering if anyone can see something I'm doing wrong and offer any advice. (Yes, I understand that some of this is maybe not the ideal way to make it work, but for the most part it is working the way I need it to...and I've spent tons of hours to make all these moving parts get along).
Thank you in advance for any advice.

I did manage to figure it out.
I was testing this out in IE, which the users will all be using. Same issue in Firefox, which I use.
I came across this article http://www.electrictoolbox.com/jquery-json-ajax-caching/ and once I tried it in Chrome, it turned out to be a browser issue. So I implemented the following solutions:
I added
$.ajaxSetup({ cache:false });
to the top of my script, and for good measure, added
cache: false,
to my ajax call.
Now it works great everywhere.

Related

jQuery button response time issue while auto refreshing a DIV in every X second

I am using this code for refresh my main DIV in my main page (named readings.php):
jQuery(document).ready(
function intervalle() {
setInterval(jQuery('#myMainDiv').load('readings_content.php'), 10000);
});
In the readings_content.php, sensor readings are being checked from database and drawing a screen like a security cam screens according to the sensor count. This code is like:
$db_sensors->query("select * from tbl_sensors where status=1");
if ($db_sensors->recordcount>0){
while ($db_sensors->nextrow()){
$sensors=$db_sensors->fields;
$sensorname = $sensors["name"];
$sensorvalue = $sensors["lastreading"];
echo "<div>";
echo "Sensor Name: ".$sensorname."<br>";
echo "Last Reading: ".$sensorvalue;
echo "</div>";
}}
This idea is working fine. But because of this loop (there are 9-16 sensors) refresh is taking time. That is normally fine because page is not reloading, just changing the values when it reads a new sensor reading. But there is a button in the my main page (readings.php). It takes almost 10 second for response time for this button even I am using local database.
I want to make this refresh process faster. Or if that is possible, I want to stop this refresh thing (or what ever is happening in the page) when I click the button. and make its onClick event working.
After my whole researches I started to try all different options. And it only was OK when I change the jQuery code like this:
setTimeout('sensorcells_load()', 10000);
function sensorcells_load()
{
jQuery('#sensorcells').load('dashboard_content.php');
setTimeout('sensorcells_load()', 10000);
}
I am not a jQuery man and I don't really know why this one works but other one doesn't. But this solved my issue.

Counting paragraphs with pagination

I’ve just started learning PHP and have attempting to build my first data driven web page to aid with my learning but I now seem to have come across a problem that's been driving me nuts.
Here is a bit of background.
What I have been attempting to do is pull content from a database, this content is already marked up with html paragraph tags. The content will be user submitted and so I have no way of knowing how many paragraphs each row will contain.
I am then looping through the content and counting the paragraphs so that I end up with 5 paragraphs inside each containing div.
Here is the code I am using to do this, I know my code is a bit basic but it seems to work fine as long as all of the content is retrieved in just a single query.
$stmt = $db->prepare('SELECT * FROM content');
$stmt->execute();
foreach($stmt as $row) {
$allParagraphs .= $row['content'];
}
$paragraphArray = explode("</p>", $allParagraphs);
$paragraphCount = 0;
echo '<div class="bookPage">';
foreach ($paragraphArray as $value) {
echo $value;
$paragraphCount = $paragraphCount + 1;
if ($paragraphCount == 5){
echo '</div><div class="bookPage">';
$paragraphCount = 0;
}
}
echo '</div>';
And now my problem.
Now I would like to include pagination with an endless scroll effect using PHP and Jquery. I feel confident enough to do this; however, I have noticed that the current code I am using (to count every 5 paragraphs) is not going to work when I introduce pagination.
As far as I can see, after working through the code what is going to happen is that the closing div is going to be inserted and then, when the 2nd query made via ajax (read more link clicked) it is going to result in a new opening div. This results in the leftover paragraphs from each query being surrounded by the div tag and not containing the 5 paragraphs I need.
Basically, in its simplest terms, what I would like to do is to still be able to wrap div tags around every 5 paragraphs but also still be able to paginate the results via ajax.
If anyone could advise me of the best way to go with this it would be very much appreciated.
My musings on this issue so far...
I am not sure if this is even possible to do which leads me to believe I have approached this the wrong way. I’m not very experienced at the moment but I can’t help think that it would be easier to store every paragraph in a separate row in the database which would allow me to then pull them out in multiples of 5. But then, something else is telling me that would not be a practical solution at all, especially as I have no way of knowing how many paragraphs each user would be writing/submitting.
I dont have enough points to post an image so here is a link to an image i uploaded in attempt to demonstrate what i mean should my attempt at describing the issue not be enough.
Diagram showing issue
Thank you in advance of any suggestions.
I guess you could remove all the HTML tags in your PHP script and just return the content of the paragraphs as JSON object, for example.
So, basically, you'd return something like:
echo json_encode($paragraphArray);
And request that with jQuery like this (which is an adoption of the first example at http://api.jquery.com/jQuery.getJSON/):
jQuery.getJSON('yourURL.php', function(data) {
var items = [];
jQuery.each(data, function(key, val) {
items.push('<p>' + val + '</p>');
if(items.length == 5) {
appendItemsToBody(items);
items = [];
}
});
appendItemsToBody(items);
});
function appendItemsToBody(items) {
if(items.length) {
jQuery('<div/>', {
'class': bookPage,
html: items.join('')
}).appendTo('body');
}
}
Depending on what should happen when clicking on "load more", you could pass the count of currently displayed items as data to the call to your PHP script via jQuery.getJSON() (see their API documentation) and then decide in your PHP script which paragraphs you should return (i.e. where to start from). You'd have to append the "rest" of the paragraphs to fill up the 5 items to the existing last div in jQuery, and put the rest into new divs.

Jquery - pull new data with $_GET variables each time a div is clicked

I'm going to do my best explaining this, as I'm fumbling around a bit as it's my first time doing anything like this.
At the beginning of my page I call a function that returns 3 recipe's, I then create variables and assign each with a recipe id:
$meal = builder::buildMealPlan(1200,0,0,0,3);
$id1 = $meal[0][id];
$id2 = $meal[1][id];
$id3 = $meal[2][id];
So I now know the id's of the 3 recipe's that have been chosen by the function, I then display these 3 recipe's in 3 div's:
<div id="meal1"><h2><? print_r($meal[0]); ?></h2></div>
<div id="meal2"><h2><? print_r($meal[1]); ?></h2></div>
<div id="meal3"><h2><? print_r($meal[2]); ?></h2></div>
When any of these div's are clicked it means you don't like that recipe and want a different one, it calls a page with 4 parameters (id1,id2,id3,clicked), basically telling it the 3 recipe's that are currently displayed as well as which one was clicked, so I can find another combination of recipes with 2 of the same id's, as well as the new one:
$(document).ready(function(){
$("#meal1").click(function(){
$.get("testing-01.php?id1=<?echo $id1;? >&id2=<?echo $id2;?>&id3=<?echo $id3;?>&clicked=1", function(result){
$("#meal1").html(result);
});
});
This works great, a proper recipe is selected and the div is refreshed with the new recipe, however my problem is now, if you click any of the div's again, it refreshes with the same recipe over and over again, because my php variables ($id1, $id2, $id3) are always the same value, since the page is never reloaded.
My question: How can I set a javascript variable with the result of my onclick event? Right now the on click event replaces the div with data from:
$.get("testing-01.php?id1=<?echo $id1;? >&id2=<?echo $id2;?>&id3=<?echo $id3;?>&clicked=1
However I need to somehow update the variables that I'm sending in the above statement with new values each time a div is clicked.
If you've read this far, thanks, if I've left important/obvious things out please just let me know and I'll add it in.
EDIT: Ok, I've got it outputting JSON now:
{"mealnumber":1,"id":"69","title":"Protein Packed Meatloaf","description":"This meatloaf is packed with protein to help your muscles grow.","cookingtime":"00:25 ","preptime":"00:10 ","servings":"4.00","rating":"0.000","calories_ps":"205.00","carbohydrate_ps":"7.70","protein_ps":"20.55","fat_ps":"9.64"}
My JS code to try and show that I'm at least reading it correctly:
$(document).ready(function(){
$("#meal1").click(function(){
$.getJSON("testing-01.php?id1="+id1+"&id2="+id2+"&id3="+id3+"&clicked=1", function(data) {
$.each(data.items, function(i, item) {
console.log(item.id);
alert(item.id);
});
});
});
});
However nothing is logged or alerted when I click the div... am I missing something obvious here? I can see in the console that it's calling to the correct page, if I copy and paste the URL I get the json code I pasted above.
Im not sure i understand all you need, but i guess you need to change this 3 ID's in get method.
You could make some simple javascript object that store 3 id's, and rewrite it on success ajax... Buy you need better repsonse then just html... Try json...
$(document).ready(function(){
$("#meal1").click(function(){
$.get("testing-01.php?id1="+SomeJavascriptObject.id1"&id2="+SomeJavascriptObject.id2"&id3="+SomeJavascriptObject.id3"&clicked=1", function(result){
SomeJavascriptObject.id1 =result.returnedID1;
SomeJavascriptObject.id2 = result.returnedID2;
SomeJavascriptObject.id3 = result.returnedID3;
$("#meal1").html(result.html);
});
Maybe this can help you.

How to create a Facebook style "Like" system?

I've been trying to find an example online of a Facebook style "Like" button but have not been able to find anything like this. What I would like to do is, place a button below an image which the user can press. Once pressed it will increment a value in the database for the image's record, and then reflect the addition on the page by adding + 1 to the existing amount. I can guess this will need PHP, SQL and jQuery to pull off. Problem is I have no idea where to begin. I've created already a PHP script to add to my Like's for a particular image by giving the image ID. I created already a jQuery post button which posts to the PHP and likes the image. The thing I'm stuck on is updating the page to reflect the like.
For starters, I think the code I made to do this so far is completely disgusting lol.
Here is all my code so far.
PHP to output the Likes count and Like button, plus code for addition. $info is the array for the result of my whole image files table:
Echo "<b>Likes:</b> ".$info['likes'] . "</span>";
Echo '<script src="http://code.jquery.com/jquery-latest.js"></script><script type="text/javascript">function test() {$.post("http://stormstorm.com/like.php? id='.$info['fileid'].'")</script>';
Echo '<br /><img onClick="test();" src="img/like.jpg"></p>';
The PHP for the like incremented in like.php:
$id = $_GET['id'];
mysql_query("UPDATE files SET likes=likes+1 WHERE fileid=".$id) or die(mysql_error());
The PHP for the liking works fine, I'm happy with that. But the thing to show the liking just sucks badly I think. Thing is I have a list.php which will print the contents of the database one after the other to print all the image listed. So it will print the same replica of the script over and over, typically hard coding the current image ID into the posting. I'm pretty new to this but feel this code sucks, plus it doesn't update the images section.
I was thinking to use Javascript to simply get the Likes element and ++ it but, then it hit me. My list will have over 100+ of these same elements. You can probably tell I might be approaching this the wrong way, and I hope someone can help me out with this.
It looks like you have the general idea down, just a crude implementation of it.
You may want to designate the counter element for each image and update the inner content after the button is pressed...
<img src="xxx.jpg">
<p>
Like <span id="{image_id}_count">150</span>
</p>
where the {image_id} is obviously unique to each image. Pass that to test({image_id}) and then update the html of the count total on success...
function test(id)
{
$.ajax({
url: 'http://stormstorm.com/like.php',
method: 'get',
data: {id: id},
dataType: json,
success: function(data)
{
$('#' + id + '_count').html(data.total);
}
});
}
in your php you would do exactly what you did except return a json encoded array back to the js for update...
$id = mysql_real_escape_string($_GET['id']);
mysql_query("UPDATE files SET likes=likes+1 WHERE fileid=".$id);
if(mysql_affected_rows() > 0)
{
$sql = mysql_fetch_assoc(mysql_query("SELECT `likes` FROM `files` WHERE `fileid` = ".$id));
echo json_encode(array('total' => $sql[0]['likes']));
}
Keep in mind this is a VERY POOR implementation of this. The real system should definitely be one that does not allow people to just repeatedly click the button over and over again to increment something for the hell of it. According to your needs, of course, you should limit it by login and even record user information relative to the file they're liking and not just increment a number in the database.
So you would have a relational table that stores information for each like. That way you can query the database to make sure a user has not already liked the file before incrementing the number.
Hope that makes sense.
I think you are headed the right direction. You can return the number of likes after the update call in php and let jquery update the like count. I added some code below as an example.
HTML:
<form name="like_form">
<input type="hidden" name="id" value="<?php echo $info['fileid']; ?>" />
Likes: <span class="like_count"><?php echo $info['likes']; ?></span>
<img src="img/like.jpg" class="like_click" />
</form>
Javascript:
$(document).ready(function() {
$('img.like_click').click(function() {
var form = $(this).closest('form[name=like_form]');
var id = $(form).find('input[name=id]').val();
$.post("http://stormstorm.com/like.php?id='" + id + "', function(data) {
$(form).find('span.like_count').html(data);
});
});
PHP: (*Note: I didn't check syntax but hopefully it will be enough code to understand the idea.)
$id = $_GET['id'];
mysql_query("UPDATE files SET likes=likes+1 WHERE fileid=".$id) or die(mysql_error());
$result = mysql_query("SELECT likes from files where fileid=" . $id) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['likes'];

how to display iframes with sites from a mysql database?

Hi guys I'm trying to somewhat of an autosurfer and for the life of my I cannot figure out how to use iframes on my site to display all of the sites I have in my mysql database. Now all of the website urls are stored in a column in my table in the database, so I assume I'll need to assign them to an array. But my main problem is getting them to display each site for fifteen seconds then load a different one. I understand iframes for the most part, but I don't get how to get it to show a site, refresh show another, etc. I also can't figure out how to load the sites into an array for the iframe to use. Please help. Thanks.
You will need to use JavaScript to refresh your iframe.
Let's say this is your iframe:
<iframe id="iframe" src="http://www.google.com"></iframe>
You'll need to use JavaScript to do the refresh, and AJAX if you want it to get data from your database. So do something like this in a javascript file (I'm using jQuery):
$(function(){
function refresh_iframe(){
$.get('iframe_url.php', function(data){
// set iframe src to the url that the php gave us
$('#iframe').attr('src', data);
// run this function again in 15s
setTimeout("refresh_iframe()",15000);
});
}
// run the first time
refresh_iframe()
});
Then in iframe_url.php you'd have something like:
<?php
$q = mysql_query("SELECT `url` from `iframe_urls`");
$results = mysql_fetch_assoc($q);
$key = array_rand($results);
echo($results[$key]['url']);
?>

Categories