简体   繁体   中英

Counter not working as intended

I am trying to get some comments from the db.I have created a counter that is set to 2

var limit=2;

Once the user clicked it then comment count is set to 4 and second time counter value 6 .....etc

The problem is that when I click the button first time then 6 record are displaying instead of 4

$(document).ready(function(){
        var limit=2;
        $(document).on('click','.more',function(){
            limit=limit+2;
            $('#comments').load("loadComments.php",{
                limit:limit
            });
        });
    });

this is loadComment.php

 $limit=$_POST["limit"];
        $sql = "SELECT * FROM comments order by id desc limit  $limit ";  

Your very close

$(document).ready(function(){
    var limit=2;
    $(document).on('click','.more',function(){
        limit=limit+2;
        $('#comments').load("loadComments.php?limit="+limit);
    });
});

$limit = (int)$_GET["limit"];
//$limit = intval($_GET["limit"]); //if you like functions better they are basically the same.
$sql = "SELECT * FROM comments order by id desc limit $limit"; 

First off load is $_GET request, so you can pass limit via the query string in the URL.

Then, cast the limit to an int. A lot of prepared statements cant really handle the limit or order by clause very well. Not to mention I have no Idea what DB or library you are using. But casting it should take care of most of the issues.

Now It's perfectly acceptable to use load if it does what you want (load html inside a container), but it's considered a Get type request. Some people for some reason thing POST is somehow more secure then GET, well it's not. Therefor if this makes your code easier to read and implement than it's fine.

Description: Load data from the server and place the returned HTML into the matched element.

http://api.jquery.com/load/

The last thing I will mention is be careful of SQLInjection:

What is SQL injection?

It's best to always make your queries prepared statements. It's a bit tricky for the ORDER BY and LIMIT clauses in a query. But because limit only accepts a number we can cast it to int (int) , or use intval()

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM