0

I have 2 files, index.php and ajax.php, I am retrieving data from ajax.php to display in index.php via ajax.. I would like to pass the username to ajax.php to use in my sql statement.. How can I achieve this?

index.php -

$profile_user =$_GET['user'];

    $(document).ready(function(){
        $('.loader').hide();
        var load = 0;
        var nbr = "<?php echo $nbr;?>";
        $(window).scroll (function(){
            if($(window).scrollTop() == $(document).height() - $(window).height()){
                $('.loader').show();
                load++;
                if(load * 5 > nbr){
                    $('.messages').text("No more to see..");
                    $('.loader').hide();
                }else{

                $.post("ajax.php", {load:load},function(data){
                    $(".images").append(data);
                    $('.loader').hide();
                });
                }
            }
        });
    });

ajax.php

$profile_user =$_GET['user'];
$sql = "SELECT * FROM images WHERE  user = '$profile_user'  ORDER BY ID DESC ";

Can I pass the variable in the ajax call?

Ryan D
  • 741
  • 1
  • 11
  • 29
  • You seem to be mixing up JavaScript and PHP here in an impossible way. [See this question](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript). – Pieter van den Ham Oct 10 '16 at 17:47
  • be a lot simpler if you just stored user in session variable instead of passing it all around – charlietfl Oct 10 '16 at 17:51

3 Answers3

1

Add the PHP variable in the AJAX call

$.post("ajax.php", {
  load: load,
  user: '<?php echo $profile_user; ?>'
},function(data){

And change $_GET by $_POST in your ajax.php file, like this

$profile_user = $_POST['user'];
Robiseb
  • 1,576
  • 2
  • 14
  • 17
0

You need to POST that data:

            $.post('ajax.php', {load:load, user: '"<?php echo $_GET['user'];?>"'},function(data){
                $('.images').append(data);
                $('.loader').hide();
            });
Solrac
  • 924
  • 8
  • 23
0

You can change

$.post("ajax.php", {load:load},function(data){
                    $(".images").append(data);
                    $('.loader').hide();
                });

to

$.post("ajax.php", {load:load, user:user},function(data){
                        $(".images").append(data);
                        $('.loader').hide();
                    });

And in ajax.php after getting mysql result just encode the array in json format and echo it.

$data = mysql_query($sql);
echo json_encode($data);exit;