jQuery on click , execute too many times - php

I'm making a pagination with jQuery Ajax,php and mysql, 1 by 1.
I want to show cards with name and description.
Here I leave my code.
Index.php
<?php
require_once './conexiones.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Language" content="kr">
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<link rel="stylesheet" type="text/css" href="cards.css">
<meta http-equiv="Content-Language" content="ko">
<meta http-equiv="Content-Type" content="text/html; charset=UTF8">
<title></title>
<script type="text/javascript" src="jquery-ui-1.10.3.custom.min.js"></script>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="card.js"></script>
</head>
<body>
<?php
// ----- CONSULTA PALABRAS POR CATEGORIA
if((isset($_GET['idcat']))||(isset($_GET['limite']))){
$consulta = "
SELECT nompalabra, trapalabra, rompalabra, imgpalabra, ejpal, ejrompal, ejtrapal
FROM palabra
WHERE idcat = '". $_GET['idcat'] ."'
LIMIT ". $_GET['limit'].",1
";
echo $consulta;
$resultado = mysql_query($consulta,$conexion);
}
//----- FIN
//CONSULTA TODAS LAS CATEGORIAS
$consultaCategorias = "
SELECT nomcat
FROM categorias";
$resultadoCategorias = mysql_query($consultaCategorias,$conexion);
//
require_once './carta.php';
?>
</body>
cards.js
var limit = 0;
$(document).on("click",".cat",function(){
var cat = $(this).attr('name');
limit = 0;
var id;
switch (cat){
case 'casa': id = 1;
break;
case 'colores': id = 2;
break;
case 'cuerpo': id = 3;
break;
}
$.get("index.php",{"idcat":id,"limit":limit},function(data) {$("#contenedor").html(data);});
});
$(document).on("click",".next",function(){
var id = $(this).attr('name');
limit++;
$.get("index.php",{"idcat":id,"limit":limit},function(data){$("#contenedor").html(data);});
});
$(document).on("click",".back",function(){
var id = $(this).attr('name');
limit--;
$.get("index.php",{"idcat":id,"limit":limit},function(data){$("#contenedor").html(data);});
});
cartas.php
<?php
require_once './consultas.php';
?><div id="contenedor"><?php
while($categoria = mysql_fetch_array($resultadoCategorias)){
?><div class="cat" name="<?php echo $categoria['nomcat'];?>"><?php echo $categoria['nomcat'];?></div> <?php
}
if(isset($_GET['idcat'])){
?>
<div id="container_card">
<div id="container_card_top">
<div class="centrar"> <?php
while ($fila = mysql_fetch_array($resultado)) {
echo $fila['nompalabra']."(".$fila['rompalabra'].") ".$fila['trapalabra'];
?>
</div>
</div><!-- FIN CONTAINER_CARD_TOP -->
<div id="container_card_content">
<div id="imagenPalabra"><?php echo $fila['imgpalabra'];?></div>
<div class="frase"><?php echo $fila['ejpal'];?></div>
<?php } ?>
<div class="next" name="<?php echo $_GET['idcat'];?>">-></div>
<?php if($_GET['limit']>0){ ?><div class="back" name="<?php echo $_GET['idcat'];?>"><-</div><?php } ?>
</div><!-- FIN CONTAINER_CARD_CONTENT -->
</div><!-- FIN CONTAINER_CARD -->
<?php } ?>
each time I click on .next, the counter should be 0, 1, 2, 3 ... but when I do the first time, the jQuery function execute 2 times, and next time I click on it, it executes more times, so I cannot show 1 by 1 and I don't know how to fix it. I already tried many things.

Maybe with every click the script creates the same handlers again ...
Try to change cards.js to something like that:
var limit = 0;
$(document).ready(function() {
$('.cat').click(function() {
var cat = $(this).attr('name');
limit = 0;
var id;
switch (cat){
case 'casa':
id = 1;
break;
case 'colores':
id = 2;
break;
case 'cuerpo':
id = 3;
break;
}
$.get("index.php",{
"idcat":id,
"limit":limit
},function(data) {
$("#contenedor").html(data);
});
});
$('.next').click(function() {
var id = $(this).attr('name');
limit++;
$.get("index.php",{
"idcat":id,
"limit":limit
},function(data){
$("#contenedor").html(data);
});
});
$('.back').click(function() {
var id = $(this).attr('name');
limit--;
$.get("index.php",{
"idcat":id,
"limit":limit
},function(data){
$("#contenedor").html(data);
});
});
});

Related

progressbar para ciclos for em php

My question is very simple. I have some cycles within other cycles, however, let's imagine it's just one and I want to use a progress bar to only show the progress of this cycle.
I have here code that I am developing, in which I use UIKit, but that is making my head hurt because everything works except the progress bar.
The memory consumption is also a complete exaggeration, because through the task manager I see RAM being completely consumed!
The code I'm using is this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="uikit3/css/uikit.min.css" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="uikit3/js/uikit.min.js"></script>
</head>
<body>
<progress id="progressbar" class="uk-progress" value="0" max="100"></progress>
<div id="information" style="width"></div>
<div id="information2" style="width"></div>
<?php
ini_set('memory_limit','16M');
$total = 1741768;
$x = 0;
for($n1=1; $n1 < 15; ++$n1)
{
for($n2=($n1+1); $n2<48; ++$n2)
{
for($n3=($n2+1); $n3<49; ++$n3)
{
for($n4=($n3+1); $n4<50; ++$n4)
{
for($n5=($n4+1); $n5<51; ++$n5)
{
++$x;
$percent = intval($x/$total * 100);
echo '<script language="javascript">document.getElementById("information").innerHTML="'.$percent.'"</script>';
echo '<script language="javascript">document.getElementById("information2").innerHTML="'.$x.'"</script>';
echo '<script>
jQuery(function () {
var animate = setInterval(function () {
window.progressbar && (progressbar.value = "'.$percent.'");
if (!window.progressbar || progressbar.value >= progressbar.max) {
clearInterval(animate);
}
},0);
});
</script>';
}
}
}
}
}
echo '<script language="javascript">document.getElementById("information").innerHTML="Chaves Geradas!"</script>';
?>
</body>
</html>

.append() with Database

I'm trying to retrieve information from my database, and output it to my page. I'm able to hardcore it, so to show exactly what I want to be able to do is located here:
I'm not having any console errors in the javascript, but I am unable to append data to the list once it is clicked.
HTML & JS:
<!doctype html><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="../img/sd.ico" />
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="body">
<div id="header"><h1>Bookmarks</h1></div><!-- header -->
<iframe id="iFrame" name="iFrame"></iframe>
<div id="links"><ul id="accordion">
<li><div class="bookmarkTitle"><p><h4>CareerResources</h4></p></div></li><ul id="CareerResources">
</ul><li><div class="bookmarkTitle"><p><h4>CSS</h4></p></div></li><ul id="CSS">
</ul><li><div class="bookmarkTitle"><p><h4>JS</h4></p></div></li><ul id="JS">
</ul><li><div class="bookmarkTitle"><p><h4>JS: Jquery</h4></p></div></li><ul id="JS: jQuery">
</ul></div><!-- links end -->
</div><!-- body end -->
<script type="text/javascript">
$(document).ready(function(){
$("#accordion > li").click(function(e){
var catName=$(e.target).text();
$.getJSON("get.php?catName=" + catName, function(data){
if (data.data){
$.each(data.data,function(index,value){
var url = value.URL;
var title = value.title;
var desc = value.desc;
alert(catName);
$("#"+catName).append('<div class="bookmark"><p><h3>'+title+'</h3><br />'+desc+'</p></div>');
});
}
});
});
});
</script>
</body>
</html>
PHP:
// retval: 0 - login ok, 1 - login failed, 2 - internal error
$json = array("retval" => 2, "data" => NULL, "debug" => "");
$catName=mysql_real_escape_string($_REQUEST['catName']);
$sql="SELECT * FROM linktb WHERE catName='$catName'";
$json['debug'] .= "SQL query was: ".$sql."\n";
$result=mysql_query($sql);
if (!$result) {
$json['debug'] .= "SQL query failed\n";
$json['debug'] .= "Other output: ". ob_get_contents();
ob_end_clean();
die(json_encode($json));
}
$count=mysql_num_rows($result);
if($count > 0){
$json['retval'] = 0;
$json['data'] = array();
while ($row = mysql_fetch_assoc($result)){
$json['data'][] = $row;
}
} else {
$json['retval'] = 1;
}
$json['debug'] .= "Other output: ". ob_get_contents();
ob_end_clean();
echo json_encode($json);
var catID=e.target.text(); Should be var catID=$(e.target).text(); as .text() is a jQuery method.
If you want to iterate through the returned data you'll have to do it in the success function. Also from your php script you only output one row from your database.
if($count > 0){
$json['retval'] = 0;
$json['data'] = array();
while ($row = mysql_fetch_assoc($result)){
$json['data'][] = $row;
}
}
else {
$json['retval'] = 1;
}
$.getJSON("get.php?catID=" + catID, function(data){
if (data.data){
$.each(data.data,function(index,value){
var url = value.URL;
var title = value.title;
var desc = value.desc;
$("#"+catID).appendText('<div class="bookmark"><p><h3>'+title+'</h3><br />'+desc+'</p></div>');
});
}
});

Switch between two javascript functions

basically I want php to decide which version of the site pieces to load
something along the lines of:
<?php
$sql="SELECT _1 FROM Player_Registry WHERE Player_Name = $_SESSION[user_name]";
$result_1=mysql_query($sql);
if($result_1 < 10) { ?>
<script type="text/javascript">
function setdescription_1() {
document.getElementById('title_box').innerHTML = 'Alchemist';
}
</script>
<?php
}
else {
?>
<script type="text/javascript">
function setdescription_1() {
document.getElementById('title_box').innerHTML = 'Master Alchemist';
}
</script>
<?php
}?>
issue is that they both run so even if I set the condition to true I still get the second.
The complete source which is identical to what is being viewed-as-source as far as I can tell but none of the php shows up in the site preview (it is actually there though because my other computer can view the site without seeing the php but when it views source it can see it which it shouldn't be able to):
<head>
<title>Blank</title>
<link rel="icon" type="image/png" href="Pictures/favicon.png">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<meta name="owner" content="" />
<meta name="copyright" content="" />
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" href="TreeStyle.css" type="text/css" />
</head>
<body>
<div style="width:100%; height:12.5%;">
<p style="font-size: 300%;"><b>Skill Tree: Alchemist</b></p>
</div>
<div style="width:100%; height:75%;">
<?php
$sql="SELECT _1 FROM Player_Registry WHERE Player_Name = $_SESSION[user_name]";
$result_1=mysql_query($sql);
if($result_1 < 10)
{
?>
<script type="text/javascript">
function setdescription_1()
{
document.getElementById('title_box').innerHTML = 'Alchemist';
document.getElementById('desc_box').innerHTML = 'Turn surroundings into base element costs.';
}
</script>
<?php
}
else
{
?>
<script type="text/javascript">
function setdescription_1()
{
document.getElementById('title_box').innerHTML = 'Master Alchemist';
document.getElementById('desc_box').innerHTML = 'Equiped Philosopher's Stone allows bypass of element costs.';
}
</script>
<?php
}
$sql="SELECT _2 FROM Player_Registry WHERE Player_Name = $_SESSION[user_name]";
$result_2=mysql_query($sql);
if($result_2 < 10)
{
?>
<script type="text/javascript">
function setdescription_2()
{
document.getElementById('title_box').innerHTML = 'Learn Runes';
document.getElementById('desc_box').innerHTML = 'Create Runes and Cores up to Lv.<?php echo "$result_2" ?>';
}
</script>
<?php
}
else
{
?>
<script type="text/javascript">
function setdescription_2()
{
document.getElementById('title_box').innerHTML = 'Comprehension';
document.getElementById('desc_box').innerHTML = 'Create Runes and Cores up to Lv.10';
}
</script>
<?php
}
?>
<script type="text/javascript">
function cleardescription()
{
document.getElementById('title_box').innerHTML = 'Skill Name';
document.getElementById('desc_box').innerHTML = 'This is the skill description.';
}
</script>
<table>
<tr>
<td></td>
<td><img src="Alchemist.png" /></td>
<td><img src="Blank_Tile.png"/></td>
<td><a href='AddSkillPoints.php?skill=_2' onmouseover="setdescription_2()" onmouseout="cleardescription()"><img src="Learn_Runes.png"/></td>
etc..............
</table>
</div>
<div style="width:100%; height:12.5%;">
<b><p id="title_box" style="font-size: 150%;">Skill Name</p></b><br />
<p id="desc_box">This is the skill description.</p>
</div>
</div>
</body>
</html>
I do not believe you get both if your PHP is actually parsed.
If it is not parsed, you will see the code you pasted exactly as you pasted it if you look at the source of the web page
Make sure the php is parsed - if not, then that is the issue.
A script tag will generally not interfere with parsing unless you have to post processing that does not allow the tags - for example if you use some kind of framework where you are not supposed to enter php but instead some tokenised code
Here is a better example - note I moved the script to the head but did not optimise really - so the php can be more elegant if you get both values in one call and create an object array
<?PHP
$sql="SELECT _1 FROM Player_Registry WHERE Player_Name = $_SESSION[user_name]";
$result_1=mysql_query($sql);
$sql="SELECT _2 FROM Player_Registry WHERE Player_Name = $_SESSION[user_name]";
$result_2=mysql_query($sql);
%><html>
<head>
<title>Blank</title>
<link rel="icon" type="image/png" href="Pictures/favicon.png">
.
.
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" href="TreeStyle.css" type="text/css" />
<script type="text/javascript">
var result1 = parseInt("<?PHP echo $result_1; ">,10);
var skillLevel = (result1>=10?'Master ':'')+'Alchemist';
var skillDesc = result1>=10?"Equipped with Philosopher´s Stone allows bypass of element costs.":"Turn surroundings into base element costs.";
var runeLevel = result2>=10?'Comprehension':'Learn Runes';
var runeDesc = 'Create Runes and Cores up to Lv.'+result2;
window.onload=function() {
setdescription_1();
}
function setdescription_1() {
document.getElementById('title_box').innerHTML = skillLevel;
document.getElementById('desc_box').innerHTML = skillDesc;
}
function setdescription_2() {
document.getElementById('title_box').innerHTML = runeLevel;
document.getElementById('desc_box').innerHTML = runeDesc;
}
function cleardescription() {
document.getElementById('title_box').innerHTML = 'Skill Name';
document.getElementById('desc_box').innerHTML = 'This is the skill description.';
}
</script>
</head>

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?

jquery simple pager with first , last

<code>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery.pager.js Test</title>
<link href="Pager.css" rel="stylesheet" type="text/css" />
<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="jquery.pager.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#pager").pager({ pagenumber: 1, pagecount: 15, buttonClickCallback: PageClick });
});
PageClick = function(pageclickednumber) {
$("#pager").pager({ pagenumber: pageclickednumber, pagecount: 15, buttonClickCallback: PageClick });
$("#result").html("Clicked Page " + pageclickednumber);
}
</script>
</head>
<body>
$query = "select name from student";
$result = mysql_query(Query);
while($row=mysql_fetch_array($result)){
$student_name = $row['name'];
?>
<h1 id="result"><?php echo $student_name; ?></h1>
<? }
?>
<div id="pager" />
</body>
</html>
</code>
For my above code am not geting the student name , if i remove the pager script , the student name will appear, may i know , why, where i made mistake..
i thing i have to pass somthing to html() , but i am not sure..
while($row=mysql_fetch_array($result)){ $student_name = $row['name']; }
should be
$student_name = NULL;
while($row=mysql_fetch_array($result)){ $student_name .= $row['name']; }

Categories