Can't get pagination to work in a div - php

I have a page showing a picture of a product. Underneath that I have tabs for the Description, Contact Details and Comments. When you click on the Comments tab a comments page is loaded into the div="info" using Jquery.
products.php:
<html>
<head></head>
<body>
<img src="image.jpg">
<hr>
<a id="det"><h3>Details</h3></a> &nbsp<a id="contact"><h3>Contact</h3></a>
&nbsp<a id="comments"><h3>Comments</h3></a>
<div id="info"></div>
</body>
<html>
Jquery:
<script>
$(document).ready(function(){
$("#comments").click(function(){
$("#info").load("comments.php");
});
});
</script>
The comments.php page below uses pagination for the comments.
When I click on the pagination links the page refreshes the comments.php?page=* removing it from the div="info".How do I keep the comments in the div id="info" when I use pagination?
comments.php:
<?php
// 1)Set current page
$current_page = ((isset($_GET['page']) && $_GET['page'] > 0) ?
(int)$_GET['page'] : 1);
require 'connect.php';
// 2)Get total amount of rows
$sql = "SELECT * FROM comments";
$result=mysqli_query($conn,$sql);
$totalrows = mysqli_num_rows($result);
// Offset - calculation to skip to the data you want to display
$results_per_page = 10;
$offset = ($current_page-1)*$results_per_page;
?>
/*------- Comments Form -----*/
/*------- Comments from Database ---- */
<?php
//Here is the code for displaying link and page number.
$number_page = $totalrows/$results_per_page;
for ( $page = 1; $page <= $number_page; $page ++ )
{
echo "<a href='comments.php?page={$page}'>{$page}</a>";
}
?>

You know... you could end this problem doing a js making every link inside the #info element update only inside it. Not sure if is that what you need.
$('#info').on('click', 'a', function (e){
e.preventDefault();
$("#info").load($(this).attr('href'));
});

You need to attach a click event to the links that are loaded in the ajax partial.
The simplest way to do that is to add a class property to any of the links you want to load via ajax, then attach your event to that class.
Example:
<?php
// example just increments the page param
if(strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH', FILTER_SANITIZE_STRING)) == 'xmlhttprequest') {
die('<a class="ajaxlink" href="?page='.($_GET['page']+1).'">Goto page '.($_GET['page']+1).'</a>');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h3><a class="ajaxlink" href="index.php">Contact</a></h3>
<div id="info"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).on("click", ".ajaxlink", function(event) {
event.preventDefault();
if ($(this).prop('href').length > 0) {
$("#info").load($(this).prop('href'));
}
return false;
});
</script>
</body>
</html>

Related

AJAX response includes html from page instead of single value

I have a 'like' button that I have implemented with PHP/MySqL, AJAX and Jquery, which increments likes by +1 each time. It all seems to work fine and updates the database with the new value; however, the response that is returned from the AJAX call is returning all of the html in my .php file that comes before the post handler in my index.php. Other than moving the handler all the way to the top of the page, is there a way of fixing this?
Code below:
index.php
<?php
include './includes/header.php';
?>
<?php
include './includes/title_box.php';
?>
<?php
include './includes/categories_box.php';
?>
<?php
include './includes/roadmap_box.php';
?>
<?php
if(isset($_POST['liked'])) {
$postid = $_POST['postid'];
$query = "SELECT * FROM posts WHERE post_id=$postid";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$n = $row['post_upvotes'];
$query = "UPDATE posts SET post_upvotes=$n+1 WHERE post_id=$postid";
mysqli_query($connection, $query);
echo $n + 1;
exit();
}
?>
<button class="upvote-button" value=<?php echo $id ?>><?php echo $upvotes ?></button>
script.js
$(document).ready(function(){
$(".upvote-button").click(function(){
var postID = $(this).val();
$post = $(this);
$.ajax({
url: './index.php',
type: 'post',
data: {
'liked': 1,
'postid': postID
},
success: function(response){
$post.html(response);
}
});
});
});
console.log(response)
element.style {
}
user agent stylesheet
body {
display: block;
margin: 8px;
}

script.js:14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<title>Product Feedback App</title>
</head>
<body><div class="title-box">
<h1>Frontend Mentor</h1>
<p>Feedback Board</p>
</div><div class="categories-box">
<ul>
<li>All</li>
<li>UI</li>
<li>UX</li>
<li>Enhancement</li>
<li>Bug</li>
<li>Feature</li>
</ul>
</div>
<div class="roadmap-box">
<h2>Roadmap</h2>
View Roadmap
<ul>
<li>Planned - 2</li>
<li>In-Progress - 3</li>
<li>Live - 1</li>
</ul>
</div>
134
Move your if(isset($_POST['liked'])) and all associated code to a separate file and call that file in your Ajax query url.
You will probably need to include the file that connects to your database in the new file as well, but without seeing the contents of your included files it's hard to give specific advice.

Div with anchor tags to load php pages in another div

I have a div tag with many anchor tags in it. On clicking a lick it should open a php page in another div tag of the same page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<header>
<h2>Test</h2>
</header>
<div class="topnav" id="myTopnav">
page1
page2
page3
page4
</div>
<div id="content" >
</div>
<script>
$(function(){
$("#myTopnav a").click(function(e){
e.preventDefault(); //To prevent the default anchor tag behaviour
var url = this.href;
$("#content").load(url);
});
});
</script>
</body>
</html>
I have a nav bar and on clicking the links it should load a php page in content div. I tried the above code but it does not work.
The Reason is that its a local file at your system, you need to set up a webserver.
If the problem exist further then you can add "Cross Origin" headers to the called php files.
If it's not working for you, try the full context and see what the error message might be:
$( "#content" ).load( url, function( response, status, xhr ) {
if ( status == "error" ) {
window.alert(xhr.status + " " + xhr.statusText);
}
});

Select data and display on same page without loading (php/ajax)

I am getting user data by passing the id in url and using the select statement where it matches the id in url and display result
But I want this by using ajax. Please help me
<div id="show_data">
<?php
$id=$_GET['id'];
$category=$_GET['category'];
if ($category==Hosted) {
$result = $wpdb->get_results ("SELECT * FROM wp_user_host WHERE user_id=$id");
foreach ( $result as $print ){
?>
<table>
<tr>
<td>Name: <?php echo $print->drive_name;?</td>
<td>Date: <?php echo $print->drive_date;?</td>
</tr>
</table>
<?php
}
}
?>
</div>
<a href="page.php?id=2&category=Hosted:>VIEW DATA</a>
lets say i have an index file like follow
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
<button id="testDom">click to load dom</button>
<p id="domOutput"></p>
<script>
document.getElementById("testDom").addEventListener('click', function(){
loadAjax();
});
function loadAjax(){
var xmlHttp = new XMLHttpRequest();
var requestUrl = 'test.php';
xmlHttp.onreadystatechange = function(){
if( this.readyState == 4 && ( this.status > 200 || this.status < 300 ) ){
console.log("ok");
document.getElementById("domOutput").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open('GET', requestUrl);
xmlHttp.send();
}
</script>
</body>
lets say if u click the button ajax call made to the php file called test.php
<?php
echo "php file loaded";
ouput will printed in the index.html on p tag.

How to pass database id in jquery

i want to delete a record that are showing in while loop from the database but before deleting i want to display a confirmation box.The code i have written is below.it is working fine but to delete record i need to pass an id that i haave described in the code
------index.php starts
<!DOCTYPE html><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A jQuery Confirm Dialog Replacement with CSS3 | Tutorialzine Demo</title>
<link href='http://fonts.googleapis.com/css?family=Cuprum&subset=latin' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.confirm/jquery.confirm.css" />
</head>
<body>
<div id="page">
<?php
$sql = "SELECT * FROM tablename";
$result = db_query($sql);
while(db_fetch($result))
{
?>
//here we need to pass the fetched record id to script.js file,but i dont know how
<div class="item">
<div class="delete"></div> //here i have applied css i.e it displays wrong icon, when we click on that icon ,it is showing confirmation box. Everything is perfect in this.. but i wnat to pass and id.. im new to jquery
</div>
<?php
}
?>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="jquery.confirm/jquery.confirm.js"></script>
<script src="js/script.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A jQuery Confirm Dialog Replacement with CSS3 | Tutorialzine Demo</title>
<link href='http://fonts.googleapis.com/css?family=Cuprum&subset=latin' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.confirm/jquery.confirm.css" />
</head>
<body>
<div id="page">
<?php
$sql = "SELECT * FROM tablename";
$result = db_query($sql);
while(db_fetch($result))
{
?>
<div class="item">
<div class="delete"></div>
</div>
<?php
}
?>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="jquery.confirm/jquery.confirm.js"></script>
<script src="js/script.js"></script>
</body>
</html>
----index.php ends
----jquery.confirm.js file starts
(function($){
$.confirm = function(params){
if($('#confirmOverlay').length){
// A confirm is already shown on the page:
return false;
}
var buttonHTML = '';
$.each(params.buttons,function(name,obj){
// Generating the markup for the buttons:
buttonHTML += ''+name+'<span></span>';
if(!obj.action){
obj.action = function(){};
}
});
var markup = [
'<div id="confirmOverlay">',
'<div id="confirmBox">',
'<h1>',params.title,'</h1>',
'<p>',params.message,'</p>',
'<div id="confirmButtons">',
buttonHTML,
'</div></div></div>'
].join('');
$(markup).hide().appendTo('body').fadeIn();
var buttons = $('#confirmBox .button'),
i = 0;
$.each(params.buttons,function(name,obj){
buttons.eq(i++).click(function(){
// Calling the action attribute when a
// click occurs, and hiding the confirm.
obj.action();
$.confirm.hide();
return false;
});
});
}
$.confirm.hide = function(){
$('#confirmOverlay').fadeOut(function(){
$(this).remove();
});
}
})(jQuery);
----jquery.confirm.js file ends
-----script.js file starts
$(document).ready(function(){
$('.item .delete').click(function(){
var elem = $(this).closest('.item');
$.confirm({
'title' : 'Delete Confirmation',
'message' : 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
'buttons' : {
'Yes' : {
'class' : 'blue',
'action': function(){
elem.slideUp();
//sql delete query will be written here... in where condition i need to pass the fetched record id from index.php file in where condtion
}
},
'No' : {
'class' : 'gray',
'action': function(){} // Nothing to do in this case. You can as well omit the action property.
}
}
});
});
});
-----script.js ends
You can use the html data attribute and retrieve it with .data jQuery method
In your HTML:
<div class="delete" data-id="{$id}"></div>
In your Javascript
$('.item .delete').click(function(){
var elem = $(this).closest('.item');
var id = elem.data('id'); /* this is your db id */
});
Are you sure you want to send a query from Javascript? The usual way to do this is to send a request (via jQuery) with that specific id, to a script which runs the query (server side), and returns a response.
Now, since you add the item divs, using a while, why not add an id property to the divs, which contain the id from the database, something like
<div id="item<?php echo $row['id'];?>" class="item">
<div class="delete">
</div>
This way, the $('.item .delete').click handler has access to the item's id, by parsing the target's id property, and you don't need to pass it explicitly to jQuery.
Here you can use hidden field to save value for id and then use jquery to retrieve it from hidden field..
while(db_fetch($result))
{
?>
//here we need to pass the fetched record id to script.js file,but i dont know how
<input type="hidden" id="hid_id" value="<?php echo 'fetched id';?>" />
<div class="item">
<div class="delete"></div> //here i have applied css i.e it displays wrong icon, when we click on that icon ,it is showing confirmation box. Everything is perfect in this.. but i wnat to pass and id.. im new to jquery
</div>
<?php
}
?>
And then in jquery when using confirm box you can get value by id hid_id .

Notifications script, how to put data inside of a div

I was trying to create a notifications system for a website with the following code :
setInterval(function() {
$.post('notifications.php', {
email: 123
}, function(data) {
});
}, 30000);
And the notifications.php :
$userid = $_SESSION[username];
$notifications = array();
$sql = "SELECT appreciation FROM ms_notifications WHERE email = '$userid' AND new = '1'";
$res = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($res)) {
while ($r = mysql_fetch_object($res)) {
$notifications[] = $r->appreciation;
}
$nb_result = mysql_num_rows($res);
}
$sql = "UPDATE ms_notifications SET new = '0' WHERE email = '$userid'";
mysql_query($sql) or die(mysql_error());
echo $nb_result;
Problem is that, as I'm new to jquery/Js, I don't know how to put the result inside of a div. For now it stays on the top of the page, above everything.
I tried that, inside the data function but not working... :
$('#test_app').html(data);
I guess it's a very stupid question but help would be really appreciated ! Thank you very much.
UPDATE : Here the HTML Code
<?php
session_start();
include ('connection/database.php');
include ('login_script.php');
include ('notifications.php');
if($logged_in){
?>
<!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>My Home</title>
</head>
<body>
<link rel="stylesheet" type="text/css" href="ms.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/font_i/specimen_files/easytabs.js" type="text/javascript" charset="utf-8"></script>
<!-- FONT SCRIPT-->
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#container').easyTabs({defaultContent:1});
});
</script>
<script type="text/javascript" charset="utf-8">
var scrollSpeed = 70; // Speed in milliseconds
var step = 1; // How many pixels to move per step
var current = 0; // The current pixel row
var imageHeight = 505; // Background image height
var headerHeight = 59; // How tall the header is.
//The pixel row where to start a new loop
var restartPosition = -(imageHeight - headerHeight);
function scrollBg(){
//Go to next pixel row.
current -= step;
//If at the end of the image, then go to the top.
if (current == restartPosition){
current = 0;
}
//Set the CSS of the header.
$('#main_logo').css("background-position","0 "+current+"px");
}
//Calls the scrolling function repeatedly
var init = setInterval("scrollBg()", scrollSpeed)
</script>
<!-- NOTIFICATIONS_SCRIPT !!!!!! -->
<script type="text/javascript" charset="utf-8">
setInterval(function() {
$.post('notifications.php', {
email: 123
}, function(data) {
});
}, 30000);
</script>
<style>
body{
font-family:SommetRoundedLight;
}
</style>
</head>
<body>
<div id="container">
<div id="header_contain">
<div id="test_app">
</div>
</div>
</div>
</body>
</html>
<?php }
else{
echo '<script language="javascript" type="text/javascript">
<!--
window.location.replace("connexion.php");
-->
</script>';
} ?>
Thanks again
Use .append() instead of .html()
Instead of
$('#test_app').html(data);
just use:
$('#test_app').html('<div>' + data + '</div>');
Seems to simple to be it. Am I missing something?

Categories