Is it possible to insert php variables into your js code? [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
passing variables from php to javascript
I'm dynamically generating a list. I want to make each row hover on mouseover and clickable to a link. I want the link to pass the id of the content of the row.
Basically:
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?$cid');
});
});
</script>
The issue is in the js/jquery. I want to be able to grab the $cid and pass it to the student.php page upon click. The php code above works but the js won't of course. I know the fundamental of client-side vs server-side languages. This question doesn't warrant a lecture. I know I cannot do this exactly, but it is what I want to happen ultimately. Any thoughts on how I can achieve this simply? Thanks in advance my friends!

Yes, if you include the <script> section in your PHP code, you can do something similar to the following:
<script>
var foo = <?php echo $foo; ?>;
</script>
In your case, you would be looking into the following code structure:
<script>
$(function () {
$('#rc_desc<?php echo $cid ?>').hover(function () {
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid ?>').click(function () {
$(location).attr('href', 'student.php?<?php echo $cid ?>');
});
});
</script>
The reason why this is possible is because although the Javascript is run on the client-side, it's processed on the server-side first prior to being presented on the page. Thus, it'll replace all necessary instances of $cid with the one you have included.
Enjoy and good luck!
EDIT:
<script>
$(function () {
$('.rc_desc').hover(function () {
$(this).toggleClass('.tr ');
});
$('.rc_desc').click(function () {
$(location).attr('href', 'student.php?' + $(this).attr('id').split('rc_desc')[1]);
});
});
</script>

You can do it like this :
$(location).attr('href','<?php echo $cid ?>');
The javascript code doesn't know it comes from php, it appears as a constant (a literal) for it.

Yes it is possible. All you have to do is put your <?PHP echo $cid; ?> in where you need it
<script>
$(function ()
{
$('#rc_desc<?PHP echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?<?PHP echo $cid; ?>');
});
});
This is possible because by the time the scrip is put into the page the cid has already been replaced by the string on the server. Since PHP is server driven, before it spits back the html/script it will be just like you put it in yourself.

There is almost no way to actually communicate PHP and JavaScript. However, the best and simplest way is to set the ID within an attribute. The new HTML5 data attributes would be perfect.
For example, have a anchor tag with
<span data-id="22">some event</a>
and then:
$(this).attr('href','student.php?'+$(this).attr('data-id'));
Or just use
<?php echo $id; ?>
if it is not external JS file

Try this code
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
$(location).attr('href','student.php?' + $(this).attr("data-id"));
// if you want to redirect the page do this
// window.location.href = 'student.php?' + $(this).attr("data-id");
});
});
</script>

I think you block should be :
<script>
$(function ()
{
<?php foreach($courses as $cid=>cinfo) : ?>
$('#rc_desc<?php echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid; ?>').click(function ()
{
$(location).attr('href','student.php?<?php echo $cid; ?>');
});
";?>
<?php endforeach; ?>
});
</script>
UPDATE
But you don't really need to do this, you have
"<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
You can try this
$(function (){
$('.rc_desc').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
attrId = $(this).attr("data-id");
$(location).attr('href','student.php?'+id);
});
});

Related

Passing sql string variable into javascript function

I am trying to pass a string from a query into a javascript function.
An integer will pass into the function but string will not.
echo "<a href='#' onclick='delete_game({$title});'
class='btn'>Delete</a>";
<script type='text/javascript'>
function delete_game(title){
var answer = confirm('Really?');
if(answer){
window.location = 'delete.php?id=' + title;
}
}
</script>
I expected the javascript function to be executed, but instead nothing happens.
Why don't you use ajax for this? As mentioned in comments mix PHP/JS isn't good.
In your HTML, you can do something like
I'm assuming that you are using Blade.
Delete Game
Then in your javascript, you do this using jQuery:
function deleteGame(title){
var answer = confirm('Really?');
if(answer){
$.ajax({
url : "your-php-file.php",
type : 'post',
data : {
title : title
}
})
.done(function(msg){
$("#result").html(msg);
})
.fail(function(error){
console.log(error);
});
}
}
In your PHP you process receiving the data from post $_POST
$title = $_POST['title'];
You can understand better the Ajax function of jQuery here.
A few things:
I would change window.location to window.location.href
Change your echo to:
echo "Delete";
Check if $title is set
var_dump($title);
If you'd like to make it a bit cleaner and are prepared to use jQuery:
Delete
<script type='text/javascript'>
$(document).on('click', '#delete', function () {
var title = $(this).data('title');
var answer = confirm('Really?');
if (answer){
window.location.href = 'delete.php?id=' + title;
}
});
</script>

pass a variable to a JavaScript function [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a button in my php page :
<button id="myButton">Delete me</button>
and in that page I have a variable which I want to pass to a JavaScript function, and this is my JS code :
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
How can I do that ?
I think you might be wanting to put a variable through PHP on your button and pass it to your function using jQuery data. Check this out:
<button data-confirmed="<?php echo $confirmed; ?>" id="myButton">Delete me</button>
And in your js:
$(function() {
$('#myButton').on('click', function(e){
// get jquery object access to the button
var $thisButton = $(this);
// this gets that data directly from the HTML
var confirmed = $thisButton.data('confirmed');
if(confirmed) {
//Here I'll use the variable
}
})
});
Basically, you can access variables in javascript using this method if you are interpolating PHP vars directly on the page. If this isn't what you are looking for, please let me know in comments.
<button id="myButton">Delete me</button>
<input type="hidden" name="variable" id="variable" value=2>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {=
alert(document.getElementById('variable').value);
//Here I'll use the variable
}
})
});
You can declare the variable outside the click event like so:
$(function() {
var confirmed = true;
$('#MyButton').confirmOn('click', function() {
if(confirmed) {
// do stuff
}
});
});
Assuming you're talking about passing php variables to Javascript, you can do this when writing to the page, ex:
<?php
$passThis = 'Passing'
?>
<script language="javascript" type="text/javascript">
var sStr = "My name is <?php echo $passThis ?>.";
document.write(sStr);
</script>
You could also get integer values, doing something like
$integerValue = 5;
var int = "<?php echo $integerValue; ?>";
int = parseInt(int);
By modifying this, you could use it to pass more types of variables, so assuming you have something like this:
<?php
$text = 'someText';
?>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
you could do
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
console.log("<?php echo $text ?>");
}
})
});
</script>
to make Javascript alert 'someText'.

How to merge php-mysql data with jquery to fade data

I'm having a simple select statement using php-mysql and I have this script to change text with another.
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("text2");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<div id=deletesuccess > text1 </div>
Trying to display data from table using php-mysql and jquery above script but it's displaying only the last row the loop is not working
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("<?php echo $row['desc']; ?>");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<?php
}
But couldn't use it with the above PHP code to display data one by one.
You can do this easily by using jQuery ajax.
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
url: 'getData.php',
dataType: 'json',
type: 'POST',
success: function(data) {
$('#deletesuccess').delay(500).fadeOut(function(){
$.each(data,function(key, value){
$('#deletesuccess').html(value);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
}
});
});
</script>
Now in getData.php page you need to do query and echo json_encode data. That means the getData.php file should contain the following code:
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
$json = '';
while($row = mysql_fetch_array($getTextR)){
$json .= $row['desc'];
}
echo json_encode($json);
?>
Attention, you have not a clear difference between php and javascript code execution. The php code will make an echo of that javascript code, and after php has finish execution(on document ready) the javascript code will be executed at istant, so the last echo of javascript will have effect in the execution. try to separate the codes.
The problem is that you overwrite your JavaScript each time the loop runs. Instead you should make it like this:
<script type="text/javascript">
var php_results = '';
</script>
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
php_results += "<?php echo $row['desc']; ?> | ";
</script>
<?php
}
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html(php_results);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
Of course this would have to be cleaned up to make it pretty, but it should work. I added the pipe as a separator between the different descriptions from the database.

JQuery Updating Status

I am writing some jquery to call an ajax script every 2 seconds to get the result and update the page. I am mostly a backend programmer and could use some help on this.
This is the code I have now:
<script language="javascript">
function downloadProgress(id) {
$("#" + id + "").load("index.php?_controller=download&_action=getDownloadProgressAjax",
{
downloadId: id
}
);
setTimeout(downloadProgress(id), 2000);
}
</script>
<?php
foreach ($downloads as $dl) {
?>
<div id="<?php echo $dl["download_id"]; ?>">
<script language="javascript">
downloadProgress(<?php echo $dl["download_id"]; ?>);
</script>
</div>
<?php
}
?>
This does not work. What am I doing wrong or would you suggest another approach?
Thanks
I think that you are confusing your PHP script by giving it both query string variables (sent as GET) and data (which is probably getting sent as POST). Try this:
$("#" + id).load("index.php?_controller=download&_action=getDownloadProgressAjax&downloadId="+id }
since you are using jquery, you can use the $.ajax function when the page is ready.
$(function () {
function function downloadProgress(id) {
$.ajax({
url: "index.php?_controller=download&_action=getDownloadProgressAjax&downloadId="+id
})
setTimeout(function () {
if (downloadnotcomplete){ // this way your script stops at some pont.
downloadProgress(id);
}
},2000);
}
});
You will attach the downloadProgress(id) function to your download button or anything else, to trigger the function the first time.
The problem you are having is that you have to provide a parameterless function and not a function call to setTimeout. Also, I would do it a little bit different and use setInterval instead of setTimeout as it relays your intention better in the code. Here is how I would do it:
<script language="javascript">
$(function() {
setInterval(downloadHandler, 2000);
});
function downloadHandler() {
// I'm not sure where the id is coming from you will probably need to put a
// class on your div's so that you can select them.
$(".MyDivClass").each(function() {
var id = $(this).attr("id");
downloadProgress(id);
});
}
function downloadProgress(id) {
$("#" + id + "").load(
"index.php?_controller=download&_action=getDownloadProgressAjax",
{ downloadId: id }
);
</script>
and then on your div:
<?php
foreach ($downloads as $dl) {
?>
<div id="<?php echo $dl["download_id"]; ?>" class="MyDivClass"/>
<?php
}
?>
Hope this helps.

Jquery .each method

learning Jquery and integrating with PHP - getting there, but have one last challenge in some code I'm working on.
I have HTML in a string, trying to pull html in tags, might be multiple elements in the HTML string, so trying to use each. My function worked fine without each, below is my each integration (returns nothing currently):
<?php
$info = '<li><strong>I want this text</strong></li><li><strong>I want this text too</strong></li>';
$info = json_encode($info);
?>
<script type="text/javascript">
$(document).ready(function () {
$("a", $( < ? php echo $info; ? > )).each(
function () {
alert($(this).html());
});
};
This code below does work, but only returns the first element in the HTML:
<?php
$info = '<li><strong>I want this text</strong></li>';
$info = json_encode($info);
?>
<script type="text/javascript">
$(document).ready(function () {
var output = $("a", $( < ? php echo $info; ? > )).html();
var link = $("a", $( < ? php echo $info; ? > )).attr("href");
alert(output);
alert(link);
});
</script>
This is a description and a working example of How to use .each() LINK
You can try this one as a example
$("a").each(function(index){alert($(this).html()});
Your code is not working because there are a few syntax issues.
First, change
< ? php echo $info; ? >
to
<?php echo $info; ?>
PHP doesn't like spaces and the opening and closing tags must appear without spaces.
Second, close the ready function and the script tag properly. Instead of
};
use,
});
</script>
Why are you encoding a piece of XML with JSON? That makes like no sense at all. Both are ways to encode data. HTML is XML too, btw. You can directly reference the $info variable since PHP will process everything first on the server.
<?php
$info = '<li><strong>I want this text</strong></li>';
?>
<script type="text/javascript">
$(document).ready(function() {
$("a", $("<?php echo $info; ?>")).each(
function () {
alert($(this).html());
}
);
});
Or just remove the temporary variable altogether. Makes it combersome to read, but that's essentially what PHP is doing.
$("a", $("<?php echo '<li><strong>I want this text</strong></li>'; ?>")).each(
Or to make it even simpler, since you already have the HTML, simply include it as part of the page and maybe give it an ID to make referencing it easier with jQuery.
<li id="myList">
<strong>I want this text</strong>
</li>
<script type="text/javascript">
$(document).ready(function() {
$("a", "#myList").each(function() {
alert($(this).html());
});
});
</script>
This last example gets rid of PHP completely, but you weren't really using it anyways.

Categories