I'm grabbing some information out of a database and passing it to some JavaScript using json_encode(). The line: var row_data = <?php echo $month_stats ?>; is dumping the object into the JS.
But now I want to abstract my JS into an external file, so suddenly I can't just echo the contents of the object into the JS since PHP won't have any presence there.
So I need to somehow (via AJAX?) send the PHP object $month_stats directly to the JS so that it can use the information independently of PHP, but I'm not sure how this is implemented. Any pointers?
<?php
include 'db.php';
$month_stats = generate_monthly_count_stats($conn);
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var row_data = <?php echo $month_stats ?>;
console.log(row_data);
</script>
</head>
<body>
</body>
</html>
You can simply echo the variable and access it in an external file:
<script type="text/javascript">var row_data = <?php echo $month_stats ?>;</script>
<script type="text/javascript" src="external.js"></script>
row_data is now a global variable, so you can access it in the external.js. However it is better to add it to a namespace if you have lots of other variables..
You can create some javascripn function in .js file
myFunction(obj) {
console.log(obj);
}
in your php file you can do that:
<script type="text/javascript">
myFunction(<?php echo $month_stats ?>);
</script>
When you put the JS into an external file, make it a function with one parameter.
In your .js file:
function logRowData(var1)
{
console.log(var1);
}
In your .php file:
<head>
<?php
include(filename.js);
?>
</head>
To log the stats, you can call in the php file.
<script type="text/javascript">
logRowData($month_stats)
</script>
More info on JS Functions
If you reference the variable row_data in your included Javascript file, it should work, as you are declaring that in the global scope. Here's one article for reference: http://snook.ca/archives/javascript/global_variable
Related
When I do:
<html>
<head>
</head>
<body>
<?php
$value = isset($_GET['send_request']) ? $_GET['send_request'] : false ;
if ($value) {
echo $value;
return;
}
?>
A
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
// data to send
var data = { send_request: 'Yes'}
request = $.ajax({
method: 'get',
data: data
});
request.done(function(response){
console.log(response);
});
}
</script>
</body>
</html>
In the console I am getting:
<html>
<head>
</head>
<body>
Yes
Why is this?
The error here is that your php code executes after you have already outputted this part:
<html>
<head>
</head>
<body>
Move the php code to the top of the page and it will fix this :)
Keep in mind that when you execute php script, php will not ommit html, but rather consider it output and just carry on :)
The best practice is to move your PHP codes to a separate PHP file and specify it's path in the url option of your ajax function. That new PHP file should of course not contain HTML before your PHP codes as already pointed out.
I am trying to call a javascript function from php. According to all of the examples I have been looking at the following should work but it doesn't. Why not?
<?php
echo "function test";
echo '<script type="text/javascript"> run(); </script>';
?>
<html>
<script type="text/javascript">
function run(){
alert("hello world");
}
</script>
</html>
Your html is invalid. You're missing some tags.
And you need to call the function after it has been declared, like this
<html>
<head>
<title></title>
<script type="text/javascript">
function run(){
alert("hello world");
}
<?php
echo "run();";
?>
</script>
</head>
<body>
</body>
</html>
In this case you can place the run before the method declaration, but as soon as you wrap the method call inside another script tag, the script tag has to be after the method declaration.
Try yourself http://jsfiddle.net/qdwXv/
the function must declare before use
it should be
<html>
<script type="text/javascript">
function run(){
alert("hello world");
}
<?php
echo "function test";
echo run(); ;
?>
</script>
</html>
As others have suggested, the function needs to be declared first. But, if you need to echo out the JavaScript from PHP first, you can either store it in a PHP variable to echo out later, or have your code wait for the dom to finish loading first...
document.ready = function() {
run()
}
If you're using jQuery or another framework, they probalby have a better way of doing that... In jQuery:
$(function(){
run();
})
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.
I need a little bit of help im trying to page a js variable into a url thats being parsed in php using file_get_contents. Im not sure where to start to do that.
<script type="text/javascript">
var js_variable = appl+goog+fb+mfst+nflx;
</script>
<?php
$ticker = js_varable_here;
$file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re');
?>
any advice is appreciated, like i said im in the dark on this one.
Here's an example using jquery.
Javascript:
<script type="text/javascript">
var js_variable = appl+goog+fb+mfst+nflx;
$.post("/somephp.php", {ticker: js_variable}, function(data) {
// returned from php
});
</script>
PHP:
<?php
$ticker = $_POST['ticker'];
$file = file_get_contents("http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re");
?>
Expanding on what Jashwant says...
PHP is a server-sided language, which does work behind the scenes. Javascript is client-side, which runs and executes code on the local client's machine (ie through the browser).
You can however use AJAX (Asynchronous JavaScript and XML) so the local client sends HTTP requests to the server without reloading the current page. For instance, you can use AJAX to send the contents of the variable to the server.
For easier usage, you should check out jQuery's methods regarding ajax calls. See: http://api.jquery.com/jQuery.ajax/
Hope it works well.
Heres how you can do it with jquerys post() and then return json, you could build the result as you expect to output within the php part or you could use jquery to loop with each() through the result.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'
&& isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
if(!empty($_POST['s'])){
$ticker = $_POST['s'];
$file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s='.$ticker.'&f=soac1p2ghjkj1re');
header('Content-Type: application/json');
echo json_encode(array('result'=>$file));
}else{
echo 'Request not allowed!';
}
die;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" charset="utf-8"></script>
<script>
var js_variable = "appl+goog+fb+mfst+nflx";
$.post('this_script.php',{s: js_variable}, function(data) {
$('#divResult').replaceWith('<div id="divResult">'+ data.result +'<div>');
});
</script>
</head>
<body>
<div id="divResult"><div>
</body>
</html>
How do I pass parameters from a HTML file to a external Javascript file if these parameters are provided to the HTML by the server side (Codeigniter controller)?
In other words, I have parameters that I want to pass from the serverside PHP/Codeigniter to the Javascript file.
PHP/Codeigniter Serverside Code
function view($id) {
$data['id'] = $id; // this is the variable I want to pass to Javascript
$this->load->view('index', $data);
}
HTML
<html>
<head>
<script type="text/javascript" src="./js/targetfile.js"></script>
</head>
<body>
<?php echo $id; ?> //this is how I can retrieve the variable from serverside
...
Javascript (targetfile.js)
var id = id_from_serverside; // This is where I want the serverside $id to go
Additional Info:
The variable $id is grabbed off the url, so for http://www.domain.com/view/1234, serverside variable $id will be set the value 1234. This 1234 value will then have to be passed to the javascript file (which does an AJAX call back to the serverside to retrieve data from the database)
You should be able to just do this:
<script type="text/javascript>
var id = <?php echo $id; ?> //this is how I can retrieve the variable from serverside
</script>
<script type="text/javascript" src="./js/targetfile.js"></script>
How about this:
HTML
<html>
<head>
<script type="text/javascript" src="./js/targetfile.js"></script>
</head>
<body>
<input type="hidden" id="my_id" value="<?= $id ?>" />
...
JavaScript
var id = $('#my_id').val();
Try this:
PHP/Codeigniter Serverside Code
function view($id) {
echo $id;
}
JavaScript
$.get('/mycontroller/view', function(data) {
alert(data);
}, 'html');
Skip the <html><head>... stuff. Just print the data you need. Then get the data via AJAX.
You can send parameters as JSON objects:
<?php
$object = array("foo" => "bar", 12 => true);
$encoded_object = json_encode($object);
echo '<script>var _page_params = '.$encoded_object.';</script>';
?>
will output something like this*:
<script>var _page_params = {"foo": "bar", "12": "true"};</script>
disclaimer: Don't have PHP on this machine, so there might be typos ;)