user2828701
user2828701

Reputation: 305

OnClick Function Get Next Record PHP AJAX MYSQL

I am getting stuck with an example I found on SO about this very topic. See original article: How do I show next result in MySQL on "onclick" in JavaScript?

I followed this example to the T, with the exception of using some updated functions. Anyway, I am getting stuck on one step, was hoping someone could explain.

within the jquery below, the code is setting $number and then passing number in the POST action to the php file. My problem is is that when echo 'count', it echos "$number". I am not sure why it is not passing an actual number such as "0" rather than the string "$number". I am probably doing something seriously wrong, but not sure what is going on.

jquery

$(function(){
  $('#showMore').click(function(event) {
     event.preventDefault();
     $number = $('.result').size();

    $.ajax({
       type: "POST",
       url: "getNext.php",
       data: "count=$number",
       success: function(results){
         $('#results').append(results);
       }
     });

  });

PHP
I am passing count into a variable so that I can use it in a query, like so:

$pst = $_POST['count'];

SQL

$sql = "SELECT * FROM tablename LIMIT $pst,1";

I went ahead and captured the error I am receiving (see below) - as mentioned previously it is inserting "$number" instead of an actual number.

"Fatal error: Query Failed! SQL: SELECT * FROM tablename LIMIT $number,1

any help would be much appreciated

Upvotes: 2

Views: 1823

Answers (2)

bipen
bipen

Reputation: 36531

problem is you are sending count as string which is $number in your case.

your data should be

data: {"count":$number}, //notice `"`

send it as object.

or

$data:"count=" + $number,

concate the var

i prefer data as object which is more readable.

Upvotes: 2

MosheK
MosheK

Reputation: 1196

Try changing this line:

data: "count=$number",

To this

data: "count=" + $number,

Javascript doesn't "read" strings for variables like php does, so you need to concat the value manually.

Upvotes: 3

Related Questions