-2

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!

Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
  • 2
    there is no button in your code with `id="btn2"` that might be one problem I guess. Or if you want to click on `id="btn1"` and it's added dynamically you need to replace this `$("#btn1, #btn2").click(function() {` with this `$(document).on("click", "#btn1, #btn2", function() {` because it was added after DOM was generated – maximedubois Mar 10 '17 at 17:49
  • `$("#btn1, #btn2").click(function() {` change it to `$(document).on('click',"#btn1, #btn2",function() {` and check also id = "btn2" is missing – Alive to die - Anant Mar 10 '17 at 17:51
  • Check your console log if there is an issue. – Neobugu Mar 10 '17 at 17:55
  • jQuery is only aware of the elements in the page at the time it runs, so new elements added to the DOM are unrecognized by jQuery. To combat the problem use [event delegation](http://learn.jquery.com/events/event-delegation/), bubbling events from newly added items up to a point in the DOM which was there when jQuery ran on page load. Many people use `document` as the place to catch the bubbled event, but it isn't necessary to go all the way up the DOM tree. Ideally [you should delegate to the nearest parent existing at the time of page load.](http://stackoverflow.com/a/12824698/1011527) – Jay Blanchard Mar 10 '17 at 18:32
  • [ID's Must Be Unique](http://stackoverflow.com/questions/5611963/can-multiple-different-html-elements-have-the-same-id-if-theyre-different-eleme), specifically because it will cause problems in [JavaScript](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id) and CSS when you try to interact with those elements. – Jay Blanchard Mar 10 '17 at 18:33

2 Answers2

1

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/

Mazz
  • 1,859
  • 26
  • 38
1

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

  1. value should be quoted <button id="btn1" value="2">Load More ... </button>

  2. Make use of dedicated function calling in jQuery like- $(document).on('event','dom_identifiers',callbackfunction(){})

  3. 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

  4. 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>";
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Veshraj Joshi
  • 3,544
  • 3
  • 27
  • 45