Stuckfornow
Stuckfornow

Reputation: 290

How do I get my variables to my PHP script through AJAX

I have 2 variables which I am trying to pass to my PHP script for use in my sql statement but it does not seem to want to work for me. Any ideas why I cannot get a value for my $start and $limit variables? Am I missing something here?

Here are the 2 javascript variables on my index.php page:

var start = 0;
var limit = 5;
var reachedMax = false;

$(window).scroll(function(){
    if($(window).scrollTop() == $(document).height() - $(window).height()){
        infiniteScrollData();
    }
});

$(document).ready(function(){
    //infinite scroll
    infiniteScrollData();
}

Then I have my javascript function in my javascript file that will send those 2 variables to my php page:

function infiniteScrollData(){

  if(reachedMax){
      return;
  } 
$.ajax({
        method: "POST",
        url: "sortResults.php",
        dataType: "json",
        data:  {
            infiniteScrollData: 1,
            start: start,
            limit: limit
            },
        success: function(response){
            if(response == "reachedMax")
                reachedMax = true;
                else{
                    start += limit;
                    $("#rowDisplayResults").append(response);
            }   
        }
});
}

Then I have my 2 variables in my php script like so:

if(isset($_POST['infiniteScrollData'])){
    $start = check_input($_POST['start']);
    $limit = check_input($_POST['limit']);

    $query = "SELECT * FROM topics DESC LIMIT :start, :limit";
    $stmt = $conn->prepare($query);
    $stmt->bindParam(':start', $start, PDO::PARAM_INT);
    $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
}

Check input is just a function to clean the data

function check_input($dirtData) {
    $dirtData = trim($dirtData);
    $dirtData = strip_tags($dirtData);
    $dirtData = stripslashes($dirtData);
    $dirtData = htmlspecialchars($dirtData);
    $dirtData = filter_var($dirtData, FILTER_SANITIZE_STRING);
    return $dirtData;
}

Upvotes: 0

Views: 75

Answers (2)

Kaleem Nalband
Kaleem Nalband

Reputation: 697

To send data to the server(PHP) use FormData object.

for more info please check the link.

https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

Upvotes: 0

ALPHA
ALPHA

Reputation: 1155

check_input method seems to be ok.

  • Check whether you are getting the start, limit vars to your js code in the first place
  • Check your URL whether its the correct url

Upvotes: 1

Related Questions