pass associative array from php to javascript [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to pass an array of strings from PHP to Javascript using $.ajax()?
I want to pass a associative array from php code to javascript code. Please help me. how do I do this ? Is JSON helpful in this matter? If yes then please provide a simple code for help. Thank you.
From comment below:
HTML + PHP code
<td>
<input type="text" style="width:70;" name="<?php echo $quantity;?>" id="<?php echo $quantity;?>" onkeyup="check_valid_range('<?php echo $itemName;?>','<?php echo $quantity;?>',<?php echo json_encode($product_inventory);?>);">
</td>
<script type="text/javascript">
function check_valid_range(product_field, quantity_field, inventory){
var product = document.getElementById(product_field).value;
var quantity = document.getElementById(quantity_field).value;
var v = inventory[product];
alert(v);
}
</script>

JSON is perfect:
<?php
$mySweetJSONString = json_encode($myAssocPHPArray);
?>
<script>
var iWantThePHPArrayHere = <?php echo $mySweetJSONString; ?>;
</script>
User pst brought up these concerns:
"array("</script>") -- darn, just broke this "perfect" approach."
It seems to work because (</script> => <\/script>): jsFiddle
"What about ]]> which could occur in XHTML?"The string is able to be transferred.jsFiddle
Update:
In regards to debugging the problem with the JS:
Are there any errors in the console? One of your document.getElementById(...) might be returning a null. Therefore the member value doesn't exist.

I always believed JSON were invented for this:
<script>
var myArray = <?=json_encode($myArray)?>;
</script>
This will render like this:
<script>
var myArray = {"key":"value","key2":"value2",...};
</script>
Safeness
This is perfectly safe for javascript, as JSON is a subset of the javascript syntax. This means that any JSON string can be treated as Javascript.
PHP's json_encode() is perfectly safe when embedding JSON in <script> tags too, because PHP escapes the / character:
json_encode('</script>');
=> "<\/script>"
So it's not possible to write </script>, which is the only way to escape a <script> tag. (Everything in a <script> tag is part of the script, it's not parsed as HTML.) JSON allows to escape the / for this purpose.
So no JSON string can escape a <script> tag.

Related

Remove a portion of php variable output

I have following php:
$my_name = $my_site->getUserData("dfd_Name");
<?php echo $my_name?>
It outputs as following: Steve, Kim
I want to keep the format as it is. However there are times when I only need the first part (for example, "steve").
Is there a jquery way to remove everything after (including ",") the comma, so it will be "Steve" as the output.
EDIT
So, I am using the following php:
<a class="my_name_class" href="http://example.com/section1/section2/section3/<?php echo $my_name ?>" >
<?php echo esc_html($my_name) ; ?>
</a>
What would be the jQuery (or any other ways) to remove the second part (, kim) within the href?
In PHP,
<?php echo explode(',', $my_name)[0]?>
In jQuery,
First select that DOM part,
var thing = $('#anything').html();
and explode like,
var name = thing.split(',');
Your desired value,
name[0];
Place it in DOM like,
thing.html(name[0]);
Here is a quick solution in pure jQuery
HTML:
<span class="name">Steve, Kim</span>
JS:
$(function () {
$(".name").text($(".name").text().split(',')[0]);
});
To get the second part, change the above code to:
$(function () {
$(".name").text($(".name").text().split(',')[1]);
});
Include jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
https://jsfiddle.net/myLnnd0e/
Showing second name: https://jsfiddle.net/myLnnd0e/1/
Fixed for URL: https://jsfiddle.net/myLnnd0e/3/
Solution for URL:
HTML:
http://example.com/section1/section2/section3/
JS:
$(function () {
$(".name-url").attr("href", ($(".name-url").attr("href") + $(".name-url").data("names").split(',')[1].trim())).append($(".name-url").data("names").split(',')[1].trim());
});
While this is a completely valid use of Javascript, it is always best to provide users with an alternate way to access this data, for usability issues and also in the case that Javascript is disabled.

Printing PHP variables into JavaScript variables [duplicate]

This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 9 years ago.
Yes I know this question gets asked a lot, but I'm fairly new to JS and I need to use a php variable in some JS. I'm more then aware that PHP is executed server side and JS is client side however other people claim that this works.
I've got a PHP variable called "test1" that I want to log to the JS console (for instance):
<?php
$test1 = '1';
print '
<script type="text/javascript">
var carnr;
carnr = "<?php print($test1); ?>"
console.log(carnr);
</script>';
?>
What this does is print " " to the JS console. Not exactly what I was hoping for.
Now this may not even be doable and I may have to pass the variable off the page and back in again with AJAX, but I'd rather have a quick and easy solution if there is one available!
Any help is appreciated.
You could do this.
<script>
var JSvar = "<?= $phpVar ?>";
</script>
The PHP will be parsed and the value of $phpVar will become the value of JSvar whatever.
Make sure you encode phpVar properly. For example, if phpVar contains a double quote, you'll end up with a broken JS
Use this no need to give "" => change to '.$test1.'..
<?php
$test1 = '1';
print '
<script type="text/javascript">
var carnr;
carnr = "'.$test1.'"
console.log(carnr);
</script>';
?>
try
<?php $test1 = '1'; ?>
<script type="text/javascript">
var carnr;
carnr = "<?php print($test1); ?>"
console.log(carnr);
</script>
Generally, it is better to not print static stuff with php, but to have static (that is unchanging) stuff directly in HTML and only use PHP on the parts that really need it.
You made a mistake do it so:
<?php
$test1 = '1';
echo '<script type="text/javascript"> var carnr; carnr = "'.$test1.'" console.log(carnr)</script>';
?>
Since you're writing your JS with your PHP, you can simply do:
$test1 = "blah";
echo "<script type=\"text/javascript\">console.log($test1);</script>";
You are already in open php tag. When printing the line just append the variable to the output by using a dot.
Example:
print 'variable1 '.$variable1.' is now printed';

Can you access the data in a php variable from a script? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pass a PHP string to a Javascript variable (including escaping newlines)
So I'm wondering if it's possible to access the data in a php variable, in a jquery/javascript script. Say I have a wordpress query/loop, that brings up a particular post from the database.
Then if I store that post in a php variable, is there any way I could reference that variable/post from within a javascript/script?
Yes. You can.
Scenario: 1 If HTML and PHP are in seperate files
HTML
<html>
<head>
<script type='text/javascript' src='code.php' runat='server'></script>
<script>
// you can get phpVar here
alert(phpVar);
</script>
</head>
<body>
</body>
</html>
code.php
<?php
$value =" Value from PHP";
echo "var phpVar = '". $value ."'";
?>
Scenario: 2 If HTML and PHP are in same file
<?php $value =" Value from PHP"; ?>
<html>
<head>
<script>
<?php echo "var phpVar ='" . $value ."'"; ?>
alert(phpVar);
</script>
</head>
<body>
</body>
</html>
You can do the below on a PHP page.
<script>
alert("<?php echo $hello_world;?>");
</script>
This won't work in a .js file, however, as it obviously isn't set to interpret PHP syntax.
So when your browser initiates a request, it hits the server. The server processes the request, running through all the necessary methods and setting variables, and then it sends the result back to the browser. At that point, anything not in session dies on the PHP side (i.e. it's not persistent) so there's no way for javascript to access this php variable.
If what you'd like to do is to pass a php variable or object to a javascript function, I'd recommend using json_encode:
http://www.php.net/manual/en/function.json-encode.php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
The above example will output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
You could output information about the post inline in a script tag like this (assumes you're in the "loop" and only outputting one post):
<script>
var post_id = <?php the_ID(); ?>;
var post_title = "<?php the_title(); ?>";
var post_excerpt = "<?php the_excerpt(); ?>";
</script>
However, depending on what you're trying to accomplish you may want to approach this differently. Perhaps using a script to output post data in JSON format so that it can be natively understood by javascript then writing AJAX functions to retrieve and render those posts. Here are some resources that may be helpful:
Wordpress JSON API
jQuery AJAX

Pass PHP variables to Javascript/jquery [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
So far I know two ways to pass php variables to javascript.
One is by using
<script>
$(document).ready(function()
phpvalue=$("#hiddeninput").val()
})
</script>
<input type="hidden" id="hiddeninput" value="phpvalue">
And the other one is by having for example a button and using onclick
<script>
function clickf(phpvalue) {
}
</script>
<input type="submit" onclick="clickf(<?php echo phpvalue ?>)">
All of them work great but:
Is there any other way that I'm missing?
Which one is the "best"?
Any chance that I can use inside the script or the external js ?
<script>
$(document).ready(function()
var phpvalue = <?php echo $var; ?>
});
</script>
Like others already answered, just put a PHP tag whereever you would place the JS value, like var foo = <?= $php_value ?>; or var foo = <?php echo $php_value ?>;.
If you want to use this in an external JavaScript file, you have to make sure .js files get parsed by PHP. If this is not an option for you (for example, your host doesn't allow it), I suggest you set the values in a <script> tag inside your <head> and then just reference thos variables from your external JavaScript. In that case, I would strongly suggest you namespace them like var app_vars = { foo: <?= $bar ?> } in order to not clutter the global object.
Another way would be to retreive the values via Ajax. But the viability of this approach depends on your use case.
And another hint: if you want to pass multiple variables or arrays, there's JSON baked into PHP since version 5.2:
<?php
$my_complex_var = array(
'array' => array('foo', 'bar'),
'val2' => 'hello world'
);
?>
<script>
var my_complex_js_var = <?= json_encode($my_complex_var) ?>
</script>
<script>
var javascript_variable = <?php echo $php_variable; ?>;
</script>
Instead of assigning values to hidden inputs, you could just generate JavaScript directly:
$script = <<<EOT
<script>
var phpvalue = $phpvalue;
</script>
EOT;
echo $script;
for the top example you do not need to use val you could use any attr you like.
For example
phpvalue="myvalue"
then within jquery
$("#hiddeninput").attr("phpvalue");

using JS variable in PHP

how can use JS variable in PHP like this ?
<script>
x = document.getElementById(1).value;
var listOf = <?php echo $listOf[x]; ?>;
</script>
this doesn't work :(
And rightfully so. PHP is executed on the server, while JavaScript is executed in the client's browser. Those are two different contexts and the variables from one are not visible in the second.
You need to have your PHP script output a JavaScript version of the array and then use this one in your script. Something like this:
<?php
echo "listArray = new Array();\n";
foreach ($listArray as $key => $value) {
echo 'listArray[', $key, '] = ', $value, ";\n";
}
You can't use it directly like this.
You'll have to use AJAX to send the value from client side to server side and only then PHP can see it.
Using jQuery it can become really simple though:
x = document.getElementById(1).value;
$.get("mypage.php?x=" + x, function(result) {
alert("response from PHP: " + result);
});
And in the PHP read the x from querystring and send proper output.
it is not possible because both are different languages so you cant use javascript varible
in php inside javascript
This is not possible. PHP is executed serverside, even before its output reaches your browser. JS is executed clientside, in the browser. You can't do this, unless you call some other PHP script with this variable x.
You can't. JavaScript is run in your browser while PHP gets run on the server. The only way for JavaScript to communicate with PHP is by using AJAX (XMLHttpRequest), separating the JavaScript from the PHP.
like this
if you put php in any single or double quotes than it work
<script type='text/javascript'>
x = document.getElementById(1).value;
var listOf = "<?php echo $listOf[x]; ?>";
</script>
This will convert javascript variable to php variable.
<script>
function sud(){
javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar.$phpvar;?>";
}
function sud2(){
document.getElementById("rslt2").innerHTML="<?php
echo $phpvar;?>";
}
</script>
<body>
<div id="rslt">
</div>
<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>
</body>
Demo: http://ibence.com/new.php

Categories