My php generates some type from the DB and it is passed to a Smarty Variable $X.
With the help of Jquery, I want to be able to click a button, and the content of one of my div will be be replace with $X.
$(document).ready(function(){
$("button").click(function(){
$("#div1").html($X);
});
});
This piece of Jquery script is included in an external js file.
If you have a template file that is parsed where you can output PHP->Smarty assigned variables, something you could do is create a global JS variable in the template, and then use that global variable within your JS as normal.
Such as:
Template file
<script type="text/javascript">
var MyGlobalVar = "{$MyGlobalVar}";
</script>
Global.js file
$(document).ready(function(){
$("button").click(function(){
if (MyGlobalVar != '') {
$("#div1").html(MyGlobalVar);
} else {
alert('Error! Error! Abort!');
}
});
});
Note, you could output the Global.js file with it being parsed by Smarty (although... this is probably not a great idea) and inject your PHP->Smarty variables this way. This would treat the Global.js included file as a Smarty template.
To do so, you would need to use {literal}, probably name the file with a .php file ending (so it was PHP-parseable), and add a PHP header() call so PHP outputs the file contents to the browser as a Javascript content-type.
Global.js
<?php
header("content-type: text/javascript");
?>
var MyGlobalVar = "{$MyGlobalVar}";
{literal}
$(document).ready(function(){
$("button").click(function(){
if (MyGlobalVar != '') {
$("#div1").html(MyGlobalVar);
} else {
alert('Error! Error! Abort!');
}
});
});
{/literal}
Additionally, on the PHP side, you might want to consider adding slashes to your variable, especially if the JS variable will contain html or other bits of text that will use single/double quotes.
Related
I minimized the code snippets to show only the code needed, and the url for the server side file is actually connected to a url on my server.
HTML FILE
<head>
<script>
var btid = 1;
$.ajax({
url: "serverSide.php",
method: "POST",
data: { "btid": btid }
});
</script>
</head>
<body>
<?php include("serverSide.php"); ?>
</body>
serverSide FILE
<?php
$btid = $_POST['btid'];
echo($btid);
?>
DESCRIPTION
So what is going on is when the page loads, the javascript code runs. It creates a variable named btid equal to 1. This variable is then sent to a file on my server that is a php file. I want to echo that variable through php. But when I load the page, I get an error log stating that the code $btid = $_POST['btid']; has an Undefined Index.
I don't think your code is going to work as designed. You are using include("serverSide.php"); in the body of the HTML, but it is never going to have any $_POSTvalues unless you are posting a form.
Your ajax call is not doing anything with the value that is being returned.
I think you should remove the include("serverSide.php"); from the body of your HTML (it is serving no purpose in its current incarnation) and use the returned value of your ajax call to put the value of btid in the HTML (if that is where you want it).
When you use PHP's include as in <?php include("serverSide.php"); ?> PHP will execute the code on the file being included. That is what is causing your error, when the code is first evaluated it has no $_POST['btid'] because you haven't called it yet.
Your javascript will run on page load and make the ajax call correctly, but you are not using the response anywhere. In order to store the response from the Ajax call you need to add a success handler.
If I understood what you are trying correctly, your code should look more like this:
HTML FILE
<head>
</head>
<body>
<div id="response"></div>
<script>
var btid = 1;
$.ajax({
url: "serverSide.php",
method: "POST",
data: { "btid": btid },
success: function(res) {
$('#response').text(res);
}
});
</script>
</body>
What we are doing is making the ajax call and when the call is successful we assign the returned value as the div content. Also, I switched the script tag to the end of the body because we need to be sure all the document has loaded before changing anything (could have used $( document ).ready()).
I have a main (index) page which loads pages dynamically and places them inside it's div but the Javascript within those pages doesn't execute. Specifically this part
<script type="text/javascript">
$(document).ready(function(){
$('#regForm').submit(function(e) {
register();
e.preventDefault();
});
});
</script>
You will have to use getScript like this:
$('#foo').load('bar.html', function(){
$.getScript("js/fileName.js");
// call a function from fileName.js
});
You will have to put your JS code in that file and call that via getScript and then you can call functions from it as shown above.
Write your javascript in the index.php or write at the bottom of loaded page without document.ready
This is in reality a cross-browser issue: When <div>s are dynamically filled with HTML containing <script> tags, these scripts may or may not run - and this behaviour is different not only between browsers, but also between browser versions.
The only workaround I know of is to extract your JS, send it seperately and execute it after the <div> content has been set.
I have this script in index.php file:
<script type="text/javascript">
$(document).ready(function(){
$('#ads').load('output.php').fadeIn('slow');
});
</script>
And the output.php file contains a hidden input by which I pass a php variable and retrieve it succesfully:
<script type="text/javascript">
num = document.getElementById('number').value;
</script>
And if I put, say, an alert(num); in the output.php file, everything works. Though when I do the same in the index.php file, javascript doesn't seem to see that num variable.
Im just going to ges that you dont actually wait until the file is actually loaded before testing to access that variable
http://api.jquery.com/load/
the load method takes a completed callback that u can use like this
$(document).ready(function(){
$('#ads').load('output.php', function() {
alert(num);
}).fadeIn('slow');
});
but you should probably not solve your problem this way i sugest you call a function from your
loaded file instead of setting a variable
You can't access variables before you create them. In the code you provided the first time num is being assigned to is when the output.php file is loaded and parsed. Since jQuery's load function isn't blocking - that is, your browser will continue executing JS while the load function is doing its magic - you have no good way to know when num will be assigned to. It could be milliseconds, or it could be never if your webserver refuses to return the output of output.php for whatever reason.
In jQuery programming, using a callback function is common practice, although you can make it cleaner by passing it a function reference instead of an inline function:
$(document).ready(function(){
$('#ads').load('output.php', outputLoadCallback).fadeIn('slow');
});
function outputLoadCallback(response, status) {
console.log(num);
}
Maybe an even better way would be to include the logic you need to run in the callback function like so:
var num; // Make sure num is in the global scope
function outputLoadCallback(response, status) {
num = document.getElementById('number').value;
console.log(num);
}
If you're "not much of a pro", may I suggest jQuery in Action?
hi i have a graph created from a .csv file using the jquery $.get(). but currently i am passing hardcoded file name as first argument to my get() method. My function is in a file named index.js and is like this
$(document).ready(function() {
$.get('myproject.csv', function(data) { ..... }
....... });
but what i want is to pass a variable which contains the file name so that it can have any file name instead of 'myproject.csv'
$.get($filename, function(data) {
where $filename could be any filename passed. i don't have much idea about jquery and all so not sure.
Now the main thing is that i have a .phtml file where i have this javascript file incorporated as inline script. So I have no idea how to pass the variable from this .phtml file to this javascript file.
My .phtml file:
<head>.......</head>
<body>
<script type="text/javascript" src="/PFFd02/public/media/js/modules/appone/index/index.js"></script> // this is where i need to pass my variable.
...........
</body>
any help???
This should work:
var filename=<?=json_encode($filename)?>;
$.get(filename, function(data) {
This sets the Javascript variable filename to the value of the PHP variable $filename, and calls $.get(filename).
$.get(<?php echo json_encode($filename) ?>, function(data) {
using json_encode ensures that any JS metacharacters in the filename won't "break" your script.
Thanks to you all. I figured out a simple way of passing the variable from php file to my js.
What i did was i created a view variable in my controller file and assigned it a string containing div tag as follows:
$this->view->filename = "<div id=\"filename\" style=\"display:none\">".$file."</div>";
where $file is the variable that contains my filename which i have to pass to javascript. Now in my zend view i did something like this:
<?php echo $this->filename ?>
which is making the filename available to my view where i have to run that javascript. Then in my javascript function i initialized a variable like this:
var file = $('#filename').text();
$.get(file, function(data) {
and so i got the variable passed from php file to my javascript function.
I have got this code
/* Popup for hot news */
$(document).ready(function() {
var $dialog = $('<div></div>')
.html('text to be shown')
.dialog({
autoOpen: false,
title: 'Table'
});
This code is in my JavaScript files which are included by header.php.
How to pass PHP output to this function?
Inputing <?php echo($mydata)?> in .html('') above does not solve anything.
Any reason why this gives an error?
Thanks for helping!
First of all your code is having some problem, $ in php is a prefix of variable and $ in jQuery is a selection sign. You can view the html source(the output) on browser for debug.
I can think of three ways to do so:
(1)The way you have mentioned should work, see the code below
<?php $foo='hi'?>
<script>
alert("<?php echo $foo?>");
</script>
(2)Another way is to separate server side and client slide code clearly for better maintenance
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<?php echo"<div id='foo' style='visibility:hidden;'>HI</div>"?>
<script>
alert($('#foo').text());
</script>
(3)The last way is by passing variable from the URL http://example.com/example.php#hi
<script>
var foo= location.href.split('#')[1];
alert(foo);
</script>
Adding <?php //code?> to your JS files do nothing because JS files are not executed by Apache. You can either use Ajax to request for data once your page loads (if the data doesn't need to be there at start) or you can add those PHP code blocks to your HTML code.
Using Ajax (goes in your JS file)
$(document).ready(function(){
var u = 'data.php';
var d = {};//data
$.get(u, d, function(data){
//got by data. lets invoke some methods here
});
});
Putting it in your HTML (goes in your HTML file)
var __DATA = '<?php //output some data I prepared earlier ?>';
//I'm using __ and capitol case to denote a global variable. Just personal preference
<script src='myjsfile.js' type='text/javascript'></script>
//the variable __DATA is available to your JS file and you can use it