Reputation: 546
In my external JavaScript file, I have the following jQuery code:
$(function(){
$('#follow').on('click',function(){
$.ajax({
type: 'POST',
url : 'functions/follow.php',
data: {follower : session_id,
user : p_id,
success: function(result) {
if(result == 'followed'){
$('#follow').attr('id','unfollow').text('-Unfollow');
}
}
});
});
});
On my normal page, I have this:
var session_id = '<?php echo $_SESSION['id']; ?>',
p_id = '<?php echo $p_id; ?>';
but this is not passing the variables into the jQuery function. I have these two variables being set before the JavaScript file is being called, also.
EDIT: I have tested this with the function on the same page as where the button is, and I passed in the PHP values with an echo, and it worked then.
Upvotes: 0
Views: 77
Reputation: 682
You can create a namespace in the jquery object allowing access to it even inside events. Like so:
$.mynamespace = {
session_id: '<?php echo $_SESSION['id']; ?>',
p_id: '<?php echo $p_id; ?>'
};
Then reference those namespace vars in your code like so:
$(function(){
$('#follow').on('click',function(){
$.ajax({
type: 'POST',
url : 'functions/follow.php',
data: {follower : $.mynamespace.session_id,
user : $.mynamespace.p_id,
success: function(result) {
if(result == 'followed'){
$('#follow').attr('id','unfollow').text('-Unfollow');
}
}
});
});
});
This will also make them available for any other jQuery events/callbacks etc
(NB: Make sure your variables are being set before you try to use them, i.e. higher in the script)
Upvotes: 1