0

I have the following function:

$(window).scroll(function() {
if(ready && labelstatus && $(window).scrollTop() + $(window).height() > $(document).height() - 100){
   $('#bottom2').html(loading);
   ready = false;
   $.ajax({
    url: 'scripts/nearbothome.php',
    data: {"currentNumber": botnumber, "usersid": usersid},
    type: 'post',
    success: function(data) {
    botnumber = "<?php echo $uniqueend; ?>";
    alert("<?php echo $uniqueend; ?>");
    $('#oldposts').append(data);
    $('#bottom2').html(bottom);
    ready = true;
    labelstatus = data;
    if (data < 1) {
    labelstatus = false;
        }
    }
  });    
}
});

This all works fine and does as intended EXCEPT for setting the variable 'botnumber' to a new value. The PHP variable which it's supposed to be set to should be returned by the .php file executed by the Ajax ($uniqueend).

See here:

<?php
//open a database connection
include("../db.php");

//receive value
$currNum = $_POST['currentNumber'];
$uidd = $_POST['usersid'];

$results7 = mysql_query("SELECT * FROM `uc_posts` WHERE `postinguser` IN (SELECT `followers` FROM `uc_users` WHERE `id` = $uidd) AND id < $currNum ORDER BY id DESC LIMIT 20");

sleep(1);

while ($row = mysql_fetch_array($results7)) {
echo '<div class="postfeed2">';
    $color='#ababab';
    $id = $row['id'];
    $page = $row['page'];
    $postinguser = $row['postinguser'];
    $displayname=mysql_fetch_array(mysql_query("SELECT `display_name` FROM `uc_users` WHERE `id` = $postinguser LIMIT 1"));
    $username=mysql_fetch_array(mysql_query("SELECT `user_name` FROM `uc_users` WHERE `id` = $postinguser LIMIT 1"));
    $checkiffav=mysql_fetch_array(mysql_query("SELECT * FROM `uc_posts` WHERE find_in_set($uidd,`likedby`) AND `id` = $id"));
    if ($checkiffav) {
    $color='#FF5733';
    }
    echo '<table><tr><td style="vertical-align: baseline;"><b><img src="blank-user-medium.png" width="50px" height="50px" style="vertical-align: text-top;margin-right: 8px;margin-top: 0px;border: 0px solid #D0D0D0;border-radius: 5px 5px 5px 5px;"></b></td>';
    echo '<td style="display: block;word-break: break-word;"><b>' . $displayname[display_name] . '</b>';
    echo ' <span style="color:#ababab;">@' . $username[user_name] . '</span>';
    echo '<br>' . $page . '';
    echo '<br><a href="javascript:void(0)" onclick="javascript:return like(' . $id . ',' . $uidd . ');"><i class="fa fa-heart fa-lg" id="heart' . $id . '" style="margin-top: 5px;color:' . $color . '"></i></a></td></tr></table>';

echo '</div>';
}

$uniqueend2 = mysql_fetch_array(mysql_query("(SELECT * FROM `uc_posts` WHERE `postinguser` IN (SELECT `followers` FROM `uc_users` WHERE `id` = $uidd) AND id < $currNum ORDER BY id DESC LIMIT 20) ORDER BY id ASC"));

$uniqueend = $uniqueend2['id'];

echo $uniqueend;

?>

I can see that it echoes: 184. However on the alert I added to the jQuery in order to verify nothing is there.

I would use json but I have a large amount of php/content data it returns so I'm not sure how that would fit in or work.

Thanks!

3
  • So basically you're doing an ajax request where you change a variable, and then you're expecing the echo statement to actually echo out the changed variable? That's not how it works, the echo statement happens on the server, long before the page is sent to the browser, and even longer before the ajax call happens, changing that variable on the server at a later time, won't affect what is echo'ed in the past. Commented Jul 15, 2016 at 21:07
  • That code is incredibly dangerous. You are vulnerable to sql injection attacks, and you are simply ASSUMING that queries never fail. Both are horribly bad things. Commented Jul 15, 2016 at 21:08
  • @MarcB I was going to verify the post data in the .php file later. I just wanted to get the functionality working for me first (I believe that's a reasonable solution, not sure, still learning). Commented Jul 15, 2016 at 21:12

2 Answers 2

2

This is a really common misconception. In your javascript you are trying to call php code however js runs on the browser and can't parse the php or access the server side php variables. JQuery will return anything sent to the browser in the data variable and you should access it there. In order to do that your code would look like this.

$(window).scroll(function() {
if(ready && labelstatus && $(window).scrollTop() + $(window).height() > $(document).height() - 100){
   $('#bottom2').html(loading);
   ready = false;
   $.ajax({
    url: 'scripts/nearbothome.php',
    data: {"currentNumber": botnumber, "usersid": usersid},
    type: 'post',
    success: function(data) {
    botnumber = data;
    alert(data);
    $('#oldposts').append(data);
    $('#bottom2').html(bottom);
    ready = true;
    labelstatus = data;
    if (data < 1) {
    labelstatus = false;
        }
    }
  });    
}
});

If you have other information to send to the browser as well you will either need to make multiple requests with different parameters or send back a json response and parse it on the javascript side. You can send a fairly large amount of data via json. If it is somehow too much data to send via json you probably need to send it multiple requests. Like I mentioned at the top you are not able to access php variables inside of javascript.

Sign up to request clarification or add additional context in comments.

3 Comments

Hiya, I have added in the extra code which would be returned if I used 'data'. Could you show me how I might separate the two and return using the same request. Thanks!
@Ben Rather than just passing plain html through what you should do is pass it through as json. In php you can create an array and instead of using echo to print it to the page store it as a value in the array and then use json_encode to encode that. Then echo your json and fetch the html from the json array. Then you can also store your other information as a value in your array and fetch it the same way.
These links should cover what you need. JSON Encode and JQuery getJson
1

Ajax doesn't work that way. The return value of your php script at the server is send as response to the browser, then it gets put into your data parameter of the success-callback function. So you will see, your id is on data and you will have to work with it.

Try it like this:

$(window).scroll(function() {
if(ready && labelstatus && $(window).scrollTop() + $(window).height() > $(document).height() - 100){
   $('#bottom2').html(loading);
   ready = false;
   $.ajax({
    url: 'scripts/nearbothome.php',
    data: {"currentNumber": botnumber, "usersid": usersid},
    type: 'post',
    success: function(data) {
    botnumber = data;
    alert(data);
    $('#oldposts').append(data);
    $('#bottom2').html(bottom);
    ready = true;
    labelstatus = data;
    if (data < 1) {
    labelstatus = false;
        }
    }
  });    
}
});

After comment:

You can put your html in a variable instead of outputting it immediately. And then put the html and the id into an array like

$html = "<div>";
// add more html into variable
$html .= "</div>;
$returnArray['html'] = $html; 
$returnArray['id'] = $uniqueend;

And in your frontend you then have to access those indexes in your data

$(window).scroll(function() {
if(ready && labelstatus && $(window).scrollTop() + $(window).height() > $(document).height() - 100){
   $('#bottom2').html(loading);
   ready = false;
   $.ajax({
    url: 'scripts/nearbothome.php',
    data: {"currentNumber": botnumber, "usersid": usersid},
    type: 'post',
    success: function(data) {
    botnumber = $data['id'];
    alert($data['id']);
    $('#oldposts').append($data['id']);
    $('#bottom2').html(bottom);
    ready = true;
    // don't know what you are trying to do from here on
    labelstatus = data; 
    if (data < 1) {
    labelstatus = false;
        }
    }
  });    
}
});

5 Comments

Hiya, I have added in the extra code which would be returned if I used 'data'. Could you show me how I might separate the two and return using the same request. Thanks!
You can put your html in a variable instead of outputting it immediately. And then put the html and the id into an array like $returnArray['html'] = $html; $returnArray['id'] = $uniqueend; , editing answer
Thanks for the solution will see if I can get it to work. Btw the last bit after your comment is to stop the function executing if it has reached the bottom. It reaches the bottom when no-more data is returned. I guess I would just change it to if ($data['html'] < 1) {
Hm after switching it to returning the whole result as an array such a test should not be needed. But yeah, first try to get it running and then try it without that last part
The check was to stop a 'loading' text from appearing every-time. I just tried the above but for some reason the return arrays weren't working. I switched to echo json_encode(array('cntent'=>$html,'newid'=>$uniqueend)); and now it's working perfectly. Thanks for the solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.