Jump to content

Adding variable in js


V

Recommended Posts

I'm not sure how to add a variable to a js and pass it to another page. It's just a script for loading more comments like twitter.

 

this code

 

data: "lastmsg="+ ID,

 

passes a div id to ajax_more.php.. but how would I insert a variable like this into the js?

 

$post_id = $_GET['post'];

 

It's meant to grab the post id from the url to display its comments and I need to pass that id to the ajax_more.php file

 

The entire js is

 

$(function() {
//More Button
$('.more').live("click",function() 
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="images/ajax-loader.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#update").append(html);
$("#more"+ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});

 

and ajax_more.php

 

if(isset($_POST['lastmsg']))
{

$post_id = $_POST['post'];
$lastmsg= $_POST['lastmsg'];
$lastmsg = $connection->real_escape_string(strip_tags($_POST["lastmsg"]));

$sql = "SELECT * FROM comments WHERE post_id='$post_id' AND com_id<'$lastmsg' ORDER BY com_id DESC LIMIT 9";
$result = $connection->query($sql) or die(mysqli_error($connection));

while ($row = $result->fetch_assoc()) {

$com_id=$row['com_id'];
$com_dis=$row['com_dis'];
.....and so on

 

I get the error

 

Undefined index: post in ...
Link to comment
https://forums.phpfreaks.com/topic/205949-adding-variable-in-js/
Share on other sites

Since javascript is client side and php is serverside, i would guess that you would need to use php to write the js. So, maybe:

 

<script>

var post=document.write("<?php echo $_GET['post']?>");

</script>

 

Not great with js.. sorry if it's way off.

Your problem is that you're confusing GET with POST.  Looking at jQuery's ajax documentation, it's clear that the 'data' attribute is only supposed to be used with a GET request.  This makes sense, as it appends the 'data' to the end of the destination script's URL as part of a query string.  POST is done behind the scenes - no URL is used to pass data along.  In short, you can't use 'data' with a POST because POST doesn't work the way you think it does.

 

You'll need to rethink your design.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.