I am using Codeigniter and want to separate the JavaScript from the view files, but many of the JavaScript functions need data from controller (it depended on values from controllers)
ex:
controller :
function show_post() {
$data['data'] = $this -> get_data(); //some data
$data['random_key'] = $this -> generate_random(); //returns a random value
$this -> load -> view('posts', $data);
}
and in view I have a js function:
<script>
function get_random() {
return "<?= $random_key; ?>";
}
</script>
How can I save this javascript snippets to some other file say posts.js? If I did something like this then I cannot use php variables inside the script.
What is the best way to achieve this in terms of Performance and Maintenance?
Some other ways I do not want to follow :
Save the JS file as a PHP file and then pass the values to that file
Declare all those variable in the view file globally
you could pass the value as parameter to your js function, like
post.js
function get_random( param ) {
//use param here
}
//OR
function get_random( ) {
//get arguments like
var firstArg = arguments[0];
}
view.php
//include post.js file
//call the js function passing php variable as parameter, like
get_random("<?php echo $random_key; ?>");
did you mean something like this
One way to do it by using hidden fields, in your case store them in hidden field like:
<input type="hidden" value="<?php echo $random_key;?>" id="randomkey">
and access them in js by using ID like:
$("#randomkey").val();
In this way you can use controller paramter in your js.
Help it will help you!
the simplest method is that , define php variables as js variable in your view file
<script type="text/javascript">
var random_key = <?= $random_key; ?>;
</script>
then you can use that variable in your example.js file
Related
I have two separate pages, one page is where it uploads the file and the other page displays the information.
In the imageupload.php page, I have this session below:
$_SESSION['fileImage']['name'] = $_FILES['fileImage']['name'];
I also have a javascript function which calls back to the javascript functiom:
<script language="javascript" type="text/javascript">window.top.stopImageUpload();</script>
Now on a seperate page (QandATable.php), I have a javascript function, but my question is how can I call the $_SESSION code above in the javascript function so I can append it to $('.list')?
Below is javascript function:
function stopImageUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append('<br/>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}
You cant, because $_SESSION is a server side variable but you can access it by.
For the entire session variable
<script type="text/javascript" >
var session = <?php echo json_encode($_SESSION); ?>;
</script>
For a particular variable in session.
<script type="text/javascript" >
var session_var = <?php echo json_encode($_SESSION['VAR_NAME']); ?>;
</script>
Now you have js variable called session with that information. However it is not advisable in most situation to output all that info to public pages.
Session variables are stored on the server. JavaScript is executed on the cliend side, so it knows nothing about the server side. It know only as much as you pass to it.
To pass a variable to javascript, use an ajax request, or simply output the values:
<script>
var sesionValue = <?=json_encode($_SESSION['value']);?>;
</script>
You should look into using JQuery, as it makes these AJAX-like tasks much easier.
See my function I wrote just today to do something similar to what you're asking.
This takes some PHP output (returned in the success part of the call to ajax(). The format it takes is in JSON, which is compatible by both PHP and JavaScript (JSON: JavaScript Object Notation).
function viewClientDetails(id) {
var clientParams;
clientParams.clientID = id;
$.ajax({
url: BASE_URL + '/clients/get-client-details.php',
type: 'POST',
data: clientParams,
dataType: 'JSON',
success: function(myClient) {
var name = myClient.name;
$('td#name').html(name);
},
error: function(e) {
console.log(e.responseText);
}
})
}
In my PHP file (called /clients/get-client-details.php) I have something like this:
<?php
...
$myClient = array('name' => 'Mr Foobar');
print json_encode($myClient);
?>
This simply writes my PHP object to JSON format.
In the JS code above, the code inserts a part of the JSON data into an HTML table-data element whose CSS selector ID is #name, with the line: $('td#name').html(name);
Apologies if this confuses you more, I thought I'd show an example of what you can try some time..
This may help you a bit along the way...keep trying things, you'll get there :)
You can't. $_SESSION is a PHP variable, and that code runs server-side.
You'll need to store the value as a Javascript variable in the output from your PHP file, then access that variable in your Javascript.
I am passing a variable via the URL as var=5 to urlrun.php (like urlrun.php?var=5). There is a JavaScript function called testrun in urlrun.php.
Is there a way to call that JavaScript function depending on the value of that variable (var) passed through the URL?
For example, if($_GET['var']==5), I need to call that JavaScript function.
Put this somewhere:
<?php if($_GET['var'] == 5) { ?>
<script type="text/javascript">
testrun();
</script>
<?php } ?>
I am using a code look like this:
<script>
function getdata()
{
var employee =
<?php
//connect to database and get employee name
echo "'" . $row['empnm'] "'";
?>;
}
</script>
print them
It works, but the function is running the PHP code only on the page loading and not every time I call the function. So, if the target employee name is changed the JS function will show the old name untill the page is reloaded. How to make the JS function get the data from the database everytime I call it?
look into a library like jQuery
Then using the following code
function getdata(){
$.post("path/to/file.php", function(data) {
var employee = data;
// do whatever with the data.
});
}
and you can still use your same html
print them
and file.php
<?php
// connect to your db, get your results, echo them back
echo $row['empnm'];
?>
When you first request the page, PHP renders out a whole string of html, then your browser executes that generated HTML, not the original PHP. i.e. your server is going to send something like
<script>
function getdata()
{
var employee =
"hello world";
}
</script>
print them
So, as far as the web browser knows, "hello world" is just hardcoded there.
You'll need to look into AJAX for how to make it work. Check out this beginners' tutorial on using jQuery for ajax: http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
Define a global variable
<script>
var employee = <?php echo "'" . $row['empnm'] "'";?>;
function getdata(){
return employee;
}
</script>
Now keep on changing variable employee whenever it is changed
print them
If you're in a PHP loop -- it does looks like you are, since -- you can use PHP to define the parameter to be passed into getdata() in your loop; e.g.
<script type="text/javascript">
function getdata(employee) {
// connect to database and get employee name
}
</script>
<?php
foreach ($loopData as $row) {
print 'print them';
}
?>
I have some javascript that is being included in a view and I used inkedmn's method in this thread:
adding-page-specific-javascript-to-each-view-in-cakephp
So I now have the following code in my view:
$this->set('jsIncludes',array('google')); // this will link to /js/google.js
But I need to pass some values from the view into the javascript file and I'm unsure of how to accomplish this.
Update: I guess one option would be to echo the values in the php file, enclose in a div tag, and then use a getElementById() in the javascript code.
You should be able to inject a <script> tag directly into the HTML with the data you want:
<script type="text/javascript">
var mynum = <?php echo intval($num); ?>;
var mystring = "<?php echo addslashes($string); ?>";
var myarray = <?php echo json_encode(array("one" => 1, "two" => 2)); ?>;
</script>
Any javascript elsewhere should be able to use these variables.
Note: if the code using this data runs earlier in the page, they obviously won't see these variables yet. If that's the case, either ensure that your data is loaded first, or you can delay the code from running until the page is fully loaded, using either setTimeout() or a document.onready event.
Do you have some code that runs automatically? You could wrap it inside a function, and pass the function the necessary parameters.
For example, let's you currently have the following code in my-script.js:
window.onload = function() {
alert('My favorite fruits are apples, and my favorite color is red.');
}
Wrap it in a function like this:
function initialize(args) {
window.onload = function() {
alert('My favorite fruits are ' + args.fruit +
', and my favorite color is ' + args.color + '.');
}
}
Then, output a <script> element using PHP somewhere after my-script.js is loaded, and call the function. Here's an example output:
<script>
initialize({fruit: 'apples', color: 'red'});
</script>
$this->Js->set('varname',$value);
from js file
var myvar = window.app.varname;
These are following step:
1) Include the js helper in AppController.php
public $helpers = array('Js');
2) Now Declare js variable in ctp file
Like that way :
$state = 'rajasthan';
$this->Js->set('state_name',$state);
echo $this->Js->writeBuffer(array('onDomReady' => false));
3) Now Use this js vairable "state_name" in js file
Like that way :
console.log(window.app.state_name);
var state = window.app.state_name;
How do you call a PHP function that is in a different file from a JavaScript function?
I have a JavaScript function that recieves a variable from an onClick function. The variable is an id that I will use to retrieve data from MySQL database. The variable is then passed on to a PHP function that will access the database to get the data and return back to my JS function for display, but it does not seem to be working. How can I get it to work? I am using CodeIgniter PHP.
Here is my code:
JavaScript in a different file called divUpdate.php
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
base_url = '<?= base_url();?>index.php/';
</script>
<script type="text/javascript">
function changeDiv(venueID){
//document.getElementById('venue_description').innerHTML=venueID;
$.get(base_url+'home/get_venue_description/' + venueID,
function(data) {
$('venue_description').html(data);
});
}
</script>
Where the onClick function calls the JavaScript above:
<li><a href="#self" class="menulink" class=&{ns4class};
onClick="changeDiv(\''. $venue_details->VenueID . '\')">;
Function below is called from JavaScript above in divUpdate.php. The function below is also in in the model- venue_model.php
function retrieveData($venueID){
$query = $this->db->query("SELECT * FROM venue WHERE VenueID = '$venueID' ");
return $query;
}
Then, in the controller home.php I have a function that the JavaScript uses to pass the id that will then be used by the model to retrieve the data from the database
function get_venue_description($venueID){
echo $this->venue_model->retrieveData($venueID);
}
For some reason the code in the JavaScript divUpdater.php doesn't work. It looks correct but doesn't work.
Basically, in your Javascript, you should do
http://www.mywebsite.com/foo.php?venueID=123
or a form in your framework, like
http://www.mywebsite.com/controller/action/123
You can use Firebug in Firefox to do a console.log(base_url) because it looks like
base_url = '<?= base_url();?>index.php/';
$.get(base_url+'home/get_venue_description/' + venueID,
and your URL is something like:
http://www.mysite.com/index.php/home/get_venue_description/123
and in your PHP file, do a
$venueID = $_GET['venueID'];
if (preg_match('/^\d+$/', $venueID) {
$query = $this->db->query("SELECT * FROM venue WHERE VenueID = '$venueID' ");
}
The preg_match() is to say, if the $venueID is only full of digits and nothing else. This is to prevent SQL injection where somebody sends in some string to get your query to do something not intended by you.
Also, do some print_r() or var_dump() in your PHP file so that you can make sure what you are getting from the browser is correct.