I have problems creating report system. Plan is this: User has 4 radios to select and then submits one of them. First submission inserts only one row in mysql but every after that submission inserts more and more rows. Here is the code:
profile.php
<form id="myform">
bully<input type="radio" id='radio<?php echo $outid; ?>' name="nein" class='radspam' value="bulinput"> </input><br>
spam<input type="radio" id='radio<?php echo $outid; ?>' name="nein" class='radspam' value="spaminput"> </input><br>
viol<input type="radio" id='radio<?php echo $outid; ?>' name="nein" class='radspam' value="vioinput"> </input><br>
pron<input type="radio" id='radio<?php echo $outid; ?>' name="nein" class='radspam' value="pcont_input"> </input>
</form>
///jquery code
$(".report").click(function(){
var parent=$(this).parent().attr("id");
var split=parent.split("output");
var id=split[1];
loading();
closeloading(); // fadeout loading
$(".torep").fadeIn("fast"); // fadein popup div
$("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8
$("#backgroundPopup").fadeIn("fast");
$("input:radio[name=nein]").click(function() {
$(".repyes").removeAttr("disabled");
});
$(".repyes").click(function(){
var username="<?php echo $username; ?>";
var valara = $('input:radio[name=nein]:checked').val();
$.ajax({
url:"s/report.php",
data:"username=" + username + "&what=" + valara + "&whatid=" + id,
type:"POST",
success:function(data){
alert(data);
$(this).prop('checked', false);
}
});
});
});
report.php
<?php
include "db.php";
IF (isset($_POST['whatid'])){
$what=$_POST['what'];
$reported=$_POST['username'];
$whatid=$_POST['whatid'];
$sql=mysql_query("INSERT INTO report(reported,what,whatid,date) VALUES ('$reported','$what','$whatid',now())");
if (mysql_affected_rows() == 1){
echo "udje";
}else{
echo mysql_error();
}
}
?>
Move id to global scope. And assign click event to .repyes outside of $(".report").click():
var _id = null;
$(".report").click(function(){
var parent=$(this).parent().attr("id");
var split=parent.split("output");
_id = split[1];
loading();
closeloading(); // fadeout loading
$(".torep").fadeIn("fast"); // fadein popup div
$("#backgroundPopup").css("opacity", "0.7"); // css opacity, supports IE7, IE8
$("#backgroundPopup").fadeIn("fast");
$(".report").click(function() {
$("input:radio[name=nein]").click(function() {
$(".repyes").removeAttr("disabled");
});
});
});
$(".repyes").click(function(){
var username="<?php echo $username; ?>";
var valara = $('input:radio[name=nein]:checked').val();
$.ajax({
url:"s/report.php",
data:"username=" + username + "&what=" + valara + "&whatid=" + _id,
type:"POST",
success:function(data){
alert(data);
$(this).prop('checked', false);
}
});
});
It most likley is because you have an event handler binding inside an event handler. So everytime you click report a new click event is bound to .repeyes
$(".report").click(function(){
...
$(".repyes").click(function(){
Just move the second binding outside of the first one.
UPDATE
Oh, the id issue should be fixed like in Arthur Halma'S answer by moving it to global scope.
Related
I have undercome a problem when implementing a "Show more button"
The page will initially display 5 rows of data, then on click the button will make a call to a php function through ajax and load more results, ultimately displaying them on the page. It does this very well.
The problem is that each of the divs are clickable in their own right to allow for user interaction. Before clicking the button the first 5 are clickable and work correctly, however after loading the first 10, the first 5 become unclickable and the rest work as expected.
See my code here:
HTML:
<div class="col-sm-12 col-xs-12 text-center pushDown">
<div id="initDisplay">
<?php
// Display all subjects
echo displaySubjects($limit);
?>
</div>
<div id="show_result"></div>
<button id="show_more" class="text-center pushDown btn btn-success">Show More</button>
</div>
On click of the button the following is happening:
JQuery:
<script>
$("#show_more").on("click", function() {
$("#initDisplay").fadeOut();
});
/* This bit is irrelevant for this question
$("#addBtn").on("click", function(){
addSubject();
});
*/
var stag = 5;
$("#show_more").on("click", function(){
stag+=5;
console.log(stag);
$.ajax({
dataType: "HTML",
type: "GET",
url: "../ajax/admin/loadSubjects.php?show="+stag,
success: function(result){
$("#show_result").html(result);
$("#show_result").slideDown();
}
});
var totalUsers = "<?php echo $total; ?>";
if(stag > totalUsers) {
$("#show_more").fadeOut();
}
});
</script>
My PHP page and functions are here:
<?php
include_once '../../functions/linkAll.inc.php';
$limit = filter_input(INPUT_GET, "show");
if (isset($limit)) {
echo displayUsers($limit);
} else {
header("Location: ../../dashboard");
}
function displaySubjects($limit) {
$connect = db();
$stmt = $connect->prepare("SELECT * FROM Courses LIMIT $limit");
$result = "";
if ($stmt->execute()) {
$results = $stmt->get_result();
while($row = $results->fetch_assoc()){
$id = $row['ID'];
$name = $row['Name'];
$image = $row['image'];
if($image === ""){
$image = "subjectPlaceholder.png"; // fail safe for older accounts with no images
}
$result .=
"
<div class='img-container' id='editSubject-$id'>
<img class='miniProfileImage' src='../images/subjects/$image'>
<div class='middle' id='editSubject-$id'><p class='middleText'>$name</p></div>
</div>
";
$result .= "<script>editSubjectRequest($id)</script>";
}
}
$stmt->close();
return $result;
}
The script being called through this is:
function editSubjectRequest(id) {
$("#editSubject-"+id).click(function(e) {
e.preventDefault(); // Prevent HREF
console.log("You clicked on " + id);
$("#spinner").show(); // Show spinner
$(".dashContent").html(""); // Empty content container
setTimeout(function() {
$.ajax({ // Perform Ajax function
url: "../ajax/admin/editSubjects.php?subjectID="+id,
dataType: "HTML",
type: "POST",
success: function (result) {
$("#spinner").hide();
$(".dashContent").html(result);
}
});
}, 1500); // Delay this for 1.5secs
});
}
This will then take the user to a specific page depending on the subject which they clicked on.
Your problem is duplicate ids. First five items are present on the page always. But when you load more, you are loading not new items, but all, including first five. As they are already present on the page, their duplicates are not clickable. The original items are however clickable, but they are hidden.
Here is what you need:
$("#show_more").on("click", function(){
$("#initDisplay").html("");
});
Don't just fadeOut make sure to actually delete that content.
This is the easiest way to solve your issue with minimum changes. But better option would be to rewrite your php, so it would load only new items (using WHERE id > $idOfLastItem condition).
Also you don't need that script to be attached to every div. Use common handler for all divs at once.
$("body").on("click", "div.img-container", function() {
var id = $(this).attr("id").split("-")[1];
});
When you are updating a DOM dynamically you need to bind the click event on dynamically added elements. To achieve this change your script from
$("#editSubject-"+id).click(function(e) {
To
$(document).on("click","#editSubject-"+id,function(e) {
This will bind click event on each and every div including dynamically added div.
I have buttons that add and remove products from the Magento cart, but that's not so relevant in that issue. What I want to do is change the logic of what they are doing. Currently, when the buy button is clicked, the product is added to the cart, the button is "changed" to remove it and all other buttons are disabled for the click. When the remove button is clicked, the product that was added is removed and all other buttons can be clicked again.
I want to change the logic to the following: when the buy button is clicked, the product is added to the cart and the buy button is "changed" to remove (so far everything is the same as it was). But, all buttons remain click-enabled and if any other buy button is clicked, the product that was added is removed and the new product is added.
I've researched and thought in many ways, but I can not find a way to do that.
Button code:
<button type="button" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Add to Cart')) ?>" class="button btn-cart" onclick="addCartao('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>" id="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span><?php echo $this->__('Add to Cart') ?></span></span></button>
<button style="display: none;" type="button" id="cartaoMensagemRemover<?php echo $_product->getId(); ?>" title="Remover" class="button btn-cart" onclick="removeCartaotoCart('<?php echo $_product->getId(); ?>')" name="cartaoMensagem<?php echo $_product->getId(); ?>"><span><span>Remover</span></span></button>
Ajax requisition code:
function addCartao(product_id){
$j('#cartaoMensagem'+product_id).hide();
$j('#cartaoMensagemRemover'+product_id).show();
$j('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000'});
$j.ajax({
type: "POST",
url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>",
data: {
product_id: product_id
},
dataType: 'json',
cache : false,
beforeSend: function () {
},
success: function (retorno) {
var button = $j('#cartaoMensagemRemover'+product_id);
$j('#cartao').find(':button').not(button).attr('disabled',true);
$j('.item-custom').append('<tr id="trAppend"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>');
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
window.location.reload();
history.go(0);
window.location.href=window.location.href;
}
});
}
function removeCartaotoCart(itemId){
$j('#cartaoMensagemRemover'+itemId).hide();
$j('#cartaoMensagem'+itemId).show();
$j.ajax({
type:"POST",
url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>",
data:{
itemId: itemId
},
cache: false,
beforeSend: function(){
},
success: function(retorno){
var button = $j('#cartaoMensagemRemover'+itemId);
$j('#cartao').find(':button').attr('disabled',false);
$j('.item-custom #trAppend').remove();
getSubTotal();
getGrandTotal();
},
complete: function () {
},
error: function (x,y,z) {
alert("error");
alert(x);
alert(y);
alert(z);
window.location.reload();
history.go(0);
window.location.href=window.location.href;
}
});
}
I "simplified" your code a lot... Since I can't make an example with your PHP.
So the "reproduced" behavior is in this CodePen.
Now what you need to do, is to keep the added product ID in "memory" in a variable.
On add... If there already is a product ID, call the remove function, then add the other product.
It should be as simple as this.
So here is another CodePen with th modifications to make.
var productSelected = ""; // The variable used as a "memory".
function addCartao(product_id){
if( productSelected != "" ){
removeCartaotoCart(productSelected); // Remove the item in cart, if there is one.
}
console.log("Add "+product_id);
productSelected = product_id; // Keep the product id in "memory".
$('#cartaoMensagem'+product_id).hide();
$('#cartaoMensagemRemover'+product_id).show();
$('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000','color':'white'});
//Ajax...
// In the success callback:
var button = $('#cartaoMensagemRemover'+product_id);
//$('#cartao').find(':button').not(button).attr('disabled',true); // Do not disable the other buttons.
}
function removeCartaotoCart(itemId){
console.log("Remove "+itemId);
productSelected = ""; // Remove the product id from "memory"
$('#cartaoMensagemRemover'+itemId).hide();
$('#cartaoMensagem'+itemId).show();
//Ajax...
// In the success callback:
var button = $('#cartaoMensagemRemover'+itemId);
//$('#cartao').find(':button').attr('disabled',false); // The other buttons aren't disabled... This line is useless.
}
This question already has an answer here:
Function doesn't work after appending new element
(1 answer)
Closed 5 years ago.
Extremely new to JavaScript, jquery and ajax and am having difficulties with a very basic set of scripts to load more data from a database on button clicks.
The first time I click load more, it works. But the 2nd clicks do not pass the values and does nothing.
Here is the main script that loads data once and includes the jquery, ajax stuff.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn1, #btn2").click(function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
$("#btn1").hide();
$("#div1").append(response);
}
}
});
});
});
</script>
</head>
<?php
// main.php contains db connection
include('main.php');
$rowsperpage = 2;
$q = "SELECT col1, col2 from mytableORDER BY col1 LIMIT $rowsperpage OFFSET 0";
$r = pg_exec($dbconnect, $q);
echo "<div id='div1' style='margin:10px;'>";
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
echo "<button id='btn1' value=2>Load More</button>";
echo "</div>";
?>
And here is the script fetched more data to display.
<?php
include('../config.php');
include('functions.php');
$rowsperpage = 2;
if(isset($_POST['page'])) {
$paged=$_POST['page'];
} else {
$paged = 1;
}
if($paged > 1) {
$rowoffset = $rowsperpage * ($paged -1);
$limit = " LIMIT $rowsperpage OFFSET $rowoffset";
} else {
$limit = " LIMIT $rowsperpage OFFSET 0 ";
}
$q = "select subindustryid, subindustry from sub_industries ORDER BY subindustry $limit";
$r = pg_exec($dbconnect, $q);
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";
?>
The problem is the the 2nd button is displayed and nothing happens when it gets clicked.
Thank for your time!
The problem is the event binding. Change this line-
$("#btn1, #btn2").click(function() {
to this line
$("#div1").on("click","#btn1, #btn2",function(){
Also your php returns a button with id btn1 and not btn2
Read about jQuery Event bindings here: https://learn.jquery.com/events/handling-events/ and http://learn.jquery.com/events/event-delegation/
Actually id identifiers should be unique- this is general convention. You have load more button with id="#btn1" and hiding old button appearing new button from the response text form ajax by hiding and appending- but you can manage such with out sending button in response text-
Have following changes on your html page
value should be quoted <button id="btn1" value="2">Load More ... </button>
Make use of dedicated function calling in jQuery like- $(document).on('event','dom_identifiers',callbackfunction(){})
In ajax don't need to hide current button which is clicked, instead of hiding the button just add new records fetched before the load more button by using before() function of jQuery
For next page you can increase the value of current button
$(document).ready(function(){
// dedicated function calling
$(document).on('click','#btn1',function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
// increase the value load more
$("#btn1").val(parseInt($("#btn1").val())+1);
// add response data just before the loadmore button
$("#btn1").before(response);
}
}
});
});
});
button should be like
echo "<button id='btn1' value="2">Load More</button>";
Now in fetching php page please remove these two lines-
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";
I want to create a shopping cart and i'm almost finish. I use ajax for dynamic search and ajax for add to cart and use jquery for refresh a specific div when click but i face a problem.My problem is Quantity problem. I use session for store value
//this is my session update code
$con = mysqli_connect("localhost", "root" , "","atest");
session_start();
require("functions.php");
cart_session();
$id=$_POST['id'];
//echo $arr['cart'];
if(isset($_SESSION[$arr["cart"]][$id])){
$_SESSION[$arr["cart"]][$id][$arr["quantity"]]++;
//redirect("http://localhost/my/work/sellingcart/index.php",true);
}else{
$sql_s="SELECT * FROM product_1
WHERE p_id={$id}";
//echo $sql_s;
$query_s=mysqli_query($con,$sql_s);
if(mysqli_num_rows($query_s)!=0){
$row_s=mysqli_fetch_array($query_s);
$_SESSION[$arr['cart']][$row_s["p_id"]]=array(
"{$arr["quantity"]}" => 1
);
//redirect("http://localhost/my/work/sellingcart/index.php",true);
}else{
$message="This product id it's invalid!";
}
}
//use ajax for update cart
<script>
$("#link").click(function(e) {
e.preventDefault();
var id = $("#id").val();
var dataString = 'id='+id;
$('#loading-image').show();
$(".form :input").attr("disabled", true);
$('#remove_cart').hide();
$('#link').hide();
$(".container").css({"opacity":".3"});
$(".form :input").attr("disabled", true);
$('#remove_cart').hide();
$('#link').hide();
$.ajax({
type:'POST',
data:dataString,
url:'add_cart.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
$('#loading-image').hide();
$(".form :input").attr("disabled", false);
$('#remove_cart').show();
$('#link').show();
$(".container").css({"opacity":"1"});
}
});
//$("#chat").load(location.href + " #chat");
//$("#chat").load(location.href+" #chat>*","");
});
</script>
Here is image and Red mark is my problem.
i want to update my cart when i give value and move it then it update my session by ajax and php.
Is there any help? I don't want to user can update there quantity every cart item singly. i want it dynamic just give quantity number and move then it save by ajax.
Assign an onchange event to your quantity input boxes:
$('input[name=quantityBox]').change(function() { ... });
In your function() above, add an AJAX POST request containing something like
var quantity = $('input[name=quantityBox]').val();
// var id = something;
$.ajax({
type:'POST',
data:"productId=" + id + "&updateQuantity=" + quantity,
url:'add_cart.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
// anything you want to do on successful update of request
}
});
In your PHP function above, you check whether the product already exists in user's cart. At that point, change the quantity.
if(isset($_SESSION[$arr["cart"]][$id])){
$quantity = $_POST['updateQuantity'];
$id = $_POST['productId'];
$_SESSION[$arr["cart"]][$id][$arr["quantity"]] = $quantity;
}
Special Thanks To Nvj
Assign an onchange event to your quantity input boxes:
<input id="qty<?php echo $row['p_id'] ?>" value="" onchange="save_quantity(<?php echo $row['p_id'] ?>)">
function with ajax :
function save_quantity(x){
var quantity=$("#qty"+x).val();
$.ajax({
type:'POST',
data:"updateQuantity=" + quantity+ "&id="+x,
url:'update_qty.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
// anything you want to do on successful update of request
}
});
}
php file update_qty.php
session_start();
$qty = $_POST["updateQuantity"];
$p_id = $_POST["id"];
foreach($_SESSION['cart'] as $id => $value) {
if($id==$p_id)
echo $id;
$_SESSION['cart'][$id]['quantity']=$qty;
}
I made a small script to record bugs in my projects
this picture will show you a file name and the bugs it have.
then I used javascript-jquery to save myself some time.
so when I click on an error (the red ones) it will turn to green, and if i click on the fixed error (the green ones) it will turn to red.
the problem is sometime I click on the wrong error and can't turn it back unless i refresh the page. ex. if I click on error like tags plugin (* it turns green *) then I click on tags plugin again to turn it back to red it won't turn back, unless I refresh the page then click on it again to turn it.
I checked my code its fine I don't know what the problem is.
in while (fetching the error)
while ($error = mysql_fetch_assoc($find_errors))
here I print the errors
<?php
switch ($error['status']) {
case 'notfixed':
$error_class = "error";
$error_link = "fix".$error['id']."";
break;
case 'fixed':
$error_class = "success";
$error_link = "unfix".$error['id']."";
break;
}
echo "
<a href='".$_SERVER['PHP_SELF']."?del=".$error['id']."'>
<span class='del'>×</span>
</a>
<input id='errorid".$error['id']."' value='".$error['id']."' type='hidden'>
<input id='errorname".$error['id']."' value='".$error['name']."' type='hidden'>
<div id='newdiv".$error['id']."'>
<a id='".$error_link."'>
<span class='".$error_class."'>".$error['name']."</span>
</a>
</div>
<div class='clear'></div>";
?>
inside the same loop before printing the errors I printed this which the javascript
<script type='text/javascript'>
$('document').ready(function(){
$("#fix<?php echo $error['id'] ?>").click(function(){
var errorid = $("#errorid<?php echo $error['id']?>").val();
jQuery.post('fix_error.php',{posterrorid : errorid},
function(data, textStatus){
if(data == 1){
setInterval(function(){
$("#newdiv<?php echo $error['id']?>").html("<a id='unfix<?php echo $error['id']?>'><span class='success'><?php echo $error['name']?></span></a>");
}, 1000);
}else{
setInterval(function(){
$("#newdiv<?php echo $error['id']?>").text('error insert');
}, 1000);
}
});
});
$("#unfix<?php echo $error['id'] ?>").click(function(){
var errorid = $("#errorid<?php echo $error['id']?>").val();
jQuery.post('unfix_error.php',{posterrorid : errorid},
function(data, textStatus){
if(data == 1){
setInterval(function(){
$("#newdiv<?php echo $error['id']?>").html("<a id='fix<?php echo $error['id']?>'><span class='error'><?php echo $error['name']?></span></a>");
}, 1000);
}else{
setInterval(function(){
$("#newdiv<?php echo $error['id']?>").text('error insert');
}, 1000);
}
});
});
});
</script>
Try using the syntax like this :
$("#fix<?php echo $error['id'] ?>").live('click',function(){
.....
});
$("#unfix<?php echo $error['id'] ?>").live('click',function(){
.....
});
Because when you click for the first time, you are replacing the html code dynamically,
so for the next time, when you click that dynamically generated html code will not be noticed, so you have to use .live function.
REFER