I am trying to get this code to work but cannot figure out how to make it work correctly. I think I am close though. This code works fine on my page:
var entryID = $(this).attr('id');
if ("<?php echo $locations[2]['floor']; ?>" == 'firstFloor' ) {
$("#drawTable").attr("style", "background:url(\'images/firstFloor.jpg\') 50% / 100% no-repeat;");
}
else if ("<?php echo $locations[2]['floor']; ?>" == 'secondFloor' ) {
$("#drawTable").attr("style", "background:url(\'images/secondFloor.jpg\') 50% / 100% no-repeat;");
}
I am trying to make the array changeable by using the entryID instead of just a number like '2'. I do not think that I am concatenating correctly below. If you can help It would be much appreciated! Thank you
var entryID = $(this).attr('id');
if ("<?php echo $locations . "[";?>" +entryID+ "<?php echo "]['floor']"; ?>" == 'firstFloor' ) {
$("#drawTable").attr("style", "background:url(\'images/firstFloor.jpg\') 50% / 100% no-repeat;");
}
else if ("<?php echo $locations . "[";?>" +entryID+ "<?php echo "]['floor']"; ?>" == 'secondFloor' ) {
$("#drawTable").attr("style", "background:url(\'images/secondFloor.jpg\') 50% / 100% no-repeat;");
}
Then thing is you can't do that as PHP already ran on server and javascript has started to work way later after DOM ready. So, that is not possible such way. Instead you can store1 the array in a js variable like:
var entryID = $(this).attr('id');
var locations = <?php echo json_encode($locations); ?>; // i suppose this could be array.
var floor = locations[entryID]['floor']; // <----target the floor here
if (floor === 'firstFloor') {
$("#drawTable").css("background", "('images/firstFloor.jpg') 50% 100% no-repeat;");
} else if (floor === 'secondFloor') {
$("#drawTable").css("background", "url('images/secondFloor.jpg') 50% 100% no-repeat;");
}
and Instead of attr such way better to use css or event better addClass.
1. - The js has to be written on php page.
You cant access php array through javascript. for this you should convert php array to javascript array and assign it in javascript variable after that you can access that array. Like this
<script type="text/javascript">
//Assign php generated json to JavaScript variable
var tempArray = <?php echo json_encode($locations); ?>;
//You will be able to access the properties as
alert(tempArray[0].Key);
</script>
Related
Is it possible to assign a php return to a js variable? ex:
<script type='text/javascript'>
var h = <?php include'dbconnect.php';
$charl = (some number from another sql query)
$sql=mysql_query("selct type from locations where id='$charl'");
echo $sql; ?> ;
if(h == "hostile") {
(run some other js function)
}
</script>
what I need to do is get a single text value (type) from the charl (character location) and assign it to a java script variable and run an if statement on it. any hints?
Here is an update on my code. it doesnt return any errors but its not outputting the way i want it to. it should return the [type] only which should be equal to hostile, city, farm, and stuff like that.it wont run unless the entire string is in the same line. I believe its returning the entire string and not just the echo (like i need it to)
function check_hostile() { var h = '<?php session_start(); include"dbconnect.php"; $charid=$_SESSION[\'char_id\']; $charloc=mysql_fetch_array(mysql_query("select location from characters where id=\'$charid\'")); $charl=$charloc[\'location\']; $newloc=mysql_fetch_array(mysql_query("select type from locations where id=\'$charl\'")); echo $newl[\'type\']; ?>';
if(h == "hostile") {
if(Math.random()*11 > 8) {
find_creature();
}
}
$("#console").scrollTop($("#console")[0].scrollHeight);
}
Here is the output of an alert function when theis is run.
<?php session_start(); include"dbconnect.php"; $charid=$_SESSION['char_id']; $charloc=mysql_fetch_array(mysql_query("select location from characters where id='$charid'")); $charl=$charloc['location']; $newloc=mysql_fetch_array(mysql_query("select type from locations where id='$charl'")); print $newloc['type']; ?>
Change it to this
var h = <?php include "dbconnect.php";
$charl = (some number from another sql query)
$sql=mysql_query("selct type from locations where id=$charl");
$row = mysql_fetch_row($sql);
echo json_encode($row["type"]); ?>;
json_encode() will convert a PHP value into a valid Javascript representation that you can inject into your script.
Yes, it is possible and is quite a common practice.
But your code has a small issue, it returns a string, so you must enclose it in quotes in javascript.
I have updated your code to fix that small issue and improve the code readability:
<?php
include'dbconnect.php';
$charl = (some number from another sql query)
$sql=mysql_query("select type from locations where id='$charl'");
if (mysql_num_rows($sql) > 0) {
$row = mysql_fetch_array($sql);
$h = $row['type'];
} else {
$h = null;
}
?>
<script type='text/javascript'>
var h = '<?php echo $h; ?>';
if(h == "hostile") {
(run some other js function)
}
</script>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to access PHP variables from within JavaScript?
I am trying to pass a variable from mySQL to PHP then to JavaScript to perform some math on it then have the result displayed on page in a specific area (in a <p> element with a specific ID assigned to it). Is this possible or is there an easier solution?
Thanks!
I already know how to get the variable from MySQL to PHP just having trouble on what to do after that.
Here is my updated code after reading responses. Still not working but I am sure I'm doing something wrong!
<p id="p_id"><?php echo $price; ?></p>
<input type="radio" group="radio_group" value="Reduce 10%" onclick="radio_click();" />
<script type="text/javascript">
var price = <?php echo $price; ?>;
function radio_click() {
var target = document.GetElementById('p_id');
var final_number; // this will be variable your store the final number in
final_number = price * .9;
target.innerHTML = final_number;
}
</script>
In short, you have to pass the variable to the <script> tag as a string in a JavaScript friendly format (quotes and stuff).
<?php
$variable = 5;
$javaScriptAccessible = '
<script type="text/javascript">
var javaScriptAccessible = "'. $variable . '";
</script>
';
echo $javaScriptAccesible;
Also, you could JSON it:
<?php
$variable = 5;
$javaScriptAccessible = '
<script type="text/javascript">
var javaScriptAccessible = '. json_encode($variable) .';
</script>
';
echo $javaScriptAccessible;
With JSON, the quotes would be appended automatically.
Here you can see both in action: http://codepad.viper-7.com/Jyfw31
Update:
Here are more refined and, I think, better to understand examples: http://codepad.viper-7.com/1cloyB
Only thing you have to do, is use it on your radio buttons / elements.
I'd strongly suggest going with JSON, because it actually stands for JavaScript Object Notation, it has libraries in, probably, every single programming language on planet, and is specifically designed to pass JS data from one environment to other.
http://php.net/manual/en/function.json-encode.php here you can see multiple options you're able to pass in order to render it differently.
Just output the variable from PHP into a <script> item. Then set the innerHTML property of your <p> based on your calculation. You can put this into a function and call it from your radio button's onclick.
<p id="p_id"><!-- Your value will be inserted here --></p>
<input type="radio" group="radio_group" value="some_value" onclick="radio_click();" />
<script type="text/javascript">
var your_number = <?php echo $php_number; ?>;
function radio_click() {
var target = document.GetElementById('p_id');
var final_number; // this will be variable your store the final number in
// do your math here using your_number variable
target.innerHTML = final_number;
}
</script>
To pass the data from PHP to JavaScript, just echo it.
For example, say you want to display the data in a message box:
$data="something";
echo "<script>";
// Do the maths
echo 'var = ' . $data . ' + 1';
echo 'document.write("<p id=\"someID\">" + var + "</p>");' // PHP code writing Javascript code to write HTML code. Wow.
echo "</script>";
If you want to display the data on click of a radio button:
<input type="radio" onClick="someFunction();">
<?php
echo "<script>function someFunction() {";
// Do the maths
echo 'var = ' . $data . ' + 1';
echo 'document.write("<p id=\"someID\">" + var + "</p>");' // PHP code writing Javascript code to write HTML code. Wow.
echo "}</script>";
?>
*Edit: If the <p> tag already exists, use document.GetElementById(\"someID\").innerHTML = var; instead of document.write("<p id=\"someID\">" + var + "</p>");.
I am using $_SESSION to pass back a value in the event of page redirect.
As jquery cannot access $_SESSION I decided to use PHP to output the value to a hidden div and remove that div once the value had been picked up. I expect that there is a neater way to do this but I don't know how else to expose the $_SESSION variable to jquery.
<?php
$pass_Back = $session->get_Pass_Back();
$session->clear_Pass_Back();
?>
<?php
if (count($pass_Back) != 0){
echo "<input class=\"field_Input_Left\" id=\"schedule_Description\" type=\"text\" name=\"schedule_Description\" value=\"" . array_shift($pass_Back) . "\"/><br />";
echo "<div id=\"pass_Back\" style=\"visibilty: hidden;\" ></div>";
} else {
echo "<input class=\"field_Input_Left\" id=\"schedule_Description\" type=\"text\" name=\"schedule_Description\"/><br />";
}
?>
Once this was done I needed a method to let jquery know if and when this new element was added to the DOM. Hence I used the plugin livequery to match when the element added. This it does which is great.
But when I try to access the value in the div it states that it is undefined.
$("#pass_Back").livequery(function(){
if ($("#class_Name").val() != 0){
var class_Name = $("#class_Name").val();
get_Schedule_Data(class_Name);
} else {
var class_Name = "ALL";
get_Schedule_Data(class_Name);
}
$value = $(this).attr("value");
auto_Fill_Schedule($("#pass_Back").attr("value"));
// destroy pass back
$("#pass_Back").remove();
});
When reviewed in firebug I note that at the point that livequery finds the added element no html is displayed. The DOM is ready otherwise the livequery couldn't have functioned but is this why no value is found?
Any guideance gratefully received.
Don't use this:
$value = $(this).attr("value");
Do the following to get a value (for inputs in most of cases):
(assuming $(this) is your input)
$value = $(this).val();
For div cases, there is no value, but you can get the html or text from inside as the value:
(assuming $(this) is your div)
$value = $(this).html();
//or:
$value = $(this).text();
Just to know...
You can mix PHP with jQuery but take a look at my answer from this post for better understanding:
Is echoing Javascript code condtionally based on server-side logic considered harmful?
As long you're not outputting the entire $_SESSION array, or anything of importance, you're going to be ok:
<?php
$pass_Back = $session->get_Pass_Back();
$session->clear_Pass_Back();
if (count($pass_Back) != 0){
echo '<div id="passBack" type="text" value="'.implode(",", array_shift($pass_Back)).'" />';
}
?>
JS
$(function() {
if ($("#passBack").length) {
//element exists in DOM, get the value
var passBack_data = this.value;
//do something with the value
}
});
Just output the element and make sure it's a string, not an array ( I used implode() ), and on pageload see if it exists (has length), and get the value.
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.
I have this jquery code in a foreach loop. Basicaly the variable $perf gets a new value with every loop. How can I use jquery to display the different $perf value with each loop? Is it possible?
foreach ($perfs as $perf):
<script type="text/javascript">
$(document).ready(function(){
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(''+performerName+'');
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
endforeach;
You should do it like this:
<?
foreach ($perfs as $perf):
?>
<script type="text/javascript">
$(document).ready(function(){
var $perf = "<? echo $perf; ?>"; //Get from php
alert($perf); //Show it
//Here goes the rest of your script
var performerName = $(".transparency").data('title');
var divcontent = $(".transparency").html();
if ( divcontent == ' ' ){
$(".transparency").html(performerName);
}
});
</script>
<div class="transparency" data-title="<? echo $perf; ?>"> </div>
<?
endforeach;
?>
That's it. It works.
(I tried to modify your code at least as possible, cause I don't know if I can remove parts)
PS: There would be more 'elegant' solutions, do you want one? or this is enough?
Can you please describe what you are trying to do? I'm about 90% sure there is zero reason for any javascript, jQuery or otherwise.
Why not just do this?
<?php
foreach($perfs as $perf)
{
echo "<div class='transparency' data-title='$perf'>$perf</div>";
}
?>
Unless there is something more you are trying to do, you don't need javascript at all. And even if you do need javascript, take the function out of the loop and call it once each iteration. you dont need the exact same function defined multiple times.
I suggest you look into the relationship between server and client-side scripting. For starters - take a look at the HTML source generated by your PHP and see if thats anything close to what you want. Also, read up about ajax. It seems that you are trying to do combine PHP/javascript in such a way that it needs additional HTTP Requests (ajax calls)
It is impossible to have PHP and javascript interact directly without AJAX, and it is difficult to answer the question without more knowledge of what, exactly, you want to happen.
If you want a different transparacy div for each value of $perfs you can use:
<?php foreach ($perfs as $perf) { ?>
<div class="transparency" data-title="<?php echo $perf; ?>"> </div>
<?php } ?>
And they you can use the jquery .each() to iterate over the divs
$(".transparency").each( function() {
var performerName = $(this).data('title');
// do stuff //
});
If all you want is to pass the values in $perfs to you javascript function you can use
var perfs = <?php echo json_encode($perfs); ?>;
OK I think I see what you are trying to do now. You'll want something like this:
<script type="text/javascript">
$(document).ready(function(){
var perfs = <?php echo json_encode($perfs); ?>;
$.each( perfs, function( index, value ) {
$( ".transparency" ).append( value+'<br>' );
} );
} );
</script>
<div class="transparency"></div>
This will output each value of $perfs inside of the transparency div.
Using JQuery each and append.
You will never want to wrap an entire script in a foreach loop, as that will create a separate script for each element in the array. Using json_encode you will change the PHP array into a javascript object & you can do whatever you want to with it.
Remember javascript is only able to access elements written to the page using echo or something similar. Whatever you can see when you look at 'view page source' in your browser is all your script will be able to use.