<? foreach ($waiting_users as $waiting_user): ?>
<? echo $waiting_user->user_id; ?>
<? endforeach; ?>
I need to define the user id in a javascript variable. What is the best way of doing something like this?
<script type="text/javascript">
var user_id = "<? echo $waiting_user->user_id; ?>"; <-------------???
var post_id = "<? echo $post_id; ?>";
</script>
EDIT
The foreach returns just one user id. It's used to display a user that has signed up for a chat. Then I use the code below which is in end.js to delete the user from a table.
DELETE FROM table WHERE user_id = ? AND post_id = ?;
<a class="end" href="#" title="End">End</a>
$(document).ready(function() {
$("a.end").click(function() {
$.post(base_url + "index.php/home/end", { user_id : user_id, post_id : $(this).attr('id') }, function(data)
{
alert(data);
}, "json");
});
});
I would recommend getting the desired data through a service which you could call from javascript using ajax, but your version works too, although it is a bit messy.
If you really want to write php code that generates javascript code, I recommend you pass the whole object to the client side. Just make it a JSON and javascript will interpret it as a native javascript object.
<script type="text/javascript">
var users = <?php echo json_encode($waiting_user);?>;
// do whatever you want to do with the users
// ex : iterate over all users
for(var key in users)
{
var id = users[key].id;
// ...
}
</script>
UPDATE
If you only want to pass to the client side only the ids of the users, you should loop the users collection (in php) and store them in an array (or object). Then use the mechanism described above :
<?php
$user_ids = [];
foreach ($waiting_users as $waiting_user)
$user_ids[] = $waiting_user->user_id;
?>
// ....
<script type="text/javascript">
var user_ids = <?php echo json_encode($user_ids);?>;
</script>
Collect the user ids in an array and then output that array as JS.
<script type="text/javascript">
<?php
$user_ids = array();
foreach($waiting_users as $u) {
$user_ids[] = $u->user_id;
}
?>
var array_of_user_ids = <?=json_encode($user_ids)?>;
</script>
Related
I'm currently in the process of relaying the data from a column called "followers_count", in a table called "tbl_users". The site has several users each with their own page. On those pages a person can click a follow button and the follow count is displayed, using JSON. The code works so far except it only shows/updates the data of "followers_count" for the first "userID" in the table. My question is, how would I alter the code so that it knows for each user's page to display their followers_count?
In changes.php:
<?php
require_once 'class.channel.php';
$user_change = new USER();
$seqFollows = $user_change->runQuery("SELECT followers_count FROM tbl_users");
$seqFollows->execute();
$row = $seqFollows->fetch(PDO::FETCH_ASSOC);
$follow_count = $row['followers_count'];
header('Content-type: application/json');
$array = array('followers_count'=>$follow_count);
echo json_encode($array);
?>
In index.php?id= (the user page template):
<div>
Channel Adds: <div id="follow_count" style="display:inline;"></div>
</div>
<script type="text/javascript">
var timer;
timer = setInterval(function() {
$(document).ready(function(){
$.getJSON('changes.php', function(data) {
$('#follow_count').html(data.followers_count);
});
});
}, 1 * 1000);
</script>
Also in index.php?id=, this is the code that determines whose page I'm currently viewing:
$currentID = ( isset( $_GET['id']) && !empty( $_GET['id'] ) ) ? trim($_GET['id']) : '' ;
$stmt = $user_home->runQuery("SELECT * FROM tbl_users WHERE userID=:uid");
$stmt->execute(array(":uid"=>$currentID));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
You need to tell changes.php what the user ID value is. You will need to modify your index.php file to supply that value. One option is to modify the AJAX call similarly to:
$(document).ready(function(){
$.getJSON('changes.php?id=<?php echo $_GET["id"]; ?>', function(data) {
$('#follow_count').html(data.followers_count);
});
});
Then your changes.php file will need to get the value of $_GET['id'] just like index.php.
I have column name status in Database it contains values(0,1) ,in front end i have image if i click the image it will redirect to the next page i am using ajax here, what i want before redirect it should perform if condition i want to check the database column status if the column contain any row '1' it should redirect if all rows in column '0' its not checking the if condition it will redirecting can anyone guide me how to perform this .below is my code(i.e now in row status all values are 0 it will not redirect it want to show alert but its redirecting)
html
<img id='redirect' src="/image/exporttt.png" style="margin:-30 0 0 0px;cursor:pointer;" >
$sql_selectsupplier = "********";
$result1 = mysql_query($sql_selectsupplier);
while($rows=mysql_fetch_array($result1))
{
$reditect=$rows['status'];
}
Ajax
<script>
$(document).ready(function() {
$("#redirect").click(function() {
if($reditect=1){
var clientid=document.getElementById("client").value;
$.blockUI(
{
message: '<h2>Please wait...</h2><img src="/image/loader.gif" />',
timeout: 2000
});
$.ajax({
type:"post",
data:"clientid="+clientid,
success:function(data){
window.location = '?action=clientroutingchange&clientid='+clientid+'';
$("#result").html(data);
$('.blockUI').hide();
}
});
}
else{
alert("no changes made")
}
});
});
</script>
From your code it's not clear which one is PHP code, and which one is out of the PHP block.
Inside your block you have
if($reditect=1){ which does not seem like a javascript code.
Is that php?
If yes, then you are using it wrong way. = is an assignation operator, so you do assign the value 1 explicitly this way.
I would suggest, if you are using PHP conditions, also to move thme outside the script block:
<?php if ($reditect == 1): ?> # `==` for comparison
<script>
var clientid=document.getElementById("client").value;
// .. all the code
</script>
<?php else: ?>
<script>
alert('.....');
</script>
<?php endif; ?>
If it was an Javascript condition, then you need to assign the value of the php variable to the js var
<script>
var reditect = "<?= $reditect; ?>";
if (reditect == '1') {
// something
</script>
Use == for comparision
if($reditect==1)
and your $redirect is a php variable which doesn't make sense in script
So, use
var reditect = <?php echo $reditect ?>
and check by,
if(reditect==1)
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I am writing a program which I need to add php code inside script
The html has a table, with 2 chosen selectbox, I want to update 2nd selectbox when first when has been changed by user
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') //Check if first select box is changed
{
var itemcode = $(this).parent().parent().find('[data-id="item"]'); //find second select from same row
//add items from order
<?php
$ord = '<script>document.write(ord);</script>'; //javascript variable to php variable
//This code is not working, if I update the php variable from javascript variable
mysql_query('select * from ords where ord_id = '.$ord.');
?>
$(itemcode).append('<option>a</option>');
$(".chzn-select").trigger("liszt:updated");
}
});
Any ideas?
You could try sending the variables by using the jQuery load function.
page1.html:
<script type="text/javascript">
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') {
var itemcode = $(this).parent().parent().find('[data-id="item"]');
$('#ord').load('page2.php?ord='+ord);
$(itemcode).append('<option>'+$('#ord').html()+'</option>');
$(".chzn-select").trigger("liszt:updated");
}
});
</script>
<div id="ord"></div>
page2.php:
<?php
$ord = $_GET['ord'];
mysql_query('select * from ords where ord_id = '.$ord);
?>
Here's an example of how it could be done with AJAX. You probably need to adapt it to your needs. The idea was just to show you the basics of an AJAX request:
<script>
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') //Check if first select box is changed {
var itemcode = $(this).parent().parent().find('[data-id="item"]'); //find second select from same row
//add items from order
$.ajax({
url: "order.php",
type: 'POST',
data: {
ord: ord
},
cache: false,
success: function(data){
$(itemcode).append(data);
$(".chzn-select").trigger("liszt:updated");
}
});
}
});
</script>
Create a PHP file to handle the request and echo the HTML to be appended. This is just a rough example:
<?php
$ord = $_POST['ord'];
if (is_numeric($ord)){
$result = mysql_query('select * from ords where ord_id = '.$ord);
if ($result){
//process query result here
//create HTML string that will be appended
$str = '<option>'.$option.'</option>';
echo $str;
}
}
?>
PHP runs on server-side and prepares the page before the client-side javascript code is invoked. so, assuming this is a PHP file that contains javascript, be advised that best thing the PHP might do is prepare which javscript code will be in the page. if you want to pass javascript variable to PHP, you must SEND them from the client-side to the server-side (probably with $.POST command)
It does not work because $ord in literally the value of:
<script>document.write(ord);</script>
Which is no where near a id.
Try using the jquery post:
$.post("phpdoc.php", { name: ""+ord+""})//this sends the ord value to the php page
.done(function(data) {
alert("Data Loaded: " + data);//this will alert returned data
});
So I want to store all of my MySQL results in an array I can manipulate with javascript/jQuery.
Here is my current code:
<?php
$sql = "SELECT * FROM potentials";
$result = mysql_query($sql) or die(mysql_error());
$potential = mysql_fetch_array($result);
echo json_encode($potential);
?>
And my Javascript:
<script type="text/javascript">
$(document).ready(function(){
var myArray = "<?php print(json_encode($potential)); ?>";
console.log(myArray)
)};
</script>
I keep getting "Unexpected number" or "unexpected identifier". Whats going on?
json_encode() returns an object using JSON notation. Strangely, you surrounded it with quotes. Try removing them :
<script type="text/javascript">
$(document).ready(function(){
var myArray = <?php print(json_encode($potential)); ?>;
console.log(myArray);
});
</script>
(and it's not an array, it's an object, so you might want to rename your variable ;) )
You are using json_encode() twice, however if you want to use it, you need to parse it. In jQuery this can be done via jQuery.parseJSON like this
var myArray = jQuery.parseJSON('<?php print json_encode($potential); ?>');
Also if you want all the results, you need to loop the query (e.g. with while) and then save it to an array
$array = array();
while ($row = mysql_fetch_array( mysql_query( $query ) )
{
$array[] = $row;
}
<script>
var data = '<?php echo $data; ?>';
var json = JSON.parse(data);
console.log(json[0]); //etc
</script>
Notice that var data = ... is SINGLE QUOTED, so you catch the echo from php as a String
Probably a dead simple and idiotic question (I'm totally new to javascript):
I have this code that loads a new post by clicking on a "next" or "back"-link. The clicks variable is used to scroll up and down in the sql-limit-statement (using the swapContent function), means you move backward or forward in the database by clicking the links. It works easy and perfectly:
<script type="text/javascript">
var clicks = -1;
function increase()
{
clicks++;
return false;
}
function decrease()
{
clicks--;
return false;
}
</script>
<div id="<?php echo $post['id'].'-multipost'; ?>">
<?php include('views/posts/_postmultipost.php'); ?>
</div>
<div id="<?php echo $post['id']; ?>-next" class="rightbutton" style="display:block;">
next
</div>
<div id="<?php echo $post['id']; ?>-back" class="leftbutton" style="display:none;">
back
</div>
The only problem: As you see I have several posts (post-IDs). But the javascript var "clicks" is always the same. How can I add the post-id into the javascript variable name "clicks", well, something like this :
var <?php echo $post['id']; ?>-clicks = -1;
Of course it doesn't work this way, but I have no clue how to manage it. Any advice? Sorry for this stupid question...
Thanks for your help!
UPDATE
Ok, got the solution: Bryan was right!!!
Changed the code to:
<script type="text/javascript">
var clicks = {};
clicks['<?php echo $post['id']; ?>'] = -1;
function increase()
{
clicks['<?php echo $post['id']; ?>']++;
return false;
}
</script>
The javascript in html stays as it is:
>
Clicks is now an object and will output the following in the swapContent-Function:
count: Array
(
[80] => 0
)
In php you would access the value like this:
foreach($count as $key=>$value) { $count = $value }
In javascript it seems to work a bit different like this:
for(x in clicks)
{
var clicks = clicks[x];
}
Seems to work perfectly now, thanks for your help!!
I'm not incredibly familiar with PHP, so I don't know about php echo. However, would using an object work?
var postClicks = {};
postClicks['<?php echo $post['id']; ?>'] = -1;
As far as I understand you are trying to get this:
var something-clicks = -1;
But in JS something-clicks is an expression - substraction of two variables.
Name tokens in JS cannot contain '-' in contrary with CSS.
You have a syntax error:
onmousedown="increase(); javascript:swapContent('next', clicks, '<?php echo $post['id']; ?>', '<?php echo $post['title']; ?>', '<?php echo $_SESSION['user']['id']; ?>');"
that javascript: is the problem. That property is expected to contain raw JS, and that token is invalid. the javascript used as a protocol is for use on the href property of an a tag.
Other than that, it looks alright. Just type clicks in the JS console of your browser to get the current value returned. Or add console.log('clicks:', clicks); to your function so that the result is logged out on each click.