on click change questions displayed - 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.

Related

I need to refactor this php function

I need to refactor this code, Im not a php developer so i dont understand the syntax thats apparent here, what i want is this button to activate the moment the page is loaded.
<?php
$h = '';
if ($newsermonstomove) {
foreach ($newsermonstomove as $vettel) {
$h .= "<div style=\"padding: 5px;\">";
$h .= "<button id=\"btn_" . $vettel->ID . "\" class=\"btn btn-primary btn-xs\" onclick=\"doMe(" . $vettel->ID . ");\" >s3</button><span style=\"padding-left:5px;\">Channel: " . $vettel->ChannelID . ", Sermon: " . $vettel->ID . " " . $vettel->SermonTitle . "</span> <div style=\"display:none;color:blue;\" id=\"msg_" . $vettel->ID . "\"></div><br/>";
$h .= "</div>";
}
} else {
$h = "<h3>No new sermons.</h3>";
}
echo $h;
?>
From what i understand, the onclick has an escape in it onclick=\"doMe(" . $vettel->ID . ");\" In HTML i know that with a button if you do onclick=doMe its a reference to a function, which i feel like is the same thing thats happening here with the escape keys in it. its making a reference to the function doMe, but i want the function to fire automatically when the page loads.
Ok, i was able to figure out the answer I needed using JQuery.
$("document").ready(function() {
setTimeout(function() {
$(".btn").trigger('click');
},10);
});
essentially what this function does is wait for the page to load then after 10 milliseconds it targets all buttons on the screen with the class name btn and triggers the click functionality of the button, thus firing off the button on the page load.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<?php
if (!empty($newsermonstomove)) {
$h = '';
foreach ($newsermonstomove as $vettel) {
$h .= '<div style="padding: 5px;">';
$h .= '<button data-id="' . $vettel->ID . '" class="btn-vettel btn btn-primary btn-xs">s3</button><span style="padding-left:5px;">Channel: ' . $vettel->ChannelID . ', Sermon: ' . $vettel->ID . ' ' . $vettel->SermonTitle . '</span> <div style="display:none;color:blue;" id="msg_'.$vettel->ID.'"></div><br/>';
$h .= '</div>';
}
} else {
$h = '<h3>No new sermons.</h3>';
}
echo $h;
?>
<script>
$(function() {
$('.bt-vettel').on('click', function(e) {
var id = $(this).data('id');
doMe(id);
});
});
<script>

Ajax Div Refreshing Too Fast

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&nbsp' . $row["pieceWidth"] . ' x&nbsp' . $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,

PHP MySQL Database Images Toggler

I have built a little uploader that works fine, uploading the images file path to my DB, and storing the image in a folder.
Now I also have made a call that will call only images with the same ID as the Property ID it has assigned.
Where I have trouble is the Image display, I am looking for a simple way to toggle between the images in the database, but even before that, I need to know why the Database call only displays one of the images stored in the DB.
Here is my code so far :
PHP
if ($id) {
$query = "SELECT houses.*, gallery_photos.* " .
"FROM houses LEFT JOIN gallery_photos " .
"ON $id = gallery_photos.photo_category";
$result = mysql_query($query) or die(mysql_error());
}
// Print out the contents of each row into a table
while ($row = mysql_fetch_array($result)) {
$images_dir = "houses";
$photo_caption = $row['photo_caption'];
$photo_filename = $row['photo_filename'];
$photo_id = $row['photo_id'];
}
and the display happens withing a larger ECHO command, I will add a little of it so you get the idea :
Within the ECHO
echo "
<li>
<div id='imagizer'> <img src='" . $images_dir . "/" . $photo_filename ."?id=" . $photo_id . " ' title='$photo_caption'/></div>
</li>
There are many more elements within the li element that work fine, like Title, Price, Summary, etc etc.... But I can simply not accomplish 3 thing here :
Getting all the images to display (I only get one, which would be fine if the toggler worked).
Making a toggler to display the next image that has the same category_id.
Optional (An image slider)
UPDATE
This is kind of working, but I get various duplicate entries! It seems that for every picture I get 1 entry on the list. So if 4 pics, 4 entries, if 2, only 2 entries.
function showShort() {
$houses = #mysql_query('SELECT houses.*, gallery_photos.*
FROM houses LEFT JOIN gallery_photos
ON houses.id = gallery_photos.photo_category');
if (!$houses) {
die('<p> Error retrieving Propertys from database!<br />' . 'Error: ' . mysql_error() . '</p>');
}
while ($house = mysql_fetch_array($houses)) {
$id = $house['id'];
$title = htmlspecialchars($house['title']);
$ref = $house['ref'];
$summary = htmlspecialchars($house['summary']);
// $content = $house['content'];
$price = $house['price'];
$houseorder = $house['houseorder'];
$pool = $house['pool'];
$bedrooms = $house['bedrooms'];
$bathrooms = $house['bathrooms'];
$aircon = $house['aircon'];
$basement = $house['basement'];
$location = $house['location'];
$floorm = $house['floorm'];
$aream = $house['aream'];
$garage = $house['garage'];
$furbished = $house['furbished'];
$images_dir = "houses";
$photo_caption = $house['photo_caption'];
$photo_filename = $house['photo_filename'];
$photo_category = $house['photo_category'];
$photo_id = $house['photo_id'];
if ($garage == 'Yes') {
($garage = "Garage : Yes<br>");
} elseif ($garage == 'No') {
($garage = "");
}
if ($pool == 'Yes') {
($pool = "Swimming Pool : Yes<br>");
} elseif ($pool == 'No') {
($pool = "");
}
if ($aircon == 'Yes') {
($aircon = "Air Condition : Yes<br>");
} elseif ($aircon == 'No') {
($aircon = "");
}
if ($basement == 'Yes') {
($basement = "Basement : Yes<br>");
} elseif ($basement == 'No') {
($basement = "");
}
if ($furbished == 'Yes') {
($furbished = "Furbished : Yes<br>");
} elseif ($furbished == 'No') {
($furbished = "");
}
echo "
<li>
<div id='summarybox'>
<div id='titlestyle'> $title </div><br>
<div id='imagebox'> </div>
<div id='refstyle'> Ref. $ref </div>
<div id='details1'>
Bedrooms : $bedrooms <br>
Bathrooms: $bathrooms <br>
Living Area : $floorm m² <br>
Plot Area : $aream m² <br>
Location : $location <br>
</div>
<div id='details2'>
$pool
$aircon
$basement
$furbished
$garage </div>
<section class='ac-container'>
<div>
<input id='$id' name='accordion-1' type='checkbox' />
<label for='$id' >Read More</label>
<article class='ac-small'>
<div id='summarystyle'> $summary </div>
<div id='price'>Price : $price </div><br>
<div id='imagizer' align='center'>
<ul id='$id'>
<li><a href='" . $images_dir . "/" . $photo_filename . "' rel='lightbox[$photo_category]' title='$photo_caption'><img src='" . $images_dir . "/" . $photo_filename . "' height='50%' with='50%'/></a></li>
</ul>
</article>
</div>
</selection>
<br>
<div id='admbuttons'><a href='editProperty.php?id=$id' ><button>Edit</button></a>
<a href='deleteProperty.php?id=$id' onclick='return confirm()'> <button>Delete</button></a></div>
</div>
</li>";
}
}
This is the live example where i have used this idea just open the below link and click on the thumb image and then slide inside the lightbox.
Inspect the image with firebug and see the anchor tags below the image you will get the logic what i am trying to say and then you can manage it into your code
http://dev.tasolglobal.com/osclass/
your echo statement should be like in for loop
while ($row = mysql_fetch_array($result)) {
$images_dir = "houses";
$photo_caption = $row['photo_caption'];
$photo_filename = $row['photo_filename'];
$photo_id = $row['photo_id'];
echo "
<li>
<div id='imagizer'> <img src='" . $images_dir . "/" . $photo_filename ."' id=" . $photo_id . " title='$photo_caption'/></div>
</li>
}
id and src should have some space to print in echo.
please add above code in you for loop sure it will work for you.
The main thumb single image
<a href="url of the first image" rel="lightbox['unique name for a particular bunch of image']><img src="url of the first image" /></a>
Just fire a query and get all the image url only for the particular category and run a loop for the urls to create anchor tags with rel
for($b=1;$b<$thumb_url;$b++)
{
echo = '';
}
These image url are in the href so will not load on page load and when the lightbox will be triggered on the click of the first image it will load all the images with a particular unique string in the rel="lightbox[]" and will show next and previous link to show images like slider
You can use "cat_" then the unique id of a particular category to make unique the rel of those particular images.
I have tried it and it works
UPDATE
What you need to do is do not loop the li but just place the first image in the li inside the img tag and the unique rel and then after the li you have to run the loop for the rest of the category images and create anchor tag with image url in the href and rel similar to the first image
Do not forget to include the js and css for the light box
<div id='imagizer' align='center'>
<ul id='$id'>
<li><a href='" . $images_dir . "/" . $photo_filename . "' rel='lightbox[$photo_category]' title='$photo_caption'><img src='" . $images_dir . "/" . $photo_filename . "' height='50%' with='50%'/></a></li>
</ul>
//Put your loop here to make the anchor tags and keep the url in the href only with the rel corresponding to the first image so they will be treated as a bunch by lightbox
Create a common select function and try query with it and then use for loop on the result associative array it will be less confusion and neat code
Execute Select Query
function select ($sql="", $fetch = "mysql_fetch_assoc")
{
global $conn;
$results = #mysql_query($sql,$conn);
if(!$results) {
echo mysql_errno()." : ". mysql_error();
}
$data = array();
while ($row = $fetch($results))
{
$data[] = $row;
}
mysql_free_result($results);
return $data;
}

PHP Search: Using Jquery to alter a php a value

I have a comics website. A feature it has is to allow users to search comics... the search will instantly parse the input and return thumbnail results based on matching title and keywords.
Originally, the search would return all of the results, and the bounding search box would expand infinitely downward, holding every single comic result. I thought it may be a nice touch to limit the results to 4, and display a message like "load 5 remaining images" if the user chooses to do so.
If they click on that message, I wanted limiting php variable to be removed or changed.
So far, it loads with the limit, and shows a link...
EDIT: Latest Code:
search_field.php (the search file that get's included on a page... this file calls search.php via JQuery):
<?php $site = (isset($_GET['site']) ? ($_GET['site']) : null); ?>
<div id="sidebar" class="searchborder">
<!--Allow users to search for comic-->
<!--<span class="search">Search for <?php// echo (($site == "artwork") ? 'artwork' : 'a comic'); ?> </span>-->
<script type="text/javascript">
function GetSearch(mySearchString){
$.get("./scripts/search.php", {_input : mySearchString, _site : '<?php echo $site ?>'},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
</script>
<center>
<table>
<tr>
<td>
<span class="search">
<img src="./images/SiteDesign/Search.png" />
<input type="text" onkeyup="GetSearch(this.value)" name="input" value="" />
<!--<input id="site" type="hidden" value="<?php// echo $site; ?>">-->
</span>
</td>
</tr>
</table>
</center>
<span id="output"> </span>
</div>
search.php, the file that's called to parse the string and return the results:
<?php
//Query all images:
include 'dbconnect.php';
$site = $_GET['_site'];
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : $site);
$start = (isset($_GET['_start']) ? ($_GET['_start']) : null);
echo "start: " . $start;
//if user goes to hittingtreeswithsticks.com... no "site" value will be set... so I need to set one
if ($site == null) {
$site = "comics";
}
if ($siteChoice == "artwork") {
$sql = "SELECT id, title, keywords, thumb FROM artwork";
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else if ($siteChoice == "comics") {
$sql = "SELECT id, title, keywords, thumb FROM comics";
$thumbpath = "./images/Comics/ComicThumbnails/";
}
else {
$sql = "SELECT id, title, keywords, thumb FROM $site";
if ($site == "artwork") {
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else {
$thumbpath = "./images/Comics/ComicThumbnails/";
}
}
/* For this to work, need all comics replicated in an "All Comics" file along with "All Thumbnails"
else {
$sql = "SELECT id, title, thumb FROM comics
UNION
SELECT id, title, thumb FROM artwork";
$thumbpath = "./images/AllThumbnails/";
}*/
$imgpaths = $mysqli->query($sql);
mysqli_close($mysqli);
$idresult = array();
$imgresult = array();
$thumbresult = array();
//CHECK IF $INPUT == IMAGE PATH
if (strlen($input) > 0)
{
while ($row = $imgpaths->fetch_assoc())
{
//query against key words, not the image title (no one will remember the title)
if (stripos($row['keywords'], $input) !== false || strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
//if (strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
{
array_push($idresult, $row['id']);
array_push($imgresult, $row['title']);
array_push($thumbresult, $row['thumb']);
}
}
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
if (count($imgresult) > $max) {
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo "<br/><i><a href='.?action=homepage&site=" . $siteChoice . "&start=4' class='loadSearch'>load " . $difference . " more result" . (($difference != 1) ? 's' : '') . "... </a></i>";
}
else {
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
}
echo "</ul>";
}
}
?>
<script type="text/javascript">
$(".loadSearch").click(function() {
//alert("Test");
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
});
</script>
Try this:
<script type="text/javascript">
$("#loadSearch").click(function() {
$.get('URL WITH QUERY', function(data) {
$('#results').html(data);
});
});
</script>
From what i get all you need is when "load more" is clicked only new results should be shown.
Load more has to be a url same as your search url.
Search/Autocomplete URL - example.com/autocomplete?q=xkd
Load More URL - example.com/autocomplete?q=xkd&start=4&max=1000
Just add two parameters to your url. start and max. Pass them to your queries and you get exact result.
Only verify Start < Max and are integers intval() and not 0 empty(). Also if Max <= 4 then dont show load more.
I would give all of your results back, then try to determine your results. If more then 4, loop out the first 4 results. If the user clicks on the load more button your start looping from your 4th element. That way you only need to hit the server once (per search).
Try to give back your results in json, so you can format it the way you like in your html file.
In pseudo code:
searchTerm = 'hello';
resultsFromServer = getResults($searchterm);
resultcounter = count(resultsFromServer);
if(resultcounter > 4)
loop 4 results
else
loop all results
$(".loadSearch").click(function(e) {
//alert("Test");
e.preventDefault();
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
I ended up going with jquery show and hide functions.
PHP Snippet:
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo '<div id="moreResults">';
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
echo '</div>';
if (count($imgresult) > $max) {
?>
<br />Load <?php echo $difference; ?> more result<?php echo (($difference != 1) ? 's' : ''); ?>...
<?php
}
echo "</ul>";
}
}
Jquery:
<script type="text/javascript">
$("#moreResults").hide();
$("#showMore").click(function() {
$("#moreResults").show();
$("#showMore").hide();
});

Get "ActivityID" from a PHP file and put it in a JS script.

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'] . '">

Categories