Use php var in javascript file fault [duplicate] - php

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I have a question about using a php variable in my javascript file.
This is my index.php file:
<body>
<div class="container">
<div class="row">
<div class="span12">
<?php
if(isset($_GET['appid'])) {
// GET appid
$appid = $_GET['appid'];
$json_url ='http://api.url.com/api/gateway/call/1.4/getApp?appid=' . $appid;
$ch = curl_init($json_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$str = curl_exec($ch);
curl_close($ch);
$data = json_decode($str);
$array = json_encode($data);
}
else{
}
?>
<p id="errors" class="text-error"></p>
</div>
</div>
<hr>
</div> <!-- /container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/plugins.js"></script>
<script src="js/main.js.php"></script>
</body>
As you can see I check if an appid is sent. When I received it I load data from an api.
In the bottom of the page I have a link to my javascript file. (.php because I want to use the php var $ array in my js file)
My main.js.php:
$(document).ready(function() {
var data = <?php echo $array;?>;
alert(data);
});
But I got always error in console:
Uncaught SyntaxError: Unexpected token <
Does anyone know what I do wrong?

You are creating the array in a completely different file! The two variables are not in the same scope. What's more, the Javascript file is apparently not interpreted as PHP (and neither should it). So:
Javascript complains about the <? tag, which it should never see.
Even if you solved that, it won't work since there's no PHP $array variable in main.js.php.
Start by understanding how Javascript and PHP are interpreted, see Reference: Why does the PHP code in my Javascript not work?.

Your variable is in a different scope since you're not using the PHP include function. Here's the easiest way I know to achieve what you want:
Rename your JavaScript file to main.js
Since you cannot use PHP in a .js file, declare your JavaScript variable before you call your script, like this:
<script type="text/javascript">
var array = '<?php echo $array ?>';
</script>
<script src="js/main.js"></script>
Then, in your main.js file, just replace the code you posted by this:
$(document).ready(function() {
var data = array;
alert(data);
});

Try this,
$(document).ready(function() {
var data = '<?php echo isset($array) ? $array :
json_encode(array("nothing in array data"));?>';
// if $array not set then it should return {"0":"nothing in array data"}
alert(data);
});

you forgot to Quote Value of var data use this
var data = '<?php echo $array;?>';

Related

Refreshing data in session_start()

I have two files php(index.php & data.php), the first send data to the second, and this it runs every one second and show the data.
The problem is the data is not updating
Maybe the code explains better
data.php
<?php
session_start();
$xml = simplexml_load_file("file.xml"); // the contents of the file changes every second
$json = json_encode($xml);
$_SESSION['varname'] = $json;
?>
index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script language="JavaScript">
window.setInterval(function() {
<?php
session_start();
$json = $_SESSION['varname'];
?>
var newdata = <?php echo $json ; ?>;
//code to show data
}, 1000);
</script>
Thank you in advance
session_start must be called before any output (see notes in the documentation) which means you have to call session_start before any output:
<?php
session_start(); ?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script language="JavaScript">
window.setInterval(function() {
<?php
$json = $_SESSION['varname'];
?>
var newdata = <?php echo $json ; ?>;
//code to show data
}, 1000);
</script>
You are not actually calling your data.php script from your javascript at all. Your javascript is just static at this point (look at your output source), executing the same function over and over again with the same value for newdata. You need to actually make an AJAX call to the data.php script to update the JSON.
Note that the session_start comments on this thread are important. This should be fixed as well, but that will not solve the fundamental problem you area having of wanting to use javascript to pull in the updated JSON data, but not having the value of newdata change because it is currently just static on your page.

Unable to access PHP array in javascript, javascript object initialized to array ends up empty in chrome developer tools

I'm trying to get a JSON from PHP array so I can overlay the JSON on to a google charts geochart. So I am trying to get this working by using this simple code in test.php file
<?php
include("conn.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<script type="text/javascript">
document.onload = function (){
var jsonObj = <?php echo json_encode($rowarr, JSON_FORCE_OBJECT); ?>;
var jsonString = JSON.stringify(jsonObj, null, '\n');
console.log(jsonString);
};
</script>
</body>
</html>
The conn.php file returns an array like so
{"Auckland":37616,"Wellington":35357,"Christchurch":29818}
But in the chrome developer tools I see that this code appears as
document.onload = function (){
var jsonObj = ;
// Chrome error here -> Uncaught SyntaxError: Unexpected token ;
var jsonString = JSON.stringify(jsonObj, null, '\n');
The jsonObj variable is empty, when there should be something in it.
On the CDT console I get
Uncaught SyntaxError: Unexpected token ;
at line 11 in this test.php file
Chrome somtimes just doesn't show processable arrays and XMLs properly but they are exist.
my advise: just dont test your codes on chrome before getting actual results on other Browsers.
I have encountered this kind of scenario yesterday.
<script type="text/javascript">
document.onload = function (){
var jsonObj = <?php echo json_encode($rowarr); ?>;
var jsonString = JSON.parse(jsonObj);
console.log(jsonString);
};
</script>
Seems to me that $rowarr doesn't contain what you think it contains. Maybe try logging it first....
console.log("$rowarr");
You're along the right lines.
First of all, you can get rid of the enclosing document.onload as it's pointless.
Secondly, here's the amended code:
var jsonStringified = <?php echo json_encode($rowarr); ?>,
jsonObject = JSON.parse(jsonStringified);
console.log(jsonObject);

php inside javascript checkbox value

I have a list list of checkbox with name of files that came froma DB. Then I have button for delete the files. I have the following code for the button:
<input type='button' id='submit_btn' onclick='eraseFile()' value='DELETE FILES' />
and the eraseFile function
...
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
<?php
echo "HElllo World";
?>
}
</script>
It gives an error "missing ; before statement" and "eraseFile is not defined"
Is it possible to write php inside javascript right??
Is it possible to write php inside javascript right??
Unless the PHP code is generating valid JavaScript, then no.
The reason eraseFile is being called undefined is that your echo statement is causing a syntax error since it is printing the string literal Hellllo World at the end of the JavaScript function which violates JavaScript syntax rules.
Yes, it is possible.
PHP is parsed on the server, so you will literally be printing "HElllo World" inside your javascript function, which would probably cause an error.
You might be looking do do the following:
<?php echo 'document.write("Hello World!");'; ?>
Your PHP output gets appended to your JS function making your javaascript look like this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World //syntax error here
}
</script>
You can do this:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
alert("<?php echo "HElllo World"; ?>");
}
</script>
This will give a pop-up saying 'Hello World'
To pass a value from your Javascript function to your PHP script, you can do this:
var yourJsVar = {assign value here};
url = "yourPHPScript.php?value=" + yourJsVar;
if (window.XMLHttpRequest)
{ // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = someFunction;
//someFunction will get called when the PHP script is done executing
try
{
req.open("GET", url, true);
}
catch (e)
{
alert(e);
}
req.send(null);
}
else if (window.ActiveXObject)
{ // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = someFunction;
req.open("GET", url, true);
req.send();
}
}
In your PHP script:
$yourPhpVar = $_GET['value'];
I mentioned someFunction above that gets called after the PHP script completes execution. This is how it should look. (Note that this is on your Javascript)
function someFunction()
{
if(req.readyState == 4 && req.status == 200)
{
//this will only execute after your AJAX call has completed.
//any output sent by your PHP script can be accessed here like this:
alert(req.responseText);
}
}
Try to echo a meaningful javascript code, "Hello World" it's not a valid JS statement.
Try something like
<?php
echo "alert('HElllo World');";
?>
Where is your eraseFile function defined?
if it is not defined until after the place it is called, you will get that error.
Side note:
You can have php echo inside of the javascript, except what you have there will not do much...
Yes, you can use PHP code in you script files, but your code generate invalid script code here.
<?php
echo "HElllo World"; // becomes: HElllo World (text!) in JS
?>
It is possible to write PHP in Javascript, but it is not the best pratice. The way we normaly do this is through AJAX read the documentation : http://api.jquery.com/category/ajax/
Yes, it is possible to include PHP inside JavaScript, since the PHP will be executed on the server before the page contents are sent to the client. However, in your case, what is sent is the following:
<script type="text/javascript" language="javascript">
function eraseFile(){
var checekedFiles = [];
$('input:checked').each(function() {
checekedFiles.push($(this).val());
});
alert(checekedFiles); // it gives me all the checked values..good
HElllo World
}
</script>
This doesn't validate as JavaScript, since the "Helllo World" is not a valid JavaScript command. This is why the function isn't being defined properly. You need to replace the "Helllo World" string with an actual JavaScript command.

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.

How can I access a multidimentional php array in javascript?

The code is like this:
<SCRIPT LANGUAGE="JavaScript">
function showReview(){
//javascript stuff
<?php
$http="obj.href ='http://localhost/PROJECT1/thispage.php'";
if (array_key_exists(0, $arr)){
$http .= "+'&PQID={$arr[0]['ID']}'+
'&PQNo={$arr[0]['QNo']}'+
'&PNextSWF={$arr[0]['NextSWF']}';";
}
echo $http;
?>
}
</SCRIPT>
But I can't access $arr array. I tried to declare it global or use the $GLOBALS variable.
Show Review is called during onclick.
$arr is set in the main php code.
I tried just accessing the array in the main php code and passing the resulting string to the javascript which is the '?&PQID=ar&PQno=1...' part of the URL but it doesn't pass successfully. I tried passing the array itself to the javascript but js but I couldn't access the contents.
PHP runs on the server, Javascript on the client - they can't see each other's variables at all really. Think of it this way - the PHP code just generates text. It might be Javascript, but as far as the PHP concerned, it's just text.
Basically, you need to use PHP to generate text which is valid Javascript for creating the same data structure on the client.
Add this to the JS-function:
var arr=<?php echo json_encode($arr); ?>;
The PHP-Array "$arr" should now be accessible to JS via "arr" inside the JS-function.
I guess you are trying something like this:
<?php
//example array
$arr=array(
array('ID'=>'0','QNo'=>'q0','NextSWF'=>1),
array('ID'=>'1','QNo'=>'q1','NextSWF'=>2),
array('ID'=>'2','QNo'=>'q2','NextSWF'=>3),
);
?>
<script type="text/javascript">
function showReview(nr)
{
//make the array accessible to JS
<?php echo 'var arr='.json_encode($arr);?>
//some obj, don't no what it is in your case
var obj={};
var href='http://localhost/PROJECT1/thispage.php';
if(typeof arr[nr]!='undefined')
{
href+='?PQID='+arr[nr]['ID']+
'&PQNo='+arr[nr]['QNo']+
'&PNextSWF='+arr[nr]['NextSWF'];
}
else
{
alert('key['+nr+'] does not exist');
}
//check it
alert(href);
//assign it
obj.href=href;
}
</script>
<b onclick="showReview(0)">0</b>-
<b onclick="showReview(1)">1</b>-
<b onclick="showReview(2)">2</b>-
<b onclick="showReview(3)">3</b>
Try this
<SCRIPT LANGUAGE="JavaScript">
function showReview(){
//javascript stuff
var http =
<?php
$http="obj.href ='http://localhost/PROJECT1/thispage.php'";
if (array_key_exists(0, $arr)){
$http .= "+'&PQID={$arr[0]['ID']}'+
'&PQNo={$arr[0]['QNo']}'+
'&PNextSWF={$arr[0]['NextSWF']}';";
}
echo $http;
?>
}
</SCRIPT>

Categories