I want to make a 'show more' button with jQuery AJAX. I have a button with a loaded attribute like so:
<button type="button" class="smbt btn center-block" data-loaded="3">Show More</button>
In the javascript file I wrote this:
var smbt = $(".smbt");
smbt.click(function() {
var limit = $(smbt).attr('loaded');
// alert(loaded + " picture");
$.ajax({
url: '../view/profile.php',
type: 'POST',
data: ({limit1: limit}),
success: function(result) {
console.log("success");
},
error: function() {
alert("error");
}
});
Then I try to get the limit1 variable:
$limit = $_POST["limit1"];
I read the $.ajax documentation and a lot of questions and answers, I tried a lot of way to make it work but it always gives this error:
Undefined index: limit1
Try this:
var smbt = $(".smbt");
smbt.click(function() {
var limit = $(smbt).data('loaded');
$.ajax({
url: './view/profile.php',
type: 'POST',
data: {limit1: limit},
success: function(result) {
console.log("success");
},
error: function() {
alert("error");
}
});
});
You are using data-* attribute, so to get the value, you use $.data() function: https://api.jquery.com/jquery.data/
If once someone also had this problem this is how I made it work.
So there is a profile.php which contains and shows the uploaded pictures. I want want to use a button which increase the LIMIT in sql. So the profile.php contains everything. There is a div which contains the pictures wit query result and after it have the load more button. It's looks like this:
<div class="row mg-bt-20" id="cont">
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " <div class='col-md-4 col-sm-6 mg-bt-20'>
<div class='pics' data-toggle='modal' data-id='".$row['id']."' data-target='#myModal'>
<img src='" . $row['path'] . "'>
<p class='text-center' style='line-height: 6vh;'>". $row["description"] ."</p>
</div>
</div>";
}
} else {
echo "<p style='text-align: center; color:#fff; font-size: 20px;'>No posts yet.</p>";
}
?>
</div>
The problem was I try to send the variable to this profile.php but it's not work at all. I tried everything but it's just not working. So I made a new php file called show_more.php which contains only the php query results from the code above:
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " <div class='col-md-4 col-sm-6 mg-bt-20'>
<div class='pics' data-toggle='modal' data-id='".$row['id']."' data-target='#myModal'>
<img src='" . $row['path'] . "'>
<p class='text-center' style='line-height: 6vh;'>". $row["description"] ."</p>
</div>
</div>";
}
} else {
echo "<p style='text-align: center; color:#fff; font-size: 20px;'>No posts yet.</p>";
}
?>
So my jQuery code is:
var smbt = $(".smbt");
var limit = $(smbt).data('loaded');
smbt.on('click',function(event) {
event.preventDefault();
limit += 3;
console.log(limit);
// alert(loaded + " picture");
$.ajax({
url:"../php/show_more.php",
data: {limit1: limit},
success:function(data){
$("#cont").html(data);
}
});
This is successfully send the limit1 variable to the show_more.php.
In the show_more.php I just write $_POST["limit1"] to get the data.
And the sql query looks like this:
$sql = "SELECT * FROM images where user = '$username' ORDER BY id DESC LIMIT $limit";
So here is how it's work:
First of all when the profile.php is loaded the pictures are shows if you have one but its limited to shown only 3 at first. So after you click the load more button it runs the ajax code which increase the limit variable with 3 so we get a new number which is 6 now (I always increase with 3). The ajax code first send the data to the given url which is the show_more.php in this case. I write it in oop so I have a class which handle all the image thing and I have a function in it which show the images so i just pass a variable in it like this public function showImg($limit){...}. So here is where the magic happens. It's always change the limit number once I clicked. after when it's happened in ajax code the success part handle the result. The result will the html code which will be added to the image container.
I hope I help with this and I didn't write stupid things(also sorry for my english). It works for me in this form.
And thanks for everybody whose help.
Related
My HTML as follows, located in index.php
<div id="showDetails">
</div>
<div id="showList">
</div>
And my Ajax as follows, still in index.php
function funcReadRecord() {
var readrecord1 = "readrecord1";
var sometext = $('#SNOW_INC').val();
$.ajax({
url : "findsql.php",
type : 'post' ,
data : { readrecord1 : readrecord1,
sometext : sometext } ,
success : function(data, status){
$('#showList').html(data);
}
});
}
Now, I can return my list and view the required list (shown as a list group) in index.php.
I have a button in index.php that when clicked, runs the function.
<div>
<button type="button" onclick="funcReadRecord()" class="btn btn-primary">Search SQL (LIKE)</button>
</div>
The code in findsql.php as follows
if(isset($_POST['readrecord1']) && isset($_POST['sometext'])){
$displaysql = "SELECT * from datadump where short_description LIKE '%".$_POST['sometext']."%'";
$result = mysqli_query($conn, $displaysql);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
$items[] = array(
"number" => $row['number'],
"priority" => $row['priority'],
"description" => $row['short_description']);
}
}
echo '<p class="lead">SEARCH SQL (LIKE)<p>';
echo '<div class="list-group">';
foreach($items as $result) {
?>
<a href="#" class="list-group-item list-group-item-action">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1"><?php echo $result['number']; ?></h5>
<small></small>
</div>
<p class="mb-1"><?php echo $result['description']; ?></p>
<small><?php echo $result['priority']; ?></small>
</a>
<?php
}
echo '</div>';
}
All I'm doing is getting the data from MySQL and assigning them to array and listing them. I know I could do it directly but I need the array in some other function.
The question is how do I make details from the array to show in showDetails div tag when I click the list? Right now, the HREF is #. I could assign a function, but not sure where to write them.
If I should write a function to return them, should I write in index.php or findsql.php?
Thanks in advance.
I understand that you need individual record information in #showDetails div right ! then
step1: assign new function while clicking the particular item as onclick="funcReadRecord(number)", this should at findsql.php file.
step2: write an ajax function in index.php which will send that particular unique id or in your case number
function funcReadRecord(number) {
$.ajax({
url : "findsql.php",
type : 'post' ,
data : { id: number } ,
success : function(data, status){
$('#showDetails').html(data);
}
});
Step3: Write another function in findsql.php with else if block as checking id isset or not, change the query that takes the number or any key that gets only that particular record.
else if(isset($_POST['id'])){
$displaysql = "SELECT * from datadump where number = ".$_POST['id'].";
// remaining design code below
}
We can use the if-else statement to write multiple ajax calls as above.
Edited, Note: kindly ignore the syntax issue in the above code, concentrate on the process used to a single PHP file for multiple ajax calls using branching statements.
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.
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'm trying to create a comment system on my website where the user can comment & see it appear on the page without reloading the page, kind of like how you post a comment on facebook and see it appear right away. I'm having trouble with this however as my implementation shows the comment the user inputs, but then erases the previous comments that were already on the page (as any comments section, I'd want the user to comment and simply add on to the previous comments). Also, when the user comments, the page reloads, and displays the comment in the text box, rather than below the text box where the comments are supposed to be displayed. I've attached the code. Index.php runs the ajax script to perform the asynchronous commenting, and uses the form to get the user input which is dealt with in insert.php. It also prints out the comments stored in a database.
index.php
<script>
$(function() {
$('#submitButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "insert.php",
data : { field1_name : $('#userInput').val() },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
//this will add the new comment to the `comment_part` div
$("#comment_part").append(html);
}
});
});
});
</script>
<form id="comment_form" action="insert.php" method="GET">
Comments:
<input type="text" class="text_cmt" name="field1_name" id="userInput"/>
<input type="submit" name="submit" value="submit" id = "submitButton"/>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
</form>
<div id='comment_part'>
<?php
$link = mysqli_connect('localhost', 'x', '', 'comment_schema');
$query="SELECT COMMENTS FROM csAirComment";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="comment" >';
$output= $row["COMMENTS"];
//protects against cross site scripting
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8');
echo '</div>';
}
?>
</div>
insert.php
$userInput= $_GET["field1_name"];
if(!empty($userInput)) {
$field1_name = mysqli_real_escape_string($link, $userInput);
$field1_name_array = explode(" ",$field1_name);
foreach($field1_name_array as $element){
$query = "SELECT replaceWord FROM changeWord WHERE badWord = '" . $element . "' ";
$query_link = mysqli_query($link,$query);
if(mysqli_num_rows($query_link)>0){
$row = mysqli_fetch_assoc($query_link);
$goodWord = $row['replaceWord'];
$element= $goodWord;
}
$newComment = $newComment." ".$element;
}
//Escape user inputs for security
$sql = "INSERT INTO csAirComment (COMMENTS) VALUES ('$newComment')";
$result = mysqli_query($link, $sql);
//attempt insert query execution
mysqli_close($link);
//here you need to build your new comment html and return it
return "<div class='comment'>...the new comment html...</div>";
}
else{
die('comment is not set or not containing valid value');
}
The insert.php takes in the user input and then inserts it into the database (by first filtering and checking for bad words). Just not sure where I'm going wrong, been stuck on it for a while. Any help would be appreciated.
html() in your function replacing current html with your comment html, thats why u see only new comment. Change your method to append().
$("#comment_part").append(html);
Change this line
$("#comment_part").html(html);
to this
$("#comment_part").html('<div class="comment" >' + $('#userInput').val() + '</div>' + $("#comment_part").html()).promise().done(function(){$('#userInput').val('')});
I am trying to call a PHP script in my main PHP file.Below is the Jquery/Ajax part of the main php file. The display_stationinfo.php is supposed to create the DIVs in the main but it isnt.
this is what I tried so far, im new to Jquery and AJAX. thanks in advance!
working fiddle: http://jsfiddle.net/52n861ee/
thats what I want to do but when I click on desk_box DIV, the toggle station_info DIV is not being created by my display_stationinfo.php script.
When I view source code both DIVs are supposed to be already created but only desk_box is.. what am I doing wrong?
JQuery/AJAX part:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
alert("before toggle");
var id = $(this).attr("data")
alert(id);
alert($(this));
$("#station_info_"+id).toggle();
alert("after toggle");
$.ajax({
url: 'display_stationinfo.php',
type: 'GET',
success: function(result) {
alert("before result");
$("#station_info_"+id).html(result);
alert("result: " + result); //it shoes every DIV being created and not the one that I clicked on
alert("after result");
}
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while ($row = mysqli_fetch_assoc($station_result)) {
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info_' id='station_info_".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
echo $html;
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
Is fetching every row from the table coordinates, is this what you want to do? Or do you just want to return only the row with the id the users clicked?
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
success: function(result) {}
});
php
$id = $_POST['id']
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id == " $id;
Looking at you example, I would also guess that the problem could be that you are returning a string and putting it inside the target div so that the finished div looks somthing like this:
<div class="station_info_" id="station_info_84" style="position: absolute; left: 20px; top: 90px; display: block;">
<div class="station_info_" id="station_info_84" style="position:absolute;left:20px;top:90px;">
Hello the id is:84<br>
Section:Section B<br>
</div>
</div>
Instead of returning a string you could return a json object and append only data to the target div
php
while ($row = mysqli_fetch_assoc($station_result)) {
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
$result = array('id' => $id, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'sec_name' => $sec_name);
echo json_encode($array);
}
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
dataType: "json",
success: function(json) {
$("#station_info_"+id)
.css({'left':json.x_pos ,'top': json.y_pos})
.append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}
});