Jquery Pagination page number limiting - php

I have a functional pagination I built but I now have an issue where the amount of data returned is making the pagination large. I have read through a lot of posts about this issue and havent found anything that was decently close to what I thought I needed. I am looking for my pagination bar to limit the pages. Prev 1 2 3 4 5 6 . . . 11 Next Prev 1 . . . 6 7 8 9 10 11 Next
Jquery
$(function() { //Manage Users Table and Search form JS Start
//loads table page 1 upon loading page.
load_table(1);
/*$("#users_table").tablesorter({
debug: true
}); */
//upon search being clicked the table loads at the first page of result set.
$('#user_search_btn').click(function() {
load_table(1);
});
//global var for the clicking of pages and prev and next buttons.
var page = 1;
$('a.page_link').live('click', function() { //gets the number assigned to the data-page and puts it in page var. load table for page
page = $(this).data('page');
load_table(page);
});
$('#prev').live('click', function() {
//truthy loads page 1 if page - 1 equals 0. falsey loads page - 1.
if(page - 1 == 0) {
page = page;
$('#prev a').removeAttr('href');
}
else {
page = page - 1;
load_table(page);
}
});
$('#next').live('click', function() {
//truthy loads page at its current num which is also max_page
if(page + 1 > max_pages) {
page = page;
$('#next a').removeAttr('href');
}
//falsey loads page if hasnt hit max limit yet + 1
else {
page = page + 1;
load_table(page);
}
});
});
//sets gloabl var to use in multiple functions.
var max_pages = null;
function load_table(page_num) { //function to load the table with data from the providers page. passing a page_num for ajax call reuse.
var search_name = $('#user_name_input').val();
var search_email = $('#user_email_input').val();
var search_company = $('#manage_company_input').val();
var admin_option = $('#admin_user_dropdown option:selected').val();
var active_option = $('#active_user_dropdown option:selected').text();
var page_option = $('#page_limit_dropdown option:selected').val();
$.ajax({
type: 'POST',
url: 'providers/manage_users.php',
data: {mode: 'table_data', company: search_company, name: search_name, email: search_email, admin: admin_option, active: active_option, page_limit: page_option, page_num: page_num},
dataType: 'json',
success: function(data) {
if(data.success == true) {
// sets max_pages each to a rounded up number of the total rows divided by the limit.
max_pages = Math.ceil(data.total_rows / page_option);
//clears out previous data in the table and pagination bar
$('#table_body').html('');
$('#pagination_list').html('');
//Cycles through each row of data in the json array and assigns them to vars.
$.each(data.row, function(j, object) {
var group_id = (object.group_id);
var acct_id = (object.acct_id);
var company = (object.company);
var first_name = (object.first_name);
var last_name = (object.last_name);
var name = (first_name + ' ' + last_name);
var email = (object.email);
var city = (object.city);
var admin = (object.admin);
var active = (object.active);
if(active == 1) {
active = 'yes';
}
else {
active = 'no';
}
//sets each row to a single row from json array
row_show(group_id, acct_id, company, name, email, city, admin, active);
});
//checks if only 1 page of data no pagination bar
if(max_pages > 1) {
pagination();
//sets the current page to the active class
$('#page_'+page_num+'').addClass('active');
//makes the previous and next buttons on the bar active class when conditions are met.
if(page_num == 1) {
$('#prev').addClass('active');
}
if(page_num == max_pages) {
$('#next').addClass('active');
}
}
}
}
});
}
function row_show(group_id, acct_id, company, name, email, city, admin, active){ //function to setup the table row and 5 colmuns of data that the ajax call cycles through.
var html = '\
<tr>\
<td><div><a title="'+company+'" id="company_'+group_id+'" href="edit_facility.php?id='+group_id+'">'+company+'</a></div></td>\
<td><div><a title="'+email+'" id="company_'+acct_id+'" href="edit_user.php?id='+acct_id+'">'+email+'</a></div></td>\
<td><div>'+name+'</div></td>\
<td><div>'+city+'</div></td>\
<td><div>'+admin+'</div></td>\
<td><div>'+active+'</div></td>\
</tr>';
//attachs the above data to the table.
$('#table_body').append(html);
}
function pagination() { //function to make the pagination bar
var current_page = 1;
var html = '<li id="prev">‹ Prev</li>';
//loops through each page according to max_pages and gives it a li el and a el
while(max_pages >= current_page) {
html += '<li id="page_'+current_page+'">';
//data-page used later when clicked to get the current page to load in the ajax call.
html += '<a class="page_link" href="#" data-page="'+current_page+'">'+(current_page)+'</a>';
current_page++;
html += '</li>';
}
html += '<li id="next">Next ›</li>';
$('#pagination_list').append(html);
}
HTML
<table id="users_table" class="tablesorter table table-bordered table-condensed">
<thead id="table_head">
<td><strong>Company</strong></td>
<td><strong>Email</strong></td>
<td><strong>Name</strong></td>
<td><strong>City</strong></td>
<td><strong>Role</strong></td>
<td><strong>Active</strong></td>
</thead>
<tbody id="table_body">
</tbody>
</table>
<div id="user_pagination" class="pagination pagination-centered">
<ul id="pagination_list">
</ul>
</div>

CREATE TABLE messages
(
msg_id INT PRIMARY KEY AUTO_INCREMENT,
message TEXT
);
jquery_pagination.js
$(document).ready(function()
{
//Display Loading Image
function Display_Load()
{
$("#loading").fadeIn(900,0);
$("#loading").html("<img src="bigLoader.gif" />");
}
//Hide Loading Image
function Hide_Load()
{
$("#loading").fadeOut('slow');
};
//Default Starting Page Results
$("#pagination li:first")
.css({'color' : '#FF0084'}).css({'border' : 'none'});
Display_Load();
$("#content").load("pagination_data.php?page=1", Hide_Load());
//Pagination Click
$("#pagination li").click(function(){
Display_Load();
//CSS Styles
$("#pagination li")
.css({'border' : 'solid #dddddd 1px'})
.css({'color' : '#0063DC'});
$(this)
.css({'color' : '#FF0084'})
.css({'border' : 'none'});
//Loading Data
var pageNum = this.id;
$("#content").load("pagination_data.php?page=" + pageNum, Hide_Load());
});
});
config.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd)
or die("Opps some thing went wrong");
?>
pagination.php
<?php
include('config.php');
$per_page = 9;
//Calculating no of pages
$sql = "select * from messages";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript" src="jquery_pagination.js"></script>
<div id="loading" ></div>
<div id="content" ></div>
<ul id="pagination">
<?php
//Pagination Numbers
for($i=1; $i<=$pages; $i++)
{
echo '<li id="'.$i.'">'.$i.'</li>';
}
?>
</ul>
pagination_data.php
<?php
include('config.php');
$per_page = 9;
if($_GET)
{
$page=$_GET['page'];
}
$start = ($page-1)*$per_page;
$sql = "select * from messages order by msg_id limit $start,$per_page";
$result = mysql_query($sql);
?>
<table width="800px">
<?php
while($row = mysql_fetch_array($result))
{
$msg_id=$row['msg_id'];
$message=$row['message'];
?>
<tr>
<td><?php echo $msg_id; ?></td>
<td><?php echo $message; ?></td>
</tr>
<?php
}
?>
</table>
CSS Code
#loading
{
width: 100%;
position: absolute;
}
li
{
list-style: none;
float: left;
margin-right: 16px;
padding:5px;
border:solid 1px #dddddd;
color:#0063DC;
}
li:hover
{
color:#FF0084;
cursor: pointer;
}
Try this. It should help you.

Related

Creating Dynamic Pages with php and MySQL

I am creating a list of links in main.php using "donemler" table in mySQL database and would like to create a page that shows data from "sikkeler" table (which has a foreing key donemID that is used as a relationship between the two tables) as the user clicks it. (data.php is a part of the index.php which is a infinite scroll page)
Here I tried to call $row["donemID"] with GET method using
$k=$_GET['donemID'] in index.php but did not work.
I have also tried to use SESSIONS method where I add "$_SESSION['donemID']=$row$row["donemID"] to main.php
and called it back in index.php as
$k=$_SESSION['donemID']
but it also did not work.
I would like to learn how to create pages and show relevant data in php.
Thanks in advance!
main.php
<?php
require_once "config.php";
$sql = $conn->query("SELECT * FROM donemler ORDER BY donemID");
if ($sql->num_rows > 0) {
// output data of each row
while($row = $sql->fetch_assoc()) {
echo "<tr><td><a href='index.php?devletID=".$row["devletID"]."&donemID=".$row["donemID"]."'>" .$row["donemler"]. "</a></td></tr>";
}
} else {
echo "0 results";
}
$conn->close();
?>
index.php
<script type="text/javascript">
var start = 0;
var limit = 20;
var reachedMax = false;
var dnmID = $_GET("donemID");
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height() )
getData();
});
$(document).ready(function () {
getData();
});
function getData() {
if (reachedMax)
return;
$.ajax({
url: 'data.php',
method: 'POST',
dataType: 'text',
data: {
getData: 1,
start: start,
limit: limit,
dnmID: dnmID,
},
success: function(response) {
if (response == "reachedMax")
reachedMax = true;
else {
start += limit;
$(".results").append(response);
}
}
});
}
</script>
data.php
<?php
if (isset($_POST['getData']) ) {
$conn = new mysqli('localhost', 'usrnm', 'pss', 'db');
$dnmID = $conn->real_escape_string($_POST['dnmID']);
$start = $conn->real_escape_string($_POST['start']);
$limit = $conn->real_escape_string($_POST['limit']);
$sql = $conn->query("SELECT * FROM sikkeler WHERE donemID='$dnmID' ORDER BY kayit_no DESC LIMIT $start, $limit");
if ($sql->num_rows > 0) {
$response = "";
while($data = $sql->fetch_array()) {
$response .= '
<tr>
<td>ICD#'.$data['kayit_no'].'</td>
<td>'.$data['donemi'].'</td>
<td><img src="coin_images/'.$data['resim'].'" border="2" width="200px" /></td>
<td>'.$data['darp'].'</td>
<td>'.$data['tarih'].'</td>
<td>'.$data['birim'].'</td>
<td>'.$data['agirlik'].'</td>
<td>'.$data['cap'].'</td>
<td>'.$data['tip'].'</td>
<td>'.$data['reference'].'</td>
</tr>
';
}
exit($response);
} else
exit('reachedMax');
}
?>
You are checking through two different request methods:
$_POST['getData']
$k=$_GET['donemID']
Since you are using the query strings, it is a GET method to check with.
There is no such variable i.e. getData on main.php

jquery php mysql - how to hide load more button when all itemes displayed

I have a code for showing list from database and a loadmore button. After all records list is displayed and click on loadmore button show empty places.
How to hide loadmore button once all records displayed?
index.php file:
<?php $chinp=$_GET['schinp'];?>
<div id="schts"></div>
<button id="btnsch">load more</button>
<script>
$(document).ready(function() {
var chinp="<?php echo $chinp;?>";
var srchco = 1;
var offsrch = 0;
$("#btnsch").click(function() {
$.ajax({
method: "POST",
url: "search.php",
data: { srchcoun: srchco, offsrch: offsrch ,chinp:chinp}
})
.done(function(msg) {
$("#schts").append(msg);
});
offsrch = offsrch + srchco;
});
$("button").trigger("click");
});
</script>
search.php :
$srchcoun=$_POST['srchcoun'];
$offsrch=$_POST['offsrch'];
$chinp=$_POST['chinp'];
$schql="SELECT id, name, lastname FROM t_users WHERE name LIKE '$chinp' ORDER BY name ASC limit $offsrch, $srchcoun";
$rsch=mysqli_query($conn,$schql);
while ($rch=mysqli_fetch_assoc($rsch)){
$scid=$rch['id'];$snm=$rch['name'];$slnm=$rch['lastname'];?>
<div class="alsu">
<img class="sask" src="pic/<?php echo $scid;?>.png" alt="">
<span class="snm">Name : <?php echo $snm." ".$slnm;?></span>
</div>
<?php }?>
</div>
Thanks.
Here is code to hide load more button as per your code.
Replace this code in your first file.
<script type="text/javascript">
$(document).ready(function() {
var chinp="<?php echo $chinp;?>";
var srchco = 2;
var offsrch = 0;
var page_num = 0;
$("#btnsch").click(function() {
$.ajax({
method: "POST",
url: "search.php",
data: { srchcoun: srchco, offsrch: offsrch ,chinp:chinp, page_num : page_num}
})
.done(function(msg) {
if(msg == 'noMoreData'){
$("#btnsch").hide();
} else {
$("#schts").append(msg);
}
});
page_num = page_num + 1;
offsrch = offsrch + srchco;
});
$("#btnsch").trigger("click");
});
</script>
Now add this code in your search file.
<?php
$srchcoun=$_POST['srchcoun'];
$offsrch=$_POST['offsrch'];
$chinp=$_POST['chinp'];
$page_num=$_POST['page_num'];
$total_records = 0;
$totalschql="SELECT id FROM t_users WHERE name LIKE 'krishna' ORDER BY name ASC";
if ($result=mysqli_query($conn,$totalschql))
{
$total_records=mysqli_num_rows($result);
}
$last_records_count = ($page_num) * $srchcoun;
if($last_records_count >= $total_records) {
echo 'noMoreData';exit();
} else {
$schql="SELECT id, name, lastname FROM t_users WHERE name LIKE '$chinp' ORDER BY name ASC limit $offsrch, $srchcoun";;
$rsch=mysqli_query($conn,$schql);
while ($rch=mysqli_fetch_assoc($rsch)){
$scid=$rch['id'];$snm=$rch['name'];$slnm=$rch['lastname'];
?>
<div class="alsu">
<img class="sask" src="pic/<?php echo $scid;?>.png" alt="">
<span class="snm">Name : <?php echo $snm." ".$slnm;?></span>
</div>
<?php }?>
</div>
<?php
}
?>
Try this and let me know if you have any issue.
Simply use $('#myButtonId').hide(); in ajax part after you load the entire data from database.
function get_rain_data_list(is_load_more=0){
if(is_load_more!=0){//if is_load_more is not 0 then get offset data from btnlod attr
offset = $('#btn_load_more_rain').attr("data-offset");
}else{ //set offset =0 when is_load_more is 0
offset = 0;
}
var id = $('#id').val();
var countShow = 0;
if(fromDate!=''){
countShow = 1;
}
$.ajax({
url: base_url+"rain_data_list_ajax",
type: "POST",
data:{offset:offset,propertyId:propertyId,fromDate:fromDate,toData:toData},
dataType: "JSON",
beforeSend: function() {
show_loader();
},
success: function(data){
hide_loader();
// console.log(data);
$('.proprty_load_more_btn').remove();//remove load more button
if(offset==0){ //clear div when offset 0
$("#append_rain_list").html('');
}
if(data.no_record==0){//show data in div when no previous record
$("#append_rain_list").html(data.html_rain);
$("#add_count").html('');
if(countShow){
//$("#add_count").html(data.count+data.record);
}
}else{
//append data when already record show in view
$("#append_rain_list").append(data.html_rain);
$("#append_load_btn").append(data.btn_html);
$("#add_count").html('');
if(countShow){
$("#add_count").html(data.count+data.record);
}
}
},
});
}
<div id="append_rain_list"></div>
<div id="add_count"></div>
<?php
function rain_data_list_ajax(){
$limit = 6;
$is_next = 0;
//get and set offset
$offset = $this->input->post('offset');
$data['property_id'] = decoding($this->input->post('propertyId'));
$fDate = sanitize_input_text($this->input->post('fromDate'));
$tDate = sanitize_input_text($this->input->post('toData'));
$new_offset = $limit+$offset; //pr($data);
//set where
$where = array('property_id'=>$data['property_id']);
//set select field to get
$data['limit'] = $limit;
$data['offset'] = $offset;
//get count of records
$dataView['total_count'] = $this->Property_model->get_rain_count($data);
//get records
$dataView['rain_list'] = $this->Property_model->get_rain_list($data);
///lq();
//check for load more btn
//pr($dataView);
if($dataView['total_count']>$new_offset){
$is_next =1;
}
$btn_html = '';
if($is_next){
//if is next =1 set load more button in btn_html
$id = "btn_load_more_rain";
$btn_html = '<div class="col-sm-12 text-center pt-20 proprty_load_more_btn"><button class="login-btn load load_more_btn" id = "'.$id.'" data-offset ="'.$new_offset.'" data-isNext ="'.$is_next.'" >'.lang('load_more').'</button></div>';
}
//load view with data
$html_rain = $this->load->view('test1',$dataView,true);
$response = array('status'=>1,'html_rain'=>$html_rain,'btn_html'=>$btn_html,'count'=>$dataView['total_count'],'record'=>lang('recod_found'));
//flag for no record
$no_record=1;
if(empty($dataView['rain_list'])){
$no_record = 0;
}
$response['no_record'] = $no_record;
echo json_encode($response);die;
}
?>

Retrieving a value from a database and display in tooltip

I have created a tooltip using javascript and have an html page using that tooltip.
Here is my tooltip:
$(document).ready(function () {
//Tooltips
$(".tip_trigger").hover(function (e) {
tip = $(this).find('.tip');
var tipText = $(e.target).attr('ti');
tip.html(tipText);
tip.show(); //Show tooltip
}, function () {
tip.hide(); //Hide tooltip
}).mousemove(function (e) {
var mousex = e.pageX + 20; //Get X coodrinates
var mousey = e.pageY + 20; //Get Y coordinates
var tipWidth = tip.width(); //Find width of tooltip
var tipHeight = tip.height(); //Find height of tooltip
//Distance of element from the right edge of viewport
var tipVisX = $(window).width() - (mousex + tipWidth);
//Distance of element from the bottom of viewport
var tipVisY = $(window).height() - (mousey + tipHeight);
if (tipVisX < 20) { //If tooltip exceeds the X coordinate of viewport
mousex = e.pageX - tipWidth - 20;
} if (tipVisY < 20) { //If tooltip exceeds the Y coordinate of viewport
mousey = e.pageY - tipHeight - 20;
}
tip.css({ top: mousey, left: mousex });
});
});
Here is HTML:
<div class="container">
<h1><span>Simple Example</span></h1>
<map name="Koala" class="tip_trigger">
<area ti="This is the left eye" shape="rect" coords="373,365,404,402" href="#" />
<area ti="Right Eye" shape="rect" coords="641,405,681,448" href="#" />
<div class="tip"></div>
I want the database value to display where "ti" is... ex. ti="database value"
How can this be done? I will be using MySQL along with php. All help I will be very grateful for.
Create a help table in mysql:
CREATE TABLE `help` (
`helpID` varchar(100) NOT NULL,
`helpText` text NOT NULL,
UNIQUE KEY `helpID` (`helpID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
For a generic tooltip, on the page where you want the help tip, put this html:
<span id="productSKUHelp" class="helpTip questionMark"></span>
Since you want the tooltip to appear when your cursor is in a certain spot, you should be able to use your mousemove function and call showTip.
Add the following JQuery:
function showTip(thisTip){
var postdata = {
helpTip: thisTip.attr('id')
};
$.ajax({
type : "post",
url : "/getHelpRPC.php",
dataType: "html",
data : postdata,
success : function(data){
if(data.length > 0){
var origContent = thisTip.html();
thisTip.removeClass("questionMark").addClass('helpTipBox');
thisTip.html(data);
}else{
$('#helpTipBox').html("error");
}
},
error : function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
$(document).on('mouseenter', '.helpTip', function(){
var thisTip = $(this);
helpTipTimer = setTimeout(function(){
showTip(thisTip);
},
1000);
})
$(document).on('click', '.helpTip', function(){
showTip($(this));
})
$(document).on('mouseleave', '.helpTip', function(){
clearTimeout(helpTipTimer);
$(this).html('').removeClass('helpTipBox').addClass('questionMark');
});
Add the following CSS:
.helpTip{
padding-left:3px;
z-index:900;
}
.questionMark:after{
color:maroon;
cursor:pointer;
content:"?";
top:2px;
position:relative;
padding:0 3px;
}
.helpTipBox{
padding:5px;
background-color:#97abcc;
position:absolute;
curson:text;
}
Create the getHelpRPC.php RPC:
<?php
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB);
if($mysqli->connect_errno){
printf("Connect failed: %s %s %s\n", $mysqli->connect_error, __FILE__, __LINE__);
exit();
}
$helpID = $_POST['helpTip'];
if($helpID != ""){
$querystr = "SELECT helpText FROM help WHERE helpID ='" . $mysqli->real_escape_string($helpID) . "'";
$res = $mysqli->query($querystr);
$rowCount = $res->num_rows;
if($rowCount > 0){
$row = $res->fetch_object();
echo $row->helpText;
} else {
echo "error selecting help.";
}
}
Now all you need to do is create a unique id in the span and add the corresponding record to the table.

php with jquery html pop up

this is actually a part of huge project so i didnt include the css but im willing to post it here if actually necessary.
Ok i have this code
<html>
<head>
<script src="js/jquery.js"></script>
<script type="text/javascript">
var q = "0";
function rr()
{
var q = "1";
var ddxz = document.getElementById('inputbox').value;
if (ddxz === "")
{
alert ('Search box is empty, please fill before you hit the go button.');
}
else
{
$.post('search.php', { name : $('#inputbox').val()}, function(output) {
$('#searchpage').html(output).show();
});
var t=setTimeout("alertMsg()",500);
}
}
function alertMsg()
{
$('#de').hide();
$('#searchpage').show();
}
// searchbox functions ( clear & unclear )
function clickclear(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (q === "0"){
if (thisfield.value == "") {
thisfield.value = defaulttext;
}}
else
{
}
}
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var q = "0";
$.post('tt.php', { name : $(this).attr('id') }, function(output) {
$('#pxpxx').html(output).show();
});
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<img src="images/close_pop.png" class="btn_close" title="Close Window" alt="Close" />');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
</script>
</head>
<body>
<input name="searchinput" value="search item here..." type="text" id="inputbox" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><button id="submit" onclick="rr()"></button>
<div id="searchpage"></div>
<div id="backgroundPopup"></div>
<div id="popup" class="popup_block">
<div id="pxpxx"></div>
</div>
</body>
</html>
Ok here is the php file(search.php) where the jquery function"function rr()" will pass the data from the input field(#inputbox) once the user click the button(#submit) and then the php file(search.php) will process the data and check if theres a record on the mysql that was match on the data that the jquery has pass and so if there is then the search.php will pass data back to the jquery function and then that jquery function will output the data into the specified div(#searchpage).
<?
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='http://".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
}
else
{
echo "Yay! There's an error occured upon checking your request";
}
?>
and here is the php file(tt.php) where the jquery a.poplight click function will pass the data and then as like the function of the first php file(search.php) it will look for data's match on the mysql and then pass it back to the jquery and then the jquery will output the file to the specified div(#popup) and once it was outputted to the specified div(#popup), then the div(#popup) will show like a popup box (this is absolutely a popup box actually).
<?
//session_start(); start up your PHP session!//
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE id='$name'");
while($row = mysql_fetch_array($result))
{
$ss = "<table border='0' align='left' cellpadding='3' cellspacing='1'><tr><td>";
$ss .= '<img class="ddx" src="Images/media/'.$row['name'].'" />'."</td>";
$ss .= "<td>"."<table><tr><td style='color:#666; padding-right:15px;'>Name</td><td style='color:#0068AE'>".$row['title']."</td></tr>";
$ss .= "<tr><td style='color:#666; padding-right:15px;'>Description</td> <td>".$row['description']."</td></tr>";
$ss .= "<tr><td style='color:#666; padding-right:15px;'>Link</td><td><a href='".$row['link']."'>".$row['link']."</a></td></tr>";
$ss .= "</td></tr></table>";
}
echo $ss;
mysql_close($con);
}
?>
here is the problem, the popup box(.popup_block) is not showing and so the data from the php file(tt.php) that the jquery has been outputted to that div(.popup_block) (will if ever it was successfully pass from the php file into the jquery and outputted by the jquery).
Some of my codes that rely on this is actually working and that pop up box is actually showing, just this part, its not showing and theres no data from the php file which was the jquery function should output it to that div(.popup_block)
hope someone could help, thanks in advance, anyway im open for any suggestions and recommendation.
JULIVER
First thought, the script is being called before the page is loaded. To solve this, use:
$(document).ready(function()
{
$(window).load(function()
{
//type here your jQuery
});
});
This will cause the script to wait for the whole page to load, including all content and images
if you're using ajax to exchange data into a php file. then check your ajax function if its actually receive the return data from your php file.

HTML not getting changed after jQuery call is made successfully

I have a voting mechanism on the site. When people vote up or down, this code is called:
// Called right away after someone clicks on the vote up link
$('.vote_up').click(function()
{
var problem_id = $(this).attr("data-problem_id");
queue.voteUp = $(this).attr('problem_id');
var span = $(this).closest('span').find('span.votes');
queue.span = span;
vote(problem_id , 1);
//Return false to prevent page navigation
return false;
});
and the vote function that it calls looks like this:
var vote = function(problem_id , vote)
{
if ( vote == 1 )
{
queue.voteUp = problem_id;
}
else
if ( vote == -1 )
{
queue.voteDown = problem_id;
}
var dataString = 'problem_id=' + problem_id + '&vote=' + vote;
// The person is actually logged in so lets have him vote
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
text = queue.span.text ();
if ( vote == -1 )
{
if ( data == "update_success" )
{
incrementedText = parseInt(text ,10) - 2;
}
else
{
incrementedText = parseInt(text ,10) - 1;
}
}
else
if ( vote == 1 )
{
if ( data == "update_success" )
{
incrementedText = parseInt(text ,10) + 2;
}
else
{
incrementedText = parseInt(text ,10) + 1;
}
}
queue.span.text(incrementedText + " ");
},
error : function(data)
{
errorMessage = data.responseText;
if ( errorMessage == "not_logged_in" )
{
queue.login = false;
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
// $dialog.dialog('open');
$("#loginpopup").dialog();
errorMessage = "";
// prevent the default action, e.g., following a link
return false;
}
else
if ( errorMessage == "already_voted" )
{
// Display a dialog box saying that the user already voted
$('<div />').html('You already voted this way on this problem.').dialog();
}
else
if ( errorMessage == "error_getting_vote" )
{
$('<div />').html('Error getting existing votes.').dialog();
}
else
{
// ? :)
}
} // End of error case
}); // Closing AJAX call.
};
and here is the PHP that made the HTML for the vote button. The link is called "important" or "not important" :
echo '<span class="half_text" style="color: #B77F37;">'.$problem_date.'</span>
<span id="votes" class="half_text" style="padding-left: 10px;">'.$vote.'</span>
<strong> <a class="vote_up" style="font-size: 80.0%; color: #295B7B; font-weight:bold; text-decoration:none;" href="#" data-problem_id="'.$problem_id.'">Important</a></strong>
|
<strong><a class="vote_down" style="font-size: 80.0%; color: #295B7B; font-weight:bold; text-decoration:none;" href="#" data-problem_id="'.$problem_id.'">Not Important</a></strong>';
When a user votes, the AJAX gets called, and everything works ok. The only problem is that the HTML does not get updated with the new vote count. Any idea how I can accomplish that?
In your JavaScript you attempt to select the <span id="votes"> using the votes class ($(this).closest('span').find('span.votes');). So I recommend changing:
<span id="votes" class="half_text" style="padding-left: 10px;">
To:
<span class="votes half_text" style="padding-left: 10px;">
I recommend using a parent element to make your selector work properly:
$('.vote_up').click(function() {
console.log($(this).parents('div:first').children('.votes'));
});
//this requires there to be a div element that is the ancestor of the code you posted
Here is a jsfiddle of the above solution: http://jsfiddle.net/jasper/DzZCY/1/

Categories