Call php value in javascript - php

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.

Related

jquery php mysql html passing value on one page

im curious, if the value of <p class="myclass"></p> assign by jquery using $('.myclass').text('txtvalue'); can be fetch using PHP script? example. like i want to fetch the assign value of jquery without using jquery post, ajax to pass value in PHP because im do this with only one page.
here my code:
<p class='myclass'></p>
<?php
$a = strip_tags("<p>","<p class='myclass'></p>");
echo $a;
// the result is 100; but its dismase like im printing "<p class='myclass'></p>"; i im trying to do is to get exactly the value of "<p class='myclass'></p>". because the value of that, i will use to query in mysql id.
//it is impossible to me to do this?...
?>
<script>
$('.myclass').text('100');
</script>
No, this cannot be done.
PHP runs server-side and generates your HTML, including any Javascripts with jquery in it. When it's done, Javascript gets to work, client-side. The only way to get something back into PHP is to send it to the server by posting it, ajax, or redirection.

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.

Javascript isn't running in php function

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.

PHP tags in javascript tags

I'm trying to assign value of JavaScript variable to php session. Please see my code below -
<script type="text/javascript">
<?php $_SESSION['historyClass'] = "";?>
var myClass = $(this).attr("class");
if(myClass == 'trigger'){
<?php $_SESSION['historyClass'] = "trigger"; ?>
}
else{
<?php $_SESSION['historyClass'] = "trigger active"; ?>
}
alert('<?php echo $_SESSION['historyClass']; ?>')
</script>
In myClass variable, i'm getting 2 values
1) trigger
2) trigger active
Whatever the value I'll get, I want to store it in php session. But when I alert the session value it is always giving me "trigger active". It means it is always going to else part. I have checked the 'if' condition by alerting in it, the control is going properly in "If" and "else" part.
What is the problem? Am I doing something wrong?
Thanks in advance.
PHP is processed first, and then javascript is executed, so it's impossible to directly assign values to php variables.
instead you could send http requests from javascript (Ajax) to php scripts to save your data.
This won't work. PHP is executed on the server, and JS on the client. That means that the php is running before the JS is parsed. I suggest you look at Ajax if you want to run PHP from javascript (specifically the jQuery library and its ".get()" function).
What's happening is that the PHP is parsed, and doesn't see any JS, so it runs as normal, and sets the session to trigger, and then trigger active. Then javascript comes along on the client, and the client doesn't see any PHP code,so doesn't run it.
this wont work. the php code runs on serverside, js - on client. so php is executed before the page is shown to the user. it means that first is executed $_SESSION['historyClass'] = "trigger"; than $_SESSION['historyClass'] = "trigger active"; and obviously the value will be trigger active
yes you are doing something wrong.
javascript runs on client side and php on server side. so your code runs first on server side and then on the client.
thats why you can't do it like you did. a common way to transfer javascript data to a php script is, writing the value to a hidden field, so that it gets submitted to the server.
just create a hidden field and fill it with a value from javascript
<script type="text/javascript">
function valToPHP(name,value){
document.getElementById(name).value = value;
}
</script>
...
</head>
<body>
<input type="hidden" id="myField" name="myField" value="" />
...
you can then read it in your php script like that
$_GET["myField"] or $_POST["myField"]
this depends on your method of the form

Calling a JavaScript function from PHP

I have a php script that is a bit of a mess and after a form entry, I need to get an address, and display it on a google map. The html and php is crammed into the same script so I essentially need to call the JavaScript as the PHP is happening. Is there a way to do this?
Thanks,
Alex
You can POST your from to a different frame (or iframe), so your page would not reload. The response of your PHP file which comes back to that frame can contain JavaScript code, which will be executed. Something like:
echo('<script type="text/javascript"> alert("Executed on client side"); </script>');
No, PHP executed by the server and returns the full response to the browser. JavaScript in the page is then executed by the client.
You can't call Javascript functions from PHP. You can set the Javascript to run when the page loads instead.
What you want is something like this:
<script type="text/javascript"></script>
var userAddress = "<?php echo $_POST['address']; ?>";
doSomethingWithAddress(userAddress);
</script>
If that code is on the page which you are POSTing the address to, it would take the address from the user, and write it into a javascript tag. The PHP will get executed first on the server, before building the HTML document. This new document has the variable available to the javascript.
I don't know how you would go about doing that, but this seems like a good place to start looking:
http://code.google.com/intl/en/

Categories