I have a HTML button:
<button>Button Name</button>
below the button i have a div which i am requiring a file in:
<div id="my_div"><?php require_once 'file.php'; ?></div>
in the file.php file i have a PHP variable, i want to echo this variable on the button name (Button Name var_here)
but its not showing the variable as the variable is being declared after i echo it
is there any way round this?
No. You can not echo out something that is not declared.
Three suggestions:
Rearrange your HTML so that your button is below the declaration. Then use CSS to let your button appear above the div-container.
Change your php scripts so the declaration is done somewhere else before your button.
Use Jscript to change your button (p.e. like Amir Noori suggested).
you can add the variable with javascript
<button>Button Name</button>
<div><?php require_once('your_file.php'); ?></div>
<script> $('#btnID').html('<?php $var ?>')</script>
note:I don't think it is possible to use a variable before declaring it. with my code you actually using it after declaring it.
Is there any reason that you can't do the require before the button? If so, that's the real problem that you're trying to solve, because no, before you put the value in the variable, it isn't in the variable, and hence can't be echoed.
So to answer the question-behind-the-question, it's necessary to know more about what you're trying to do.
Something about this design doesn't sit right with me, you usually include all your php up top, but I understand that for layout reasons you may want to go this way.
One way around it is to set this via javascript. This is a bit hacky (real hacky) but it would work. Use jQuery for ease of JS use after your include:
<script type="text/javascript" >
$('#my_div').text('<?php echo $my_var ?>');
</script>
I have sorted this now. In the required file rather than echoing the results creating a new variable ($var_display.= ...) then echoing $var_display under the HTML button
The file Is being required right at the top of the page
Related
I am trying to hide our mailing address on our website, until someone cliks a button to "load" the address. I am doing it like follows:
Homepage.php:
<button onclick="test()"> Click </button>
<div> </div>
<script>
function test(){
$.ajax({url:"address.php", success:function(result){
$("div").text(result);}
})
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Address.php:
<?php
function php_func(){
echo '<span><?php echo $address; ?></span>';
}
php_func();
?>
This works in echoing the text onto homepage.php, but it's not loading the PHP function. Just showing the function as text as seen here:
I tried $("div").write(result);} and it won't even load.
$address is already defined elsewhere. Any tips?
You're trying to write code which outputs code which outputs the address. Why? You're already in the context of outputting something from the PHP code:
echo "something...";
If what you want to output is the value of $address then just output that:
echo "<span>$address</span>";
I suspect the reason you did it that way is because you're expecting the currently loaded page to parse and execute that PHP code. This is a fundamental misunderstanding of how these technologies work. The PHP code for that page executed once, on the server, and delivered the resulting HTML/CSS/JavaScript to the client.
The AJAX operation is making a new, separate request to another PHP resource which will execute on the server and output back to the client. In this case it's just outputting a string value, which the client-side JavaScript code will then write to an element on the page:
$("div").text(result);
(This is a good opportunity for you to use your browser's debugging tools and observe the AJAX request/result in the network tab, to see what's actually being sent/received. At no point should actual PHP code be visible to the browser. All of that is executed on the server.)
The reason this is important is because, if this is the case, then you are likely misunderstanding where $address is defined. If it's defined in the PHP script which rendered the page you're looking at, that doesn't mean it's defined in address.php. If the code you're showing us for address.php is the entirety of that page then $address is not defined.
So you'll need to define $address on that page.
After having said all of that... You might find it much easier not to involve AJAX for this at all in the first place. Just output the address to the page but style the <span> to not be visible. Then when the user clicks the button, make it visible. No need for the complexity of an entirely new HTTP request:
$('button').click(function () {
$('span').show();
});
span {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click</button>
<span>this is the address</span>
You don't use <?php echo inside strings; that's only used when you're in a section of the script that's outputting literal text, not executing PHP code.
If you're in PHP code doing echo, you use variable substitution or concatenation.
<?php
function php_func(){
echo "<span>$address</span>";
}
php_func();
?>
You'll need additional code to set the $address variable; I assume you just left that out for simplification in the question.
<?php
function php_func(){
echo '<span>' . $address .'</span>';
}
php_func();
?>
this should work, u can't use 'echo' and inside echo open 'php' tag to use again.... more another 'echo'
Is it possible to use JS/JQuery from an external file? If so, what is the best practice?
What is the best practice to call a JQuery function inside a PHP or HTML page?
Here is file.php
echo "<table..";
echo "some code...";
echo "</table>":
<script type="javascript">
$('table').hide().fadeIn(700);
</script>
or:
echo '<script type="javascript">';
echo '$('#foo').toggle("slow");';
echo '</script>';
So, besides a best practice. is any of this possible? I can't seem to make it work from external file or directly.
also from external.js
$(document).ready(function(){ $('table').css({ // code here ... }); });
You can certainly echo jquery (or any html code) directly from PHP
echo '<script type="javascript">
$(\'#foo\').toggle("slow");
</script>';
Your issue in that one was the un-escaped quotes around #foo
I'm not really sure what you meant in the first part of your question, but since you have php I would use this option rather than trying to add jquery into an html file from another javascript file (if that's what you were trying to do)
Both internal and external javascript/jquery code should work.
Make sure you jquery script tag was include in you header/body
If external, make sure to include the external.js script tag after the jquery script tag
Make sure the document was ready first ( $(document).ready() ), and check again the selector either they are exist or not.
For more clean code, no need to echo every single line html code. Just close the php ( ?> ) and write the html as usual.
Please provide as much information as you can so that we know exactly what's the problem was.
Since I know many consider the use of PHP code inside Javascript code bad practice, I wonder how to execute a javascript function provided that a certain PHP variable has a certain value.
This is the way I currently write the code:
<script type="text/javascript">
function execute_this() {
some code;
}
<?php
if(!empty($_SESSION['authorized'])) :
?>
execute_this();
<?php
endif;
?>
</script>
Any ideas how to avoid using PHP inside Javascript in this particular example?
If you don't want to include any PHP code inside the javascript code but want to know the value of a php variable, you have to integrate a communication between the server side (PHP) and the client (JS)
For example you could use a ajax request to call a small php snippet that provides the value in its reply. With that value you can go on in you java script code.
In my opinion you should decide if its worth the effort.
Edit:
In regard to the edited question: If it is important that the JS function is never ever called if the PHP session value isn't present I would stay with the PHP code but would do it that way:
<?php
if(!empty($_SESSION['authorized'])) :
?>
<script type="text/javascript">
function execute_this() {
some code;
}
execute_this();
</script>
<?php
endif;
?>
If you evaluate the value of the session variable in javascript, you have to make sure that nothing bad happens to your code if the provided value was manipulated.
It's a matter of code style. The time your project grows, you will find it increasingly difficult to maintain it or to extend its functionality. A better solution would be to initialize all needed variables in the beginning of the file and to externalize the main JavaScript functionality.
Example PHP:
<script type="text/javascript">
MYCONFIG = {
authorized: '<?php echo $_SESSION['authorized']; ?>',
foo: 'something else'
}
$(document).trigger('init'); // fire init event, you can call it as you like
</script>
Example JS with jQuery (note that i use the custom trigger 'init', you can call it however you like):
$(document).on('init', function() {
function execute_this() {
document.write(MYCONFIG.foo);
}
if(MYCONFIG.authorized) {
execute_this();
}
})
This should be in an external JS file and does not need any PHP tags.
You have to store the php variables somewhere in the html code and then access it.
For example:
<input type="hidden" id="hidval" value=<?php echo $_SESSION['authorized'] ?>/>
then in your js:
var somevar=document.getElementById(hidval).value;
if(somevar==what you want){
execute_this();
}
I think you have some basic design issues, and we are only seeing the tip of the iceberg and can't fully help you.
There is nothing inherently wrong with calling a php function this way, but you have several issues:
1) you cannot separate your js file & allow for caching or cdn
2) while MVC is certainly not "mandatory", it is definitely a good idea to try to separate this type of logic from your "view" - your rendered output
3) I suspect elsewhere you have a massive security hole - if you are setting certain parameters based on whether or not they are "authorized" in their session, this means you are most likely sending back info on which to base a permissions decision in your php code somewhere. Never do that from the page - all data should be "neutral" on the page itself, because you have no control over it.
Give this a read if you are not clear why I say that: http://www.codebyjeff.com/blog/2012/12/web-form-security-avoiding-common-mistakes
There are three possible ways to do it.
Use hidden field and add necessary variable value inside each fields and get those using jQuery.
User jQuery Session plugin and access php session variable.
make a ajax call to php and get response in json format and access response.
Where am I going wrong with my programming logic here?
I have 2 php files. File 1 includes File 2. File 1 calls a php function from File 2. Inside the php function there is a bunch of html. The html works perfectly. At the end of the function I have this javascript....
<script type="text/javascript">
alert('hello');
</script>
This javascript isn't alerting "hello".
What am I doing wrong?
Thank you in advance.
EDIT: New question because I skrewed the last one up.
In theory would the code below run properly? (yes/no)
<?php function AlertHelp(){
?><script>
alert('help');
</script><?
AlertHelp();
?>
Long shot on a wild guess here with the limited information you gave.
My assumption is that you are not "including" the file via PHP's include, require, include_once or require_once functions, but are in fact using AJAX to load in the page's content.
If this is the case, then I shall also assume you're using innerHTML to put the content on the page.
Suddenly the solution is obvious: <script> tags added by innerHTML are not parsed and run. You could probably do something like this:
// assume `result` is the variable containing the AJAX response and `elem` the element it goes in
elem.innerHTML = result; // this doesn't change
result.match(/<script[^>]*>([\s\S]*?)<\/script>/i,function(m) {eval(m[1]);});
Please note however that eval should be avoided if possible. Consider redesigning your layout to use callbacks instead.
I have run into an interesting problem. I am currently developing php page and need to access a php variable within the javascript onload.
$(document).ready(function() {
var temp = <?php $page_id ?>
}
is this valid? I know that this might seem weird and not be allowed but I am developing a page that has two popup windows. The windows are created using the same view template and there is no way to distinguish between each other. If I stored a hidden value on the page with information unique to the page like so
<input type="hidden" value="<?php $page_id ?> id="page_id" />
if there are two views open at the same time there is no way for me to get a unique page id like so
var temp = $("#page_id").val();
Because there are two views with the same input id that is not unique. Long story short, is it valid to reference a php variable in the javascript?
Long story short is it valid to
reference a php variable in the
javascript.
Short answer, yes you can...PHP is server-side language, you can use it where you want.
Note: I assume that you are doing this in a file with php extension.
Long story short is it valid to reference a php variable in the JavaScript?
You are not referencing a PHP variable in JavaScript. You are simply generating the JavaScript code dynamically through PHP, where the value of the PHP variable $page_id gets hardcoded into the JavaScript code.
If you generate your JavaScript code through PHP, and you use var temp = <?php echo $page_id ?> it will work, but I wouldn't consider it best practice for bigger projects. I prefer my JavaScript code to remain static.
Your first piece of code is valid as long as you are generating the javascript. The same wont work if you put your js code in a separate .js file. Generating dynamic js is not a good practice for several reasons, like js browser caching and reuse for example.
If you want to completely separate the js code of php, you can create a client-server communication where js will ask for a specific value from a php script through ajax and later play with it in js environment.
The only thing you need is some clarification.
As a matter of fact, you cannot pass a variable. You can pass only it's value.
Also, one cannot "pass" anything from PHP to javascript. Javascript being generated by PHP. It is like HTML. You just generate any code you want. And you can use any variables, of course, with this code generation.
Your second example will work too, but you need to echo the value of the PHP variable to the page so that JavaScript can read from it. Also use htmlspecialchars to make sure you don't end up with invalid html.
<input type="hidden" value="<?php echo htmlspecialchars($page_id, ENT_QUOTES) ?>" id="page_id" />
You will find your answer in this question.