ajax / jquery not passing 2nd click values [duplicate] - javascript

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>";

Related

During click of load more button, some divs become unclickable

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.

give a value to input when move then save it by ajax - php / jquery -php

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;
}

Delete PHP (mysqli) row - with HTML/Javascript button

Using google maps, I have events saving to a database using mysqli. These events are then displayed as markers on the map and when clicked the relevant data is displayed in an info box (Name, date, etc). I want the option to delete an event event by deleting a row from the DB when the Remove (remove-event) button is clicked. The button is contained in the data displayed with the javascript:
var eventContent = $('<div class="event-info">' + '<h4 class="event-name">' + point.name + '</h4><hr>' +
'<span><h5>Date: </h5>' +
'<p class="event-date">' + point.edate + '</p></span>' +
'<p class="event-description">'+point.description+'</p>' +
'</span><button id="remove-event" name="remove-event" class="remove-event btn btn-danger btn-sm" onclick="tidy_maps.delete()" title="Remove Event">Remove Event</button>'+
'</div>');
// Display Event details on marker click
google.maps.event.addListener(event_markers[i], "click", function () {
infowindow.setContent(eventContent[0]);
infowindow.open(map, event_markers[i]);
The script that sends it to the php (removedata.php):
tidy_maps.delete = function() {
$.ajax({
type:'POST',
url:'removedata.php',
success:function(data) {
if(data) {
alert("Are you sure?");
}
else {
alert("ERROR!!!!");
}
}
});
}
The removedata.php is:
$con = mysqli_connect("localhost", "root", "password", "gmaps1");
if (!$con) {
die("Can not connect: " .mysql_error());
}
$sql = "DELETE FROM events WHERE id = 'id' ";
$query = mysqli_query($con, $sql);
if(mysqli_affected_rows($con)) {
echo "Record deleted successfully";
}
mysqli_close($con);
As it is, it does not delete the row in the DB, but when i change the line:
$sql = "DELETE FROM events WHERE id = 'id' ";
to a specific ID No. Example:
$sql = "DELETE FROM events WHERE id = '5' ";
And i run the removedata.php in the browser, it deletes the row with ID=5 from the DB. There seems to be no errors when the console when clicking the remove button so it must be sending to PHP script ok.
I would like when the Remove button is clicked that it asks are you sure and then it deletes that specific Row form the DB.
As far as I can tell you don't pass the ID of the row to be deleted.
You can send data two ways, either as a url parameter, or post it using the
data tag:
$.ajax({
type:'POST',
url:'removedata.php',
data: {id : 5}
});
Access the ID in removedata.php:
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;
WHERE id = 'id' you need to remove the '' and add the $ symbol if you want id to be a variable.
Ok I've played around a little and amended the JS slightly:
tidy_maps.delete = function() {
var confirm_remove = confirm("Do You Want to Remove This Event?")
if(confirm_remove) {
$.ajax({
type:'POST',
url:'removedata.php',
});
window.location = "http://www.google.com/";
}
else {
alert("ERROR!!!!");
}
}
So when Confirm is YES, i threw in a redirect to Google just to see what happens. When YES is clicked in the confirm box, it redirects the page to Google but does not delete the row from the DB
Try this
var id = 5;
var request = $.ajax({
url:'removedata.php',
type: "POST",
data: "id="+id,
success: function(data){
console.log(data);
}
});
get post value in removedata.php
//get post value
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;

Code returns the latest value before last refresh instead of the latest value inserted?

I have a column of buttons in a table, declared like this:
(file index.php)
echo '';
Then this script reads the data in the row of the button clicked and posts it to another php file:
<!-- scripts that gets the lecturer chosen to SHOW functionality-->
<script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
$.ajax({ type: "POST", url: "show_lecturer.php", data: { x: names, y: surname} })
});
});
</script>
That file (show_lecturer.php) stores the data read in a table (keep_track) in the database:
(file show_lecturer.php)
<?php
ob_start(); //eliminates buffer collisions
require_once('connect_db.php');
$name = $_POST['x'];
$surname = $_POST['y'];
$result = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");
?>
Then I create an empty dialogbox with jquery, to populate it with the data taken from the database:
(file index.php)
<!-- The following script generates the empty dialog box -->
<script src="/js/jquery.min.js"></script>
<link rel="stylesheet" href="/css/jquery-ui.css">
<script src="/js/jquery-ui.min.js"></script>
<script>
$(function() {
//show lecturer dialog
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
</script>
Then these data are taken from the table keep_track and echoed in the above dialog:
(file index.php)
$name; $surname;
require_once('connect_db.php');
$firstname = pg_query(connect(), "SELECT name FROM keep_track");
while($row = pg_fetch_array($firstname)){ $name = $row['path']." ".$row['name']; }
$lastname = pg_query(connect(), "SELECT surname FROM keep_track");
while($row = pg_fetch_array($lastname)){ $surname = $row['path']." ".$row['name']; }
echo '<div id="show_dialog" class="ui-dialog-content ui-widget-content">';
echo $name."".$surname;
echo '</div>';
?>
So when I click the button of row x, a dialogbox opens with the data from the row x.
The only thing that is not working correctly is this:
The moment I click button x, it opens a dialog but displays a value, but not that of row x. However, when i see the database, the row x is stored there. The value in the checkbox is that of the button clicked before the latest refresh on the page. Its as if there is some mistake in my chain of calls or something (that I cant figure out, thats why Im asking).
To illustrate the data I get:
(Initially the table keep_track is empty)
Press button 1 -> row 1 stored, dialogbox has no content
Press button 2 -> row 2 stored, dialogbox has no content
Press button 3 -> row 3 stored, dialogbox has no content
Refresh page manually
Press button 4 -> row 4 stored, dialogbox has content from row 3
Press button 5 -> row 5 stored, dialogbox has content from row 3
Refresh page manually
Press button 6 -> row 6 stored, dialogbox has content from row 6
Press button 7 -> row 7 stored, dialogbox has content from row 3
I suggest you return your data from the POST via JSON. And please be aware that an AJAX Call is asynchronous. So you won't know when the reply is coming.
So you need to process your results using the ajax Success callback function.
</script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
do_post_and_show_info(names, surname);
});
});
function do_post_and_show_info(names, surname){
request= $.ajax({
type: "post",
cache: false,
url: "show_lecturer.php",
data: { x: names, y: surname} ,
dataType: "json",
});
request.done(function(json){
if (json.status =="ok"){
// DO YOUR THING!
Alert(json.data.names + " " + json.data.surnames);
}
else {
alert("Error! " + json.error + " : " + json.remarks);
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus + ":" + jqXHR.responseJSON);
});
}//do_post_and_show_info
</script>
I usually return a datastructure like this in PHP (so in your show_lecturer.php)
<?
// get your data before this in the variable $data
// put your status "OK" or "ERROR" in $status
// put some error info in $extraInfo
// of course some processing is involved, but here's a simple example
require_once('connect_db.php');
$name = $_POST['x'];
$surname = $_POST['y'];
$result = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");
// obviously you need to do some error checking, but here's the happy flow
$status = "OK";
$error = "";
$data['names'] = $name;
$data['surnames'] = $surname;
echo json_encode(array(
"status" => $status,
"error" => $error,
"remark" => $extraInfo,
"data" => $data
));
?>
Please be aware this is an example that I have created here in the editor and not in a real working setup. SO please try to understand it instead of copy-pasting it and giving it a run.
I wrote the content of the dialog (div) in another file and used
$("#div").load("content.php", {x:parameter_1, y:parameter_2, ......});
instead of
$.ajax({ type: "POST", url: "show_lecturer.php", data: { x: names, y: surname} })
This did the trick.
Now the div is initially invisible and empty, but once the button is clicked, it requests the content.php page to load. Since I'm passing the search parameters when I request the content, I get the data that I wanted.
The problem from before was that when the page loaded, the div was created with the data (even though I hadn't clicked any button). Therefore, when I 'd click a button, it would show me the div with the content from the last page load (last refresh).
There were also other minor changes I had to do to make it work, but this is the main idea.

Dynamically Loading Content [duplicate]

This question already has answers here:
How to select the nth row in a SQL database table?
(33 answers)
Closed 9 years ago.
I am trying to load content as the user scrolls from my database. I am trying to load 10 items at a time in order. currently I have achieved everything I want to do except I am loading the first 10 items every time. I don't really know how to keep track of what items were loaded last. If I made a variable it would reset anyways everytime the script is called.
What do I need to change in order for it to load the next 10 items instead of the first 10?
php:
<?php
// database connection info
$conn = mysql_connect('localhost','root','') or trigger_error("SQL", E_USER_ERROR);
$db = mysql_select_db('test',$conn) or trigger_error("SQL", E_USER_ERROR);
//offset
$offset=0;
// number of rows to show per page
$rowsperpage = 10;
// get the info from the db
$sql = "SELECT ID, confession, image FROM test LIMIT $offset, $rowsperpage";
$result = mysql_query($sql, $conn) or trigger_error("SQL", E_USER_ERROR);
// while there are rows to be fetched...
while ($list = mysql_fetch_assoc($result)) {
echo '<table border="0" width="600px">';
echo "<tr>";
echo "<td><p>" . '<img src="' . $list['image'] . '" hspace="10" border="1" style="float:left;">' . "</p>";
echo "<p>" . "#" . $list['ID'] . ": " . $list['confession'] . "</p></td>";
echo "</tr>";
echo "</table>";
echo "<br>";
//next ten rows
$offset+=10;
}
?>
javascript:
//load content as page scrolls
function yHandler() {
var content = document.getElementById('content');
var contentHeight = content.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if (y >= contentHeight) {
// Ajax call to get more dynamic data goes here
content.innerHTML += '<div class="newData"></div>';
document.onload = $.post('test5.php', function (data) {
$('.newData').html(data);
});
}
}
window.onscroll = yHandler;
You need to set some counter to this, for example:
<input type="hidden" value ='counter_value'>
And when you send request, you have to send it with counter value, and in php file dependce on counter value select next 10 items from db. After thet using java script increase counter value by ++. And when you will send again request the value will be +1, and in php make logic to select next items
For example, when you reached the bottom of the page, you want to download next items.
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
///here you have to send ajax to php file to get items
var counter= $('#idOfInputwithCouner').attr('value');
$.ajax({
url: 'youPhpFile.php',
data: "counter=" + counter,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('data'); //here you will get data from php file
$('#idOfInputwithCouner').attr('value',counter +1); //increase input value
}
})
}
});
you may use pagination logic here, send pageNumber with each call and retrieve data accordingly,

Categories

Resources