What is the proper way to execute JS? - php

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.

Related

How to use a jQuery object from php?

Why does this not work? This is the first thing in the body:
<?php
if(isset($_POST['submit'])){
echo "<script>$('.classToShow').show();</script>";
}else{
echo "<script>$('.classToShow').show();</script>";
}
?>
classToShow is a simple div in the body. It won't show up and its not depending on the boolean condition, it must be the code...
While this works:
<?php
if(isset($_POST['submit'])){
echo "<script>alert('works');</script>";
}else{
echo "<script>alert('works');</script>";
}
?>
So the simple JavaScript works, but the jQuery doesn't... Why is this?
This is your problem:
This is the first thing in the body
At that point the element with the class of classToShow does not exist yet, so nothing happens. You should wait for the DOM to be ready before you run that code.
On the other hand, if you just want to show something when a POST request was made, you can add it directly using php and you don't need jQuery to do that afterwards.
A common solution would be to show it directly using php and then use javascript to hide the message after a certain timeout.
You can use $(document).ready() and inside that write the code

how to echo a PHP variable before it has been declared

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

Why wont this code detect if javascript is blocked?

Okay, I have created a new question to clarify my old one, which is available here: Check if certain text was outputted to the screen PHP
Currently I have this code:
<?php
echo "
<noscript><h2>! JavaScript is not enabled!!! Features will not work !</h2></noscript>
<script type=\"text/javascript\">
document.cookie= \"jsEnabled=true\";
</script>
";
if (isset($_COOKIE['jsEnabled'])) {
// Javascript is enabled!
}
else {
die("JavaScript is not enabled!");
}
?>
I am not sure why this wont work! It should kill the PHP if JS is disabled! Thanks!
JavaScript processes after PHP has fully given out the page, not before, and not in symbiosis. As such, your PHP call will only work for the second call to the page, not the first.
That is, if you accept cookies in the first place.
If you want to prevent users without JS from using the interface on a page, consider generating the interface in pure JS instead. More reliable.

Use of PHP code inside Javascript code

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.

Call php value in javascript

I'm a bit of a newbie when it comes to Javascript and I am trying to find a way that I can pass a php value into a javascript/jquery function.
<script type="text/javascript">
$(document).ready(function() {
$('div#audit_admin_tabs').slideTabs({
contentAnim: 'slideH',
contentAnimTime: 600,
contentEasing: 'easeInOutExpo',
tabsAnimTime: 300,
buttonsFunction:'click',
tabSaveState:true,
autoHeight:true,
urlLinking:false
});
});
</script>
I have a value call $audit_id, the value for which is from a $_GET from the previous page. I would like to add it to the audit_admin_tabs. I have tried...
div#audit_admin_tabs<? echo $audit_id; ?>
But I realise that won't work because php is server side and javascript isn't. I have also tried echoing the whole function so I can add the php value but that didn't work either.
Thanks
div#audit_admin_tabs<?php echo $_GET['audit_id']; ?>
When you want get a get parameter you make it with $_GET['yourparam']
Greetz
You have the wrong tags. It's <?php ?> ... Not <? ?> ... As Franco has mentioned, you need to use $_GET['audit_id'] (or just use $_REQUEST['audit_id'] because that will take care of getting the value from $_GET or $_POST).
To answer your doubt about javascript being client side but PHP being server side :: Yes your understanding is correct, however in this case first PHP will do its magic so the code inside will get replaced with whatever it should be and then the resulting javascript will be served to the browser. And after that browser will execute that resulting javascript.
So, in short, it should work.

Categories