what i have is a list of posts on a page then each post has an icon to add to favorites (also has a watch button but it works the exact same to this) when clicked it calls the page with the script to add this post to ur favorites list in the database. (before using ajax i used a php redirect which returned to the previous page) when the page gets refreshed the database gets checked for what posts you have on your favorites list and will show the appropriate image depending on if its on ur favorites list or not.
When i click the link it appears to do what it should (go to the page and runs the update query to the database) but rather than refresh the div it just clears it. when i press f5 to refresh the page the image now displays the ticked image as it should so the query to the database is made when i click and the div gets kind of refreshed but it requires a proper refresh for it to display.
echo '<div id = "favwatchbox'.$ID.'">';
if($_SESSION['Valid'] == "True" ){
$userid = $_SESSION['ID'];
$check= "SELECT * from UserFavoritePost WHERE UserID='$userid' AND PostID='$ID'";
$resultcheck = $db->query($check);
$num_resultcheck = $resultcheck->num_rows;
$checklater= "SELECT * from UserViewLaterPost WHERE UserID='$userid' AND PostID='$ID'";
$resultchecklater = $db->query($checklater);
$num_resultchecklater = $resultchecklater->num_rows;
$prelogin = $_SERVER["REQUEST_URI"];
if($num_resultcheck >= 1)
{
echo "<a id = 'favdel".$ID."' href='#'><img id='Fav' title='Favorited' src='images/site-design/Favoritecheck.png'></a>";
?>
<script>
$(function() {
$("#favdel<?echo$ID;?>").click(function(evt) {
$("#favwatchbox<?echo$ID;?>").load("sql-scripts/deletefavorite.php?post=<?echo $ID;?>&user=<?echo $userid;?>&pre=<?echo $prelogin;?>")
evt.preventDefault();
})
})
</script>
<?
}
else
{
echo "<a id = 'favadd".$ID."' href='#'><img id='Fav' title='Mark as Favorite' src='images/site-design/Favorite.png'></a>";
?>
<script>
$(function() {
$("#favadd<?echo$ID;?>").click(function(evt) {
$("#favwatchbox<?echo$ID;?>").load("phpincludes/markasfavorite.php?post=<?echo $ID;?>&user=<?echo $userid;?>&pre=<?echo $prelogin;?>")
evt.preventDefault();
})
})
</script>
<?
}
}
the page for deleting from favourites
<?php
include '../phpincludes/dbconnection.php';
$userid = $_GET['user'];
$postid = $_GET['post'];
$query = "DELETE FROM UserFavoritePost WHERE UserID='$userid' And PostId='$postid'";
$result = $db->query($query);
$presubmit = $_GET['pre'];
if($presubmit == "/myaccount.php")
{
header("location:".$presubmit."");
}
?>
i have included an img src in the delete from favorites php file and now when you click it does the update and updates the image but when i click the link again to re add to my favorites it just brings me to the top of the page. if i refresh and click it will then run the add script but it still isnt refreshing the div properly
Related
I am building online exam system, test page is built using php and jquery. Questions are coming from different page using jquery ajax method and for every test there is a temporary test table which is deleted after every test, this table stores current test's question id and response marked by the student. What I am doing or want to do is when the user clicks on submit button this question is marked as done on the left side bar which contains all the questions.
I am doing this by checking the temporary table and fetching the question id from that table and marking it colored using jquery, it is working fine for some questions and skipping some(some gets colored but some are not)randomly.
Can someone help me with this?
Here's my jquery code to fetch question id
$("#submit").click(function(){
$.post( "getquesupdate.php", function( data ) {
$("#q"+data).addClass("doneques");
});
});
and this my getquesupdate page code
<?php
session_start();
include("includes/conn.php");
$table_name = $_SESSION['table_name'];
$sql = "SELECT qid FROM `$table_name` ";
$result = mysqli_query($db,$sql);
if (mysqli_num_rows($result) > 0) {
while( $row = mysqli_fetch_array($result,MYSQLI_ASSOC) )
{
$id = $row['qid'];
}
}
echo $id;
?>
Screenshot of the test page
I am trying to create a drop down menu that shows more information about each person displayed when the person is clicked on.
//Get users information
$sql = "SELECT user.uid, user.first, user.last, user.email, user.rating
FROM user
INNER JOIN team_members ON user.uid=team_members.uid
WHERE tid = '$tid'
ORDER BY user.last ASC";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
//name as button(displayed on page load)
echo "<button class='player' type='submit'>
".$row["first"]." ".$row["last"]."</button><br>";
//hidden information to be shown once button clicked
echo "<div class='player_info' style='display:none'>
".$row["email"]." ".$row["rating"]."
</div>";
}
$(document).ready(function(){
$('button.player').click(function(){
$('div.player_info').toggle();
});
});
The issue I am having is that when clicked it displays all information in each loop. So if there are 5 people and you click one name, each person populates information. The information corresponds to each person but I only want to show the info of the person clicked.
I thought this would mean that I need to somehow uniquely identify each class but cant seem to figure it out and make it work. Or maybe there is a better way to run my loop to solve the problem. Any input is appreciated. Thank you.
You can use HTML data- attributes to correlate each button to a div. Then modify the JavaScript to use the embedded data.
In the below snippet, I added data-uid attributes to both the button and the div that are populated with the uid from the database.
When the button is clicked, the data-uid is read and used to select the div with corresponding data-uid.
Another small improvement that I made was to change the type attribute on the button to button. A value of submit means that the button should be used for submit a form which is not what you are doing here.
//Get users information
$sql = "SELECT user.uid, user.first, user.last, user.email, user.rating
FROM user
INNER JOIN team_members ON user.uid=team_members.uid
WHERE tid = '$tid'
ORDER BY user.last ASC";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
//name as button(displayed on page load)
echo "<button class='player' type='button' data-uid='".$row["uid"]."'>
".$row["first"]." ".$row["last"]."</button><br>";
//hidden information to be shown once button clicked
echo "<div class='player_info' style='display:none' data-uid='".$row["uid"]."'>
".$row["email"]." ".$row["rating"]."
</div>";
}
$(document).ready(function(){
$('button.player').click(function(){
$('div.player_info[data-uid='+$(this).attr('data-uid')+']').toggle();
});
});
Wrap your .player and .player_info in a <div> and do some toggling with JQuery like so:
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class='player-container'>
//name as button(displayed on page load)
echo "<button class='player' type='submit'>
".$row["first"]." ".$row["last"]."</button><br>";
//hidden information to be shown once button clicked
echo "<div class='player_info' style='display:none'>
".$row["email"]." ".$row["rating"]."
</div>";
echo "</div>
}
$(document).ready(function(){
// hide all of the player_info containers
$(".player_info").hide();
$(".player-container").click(function() {
// this selects any child element of the clicked container with the
// classname .player_info and toggles it open or closed
$(this).children(".player_info").slideToggle();
});
});
You aren't specifying which player_info you want to toggle, $('div.player_info') will select all of them. A quick and dirty way to solve this would be to use select the next sibling with jQuery, relative to the button, like so:
$(document).ready(function(){
$('button.player').click(function(){
$(this).next().toggle();
});
});
I have a problem displaying the confirmation message before deleting a data
if(isset($_POST['del'])){
echo "
<script>
var x;
x = confirm ('You want to proceed deleting?');
if(x == true){";
for($i=0;$i<$_SESSION['count'];$i++){
$checkbox = $_POST['checkbox'];
$del_id = $checkbox[$i];
$query = mysql_query("SELECT picture FROM tblreserve WHERE id='$del_id'");
while($row = mysql_fetch_assoc($query)){
$del_pic = $row['picture'];
}
$sql = "DELETE FROM tblreserve WHERE id = $del_id";
$result = mysql_query($sql);
if($result){
if(is_file($del_pic)){
unlink($del_pic);
}
}
}
header('location:view.php');
echo "}
else{
location.href = 'view.php';
}
</script>";
}
You can't use JavaScript to control what PHP is output, as the PHP is executed on the server side, whereas the JavaScript is executed by the client, you can however integrate confirmation into your delete buttons using JavaScript like the example below:
<button onclick="if (confirm('Are you sure you want to delete?')) window.location = 'some_other_page.php'">Delete</button>
When the confirmation box prompted in your browser, all your php code is all parse in the file. Delete the data in mysql is via php, so you want to confirm this by clicking the javascript prompted button, you should refresh your page by sending a tag in from url, or you can implement it via ajax.
In you given snippet, php can not be halted there by the javascript confirm. You should know one is server end, the other is client-end
i am trying to implement pagination. A set of 9 products are displayed at a time. then upon clicking on a "View More" button, the content of a div should refresh by AJAX and show the next set of 9 products..here's the php code
if(!isset($_SESSION['current'])){
$query = "SELECT MAX(addedon) AS addedon FROM tags";
$result = mysql_query($query);
report($result);
$dated = mysql_fetch_assoc($result);
$recent = $dated['addedon'];
$_SESSION['current'] = $recent;
}
$query = "SELECT id, addedon
FROM tags
WHERE addedon <= '{$_SESSION['current']}'
ORDER BY addedon DESC
LIMIT 9
";
$result = mysql_query($query);
report($result);
while($row = mysql_fetch_assoc($result)){
$_SESSION['current'] = $row['addedon'];
$id = $row['id'];
$query = "SELECT name, image, cost
FROM tags, stock
WHERE tags.id={$id} AND stock.tagid = tags.id
";
$result1 = mysql_query($query);
report($result1);
$prodInfo = mysql_fetch_assoc($result1);
$pname = $prodInfo['name'];
$pimg = $prodInfo['image']; //the path to the actual image
$pcost = $prodInfo['cost'];
echo "<div class=\"oneproduct\">";
echo "<h3>{$pname}</h3><br />";
echo "<img src=\"{$pimg}\" height=\"{$ht}\" width=\"85px\" alt=\"prodImg\" /><br />";
echo "<span>Rs. {$pcost}</span>";
echo "<input type=\"image\" src=\"images/addcart.png\" class=\"addBtn\" />";
echo "</div>";
}
after all the products would be fetched and displayed, the last product on the page is stored as 'current' variable of SESSION.
problem is: the ajax thing always returns the initial set of 9 products and as soon as i refresh the page, the next set of products are coming..how do i make my link change the content?
The ajax code:
$("#viewMore").bind('click', function(){
$.ajax({
url:'showNineProds.php',
type:'POST',
dataType:'html',
success:function(data){
$("div#nineproducts").html(data);
},
error:function(xhr, status){
alert("Problem");
},
complete:function(xhr, status){
}
});
});
showNineProds.php simply calls a function that has been written above..
The correct way to do this is for the client-side code to specify with parameters to the AJAX call which "page" of records to be fetched. By using a session variable like this, the server has no concept of which records to get at which time. It's always going to return the "next" result. So any time you load that web page, it's going to serve the "next" set of records. There's no way to page backward in the result set.
Basically, you would store in local JavaScript values (or hidden form elements on the page, however you feel comfortable storing a value on the page) the information of the current result set and your AJAX call would send the necessary information to the server to return the requested result set.
For example, you could have a local JavaScript value that says which start record you're seeing and your page size:
startRecord = 1;
pageSize = 10;
Then if you click your "next" button the AJAX call would supply parameters to the server telling it what to fetch:
startRecord + pageSize, pageSize
You'd want to add a little bit of logic to determine if you're on the first or last page to disable "prev" and "next" functionality, of course. And there's a lot more you can do (variable page sizes, filtering and searching, sorting, etc.) but this is the basic gist of it.
You don't seem to be sending back the info from the ajax call. basically yoi might be fetching the values on the DB but don't seem to be sending the data back to the call..
do you echo the result set in some format? I can't see that in the code. in any case you can't access the $session variables from the js... these are accessible server side in php.
I am working on making a album-viewer like facebook.
I have made the "setup", you can see the photo, what album its in and so, now I would like to make the "next" "previous" buttons work.
I have seen them using preloading while viewing a current, and i wish to accomplish something like that.
But first of all, how can I make the "next"? What are the procedure to make the "next" work.
With this I mean how should I code it, so it knows which picture is next? I would like to sort it from the date(order by date), so the next should be newer than the current date, and previous older than the current date.
My database looks like this:
album
id uID title
album_photos
id aID uID photo date
aID holds the id of the album(album ID), uID holds the id of the user(userID).
I also want to make use of javascript too. Make an ajax request, instead of refreshing whole page.
So my question is:
What is the procedure of making next/prev button, if I would like to make it work after date DESC, how does the javascript look like? An ajax request to file.php, that are grabbing the latest image from the database and then on success it replace the current photo and show it? What about the adressbar, in facebook the adressbar changes align with loading new photo.
Any well explained answer for procedure of making this, will accept the answer
This here will load images from the database using ajax (next/previous). Also includes guides and a preloader (hosted here http://www.preloaders.net/). Let me know if you have any questions.
Here you go. these are 3 files
index.php ...display page
ajax.php ...read database for images
show.php ...loads images
just remember to set host, user, password & databasename in ajax.php
copy & paste these:
1. index.php
<?php
include("ajax.php");
?>
<script type="text/javascript" src="JQUERY/jquery.js"></script>
<script>
var ID = "<?php echo $id; ?>";
var inc = ID + 1;
var dec = ID;
var totalpages = "<?php echo $totalpages + 1; ?>";
$(function(){
$('.loader').hide();
<!-- np = next & prev button functions -->
$('.np').click(function() {
if($(this).attr('id') == "next") {
$(this).attr('push', inc++);
if($(this).attr('push')<totalpages) {
$.ajax({url:"show.php", data:"id=" + $(this).attr('push'), success: AjaxFunc, cache:false });
$('.loader').show();
dec = inc - 2;
$('#images').hide();
}
}
else if($(this).attr('id') == "prev") {
$(this).attr('push', dec--);
if($(this).attr('push')>-1) {
$.ajax({url:"show.php", data:"id=" + $(this).attr('push'), success: AjaxFunc, cache:false });
$('.loader').show();
inc = dec + 2;
$('#images').hide();
}
}
});
});
<!-- this function is called after ajax send its request -->
function AjaxFunc(return_value) {
$('#images').html(return_value);
$('.loader').hide();
$('#images').show();
}
</script>
<div id="images">
<!-- loads default numbers of images. whats inside here will change once you click next or prev -->
<?php
for($i=$id * $limit; $i<$limit + $id * $limit; $i++) {
echo $imagearray[$i]."<br/>";
}
?>
</div>
<!-- next & previous buttons -->
<a class="np" id="prev" push="<?php echo $id; ?>" href="#">Prev</a>
<a class="np" id="next" push="<?php echo $id + 1; ?>" href="#">Next</a>
<!-- preloader. hidden on start. will show while images load -->
<img class="loader" src="http://www.preloaders.net/generator.php?image=75&speed=5&fore_color=000000&back_color=FFFFFF&size=64x64&transparency=0&reverse=0&orig_colors=0&uncacher=26.066433149389923"/>
2. ajax.php
<?php
//id is tjhe page number. it is 0 by default. while clicking next/prev, this will not change. set it like this: file?id=0
$id = $_GET['id'];
//connect to the databsae
$host="localhost";
$user = "username";
$password = "";
$database = "database_name";
$connect = mysql_connect($host, $user, $password) or die("MySQL Connection Failed");
mysql_select_db($database) or die ("Database Connection Fail");
//set your the limit of images to be displayed
$limit = 5;
//push images into array
$q = mysql_query("SELECT * FROM image_table");
$num = mysql_num_rows($q);
while($r = mysql_fetch_array($q)) {
$imagearray[] = "<img src='"
.$r['IMAGE_URL']
."'/>";
}
//will determine total number of pages based on the limit you set
$totalpages = ceil($num/$limit) - 1;
?>
3. show.php
<?php
include("ajax.php");
for($i=$id * $limit; $i<$limit + $id * $limit; $i++) {
echo $imagearray[$i]."<br/>";
}
?>
If you are sorting your photos by date DESC and you got the current photos date do the following:
To find the next photo: Order your photos by date DESC and select the first photo whos date is smaller than the date of the current photo. Fetch only the first one.
To find the prev photo: Order your photos by date ASC and select the first photo whos date is greater than the date of the current photo. Fetch only the first one.
Construct the SQL-Statements for this by yourself.