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 ;)
Related
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
My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.
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 have .js and .php files and html pages. I am including js files in html files and php files in js files.
I want to pass 'cat' value from js file to php file using address bar when I go to this page;
/demo/convert.html?cat=volume
But I have no idea how to do this.
By the way, this is a blacberry project and I am not sure if I can use address bar to pass value. Any idea is welcome.
Test this sample code with an URL like :
http://sputnick-area.net/test/index.php?foobar=works_as_a_charm
<?php
$var = $_GET['foobar'];
echo <<<EOF
<html>
<head>
<title></title>
</head>
<body>
demo of using PHP GET variable in Javascript :
<script type="text/javascript">
alert("$var");
</script>
</body>
</html>
EOF
?>
Edit :
if you'd like to handle GET variables from within JavaScript, consider the following HTML + JavaScript sample : http://sputnick-area.net/test/index.html?foobar=works_as_a_charm
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var vars = [], hash;
var hashes = window.location.href.slice(
window.location.href.indexOf('?') + 1
).split('&');
for(var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
alert(vars['foobar']);
</script>
</body>
</html>
Sure you can. When your JS function is called, you would have to do something like this:
function someFunction(someParameters) {
//Do whatever you need to do
window.location = "/demo/convert.html?variableName=" + variable;
}
This will cause a page reload with the new variable accessible through PHP in the $_GET array. For example:
<?php
$name = $_GET['variableName'];
if(length($name) < 3) {
echo "That is a short name!";
}
?>
A page reload (used here), is necessary to send value to PHP as it is run server side. Your only other solution would be to use AJAX and load page content dynamically. This, however, would be the simplest solution.
EDIT:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var urlvariable = getUrlVars()['variableName'];
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>