php variable inside js code [duplicate] - php

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I need a php variable inside js code.
Why this doens't work?
index.php
<?php
$h = 966;
?>
index.js
var b = <?php echo $h;?>;
Error:
Uncaught SyntaxError: Unexpected token <

You can't run php inside a JavaScript (.js) file.
Take a look at the question shared by Ed Cottrell in the comment on your post for more information, but basically, PHP is a server language, whereas JavaScript is a client one—when your computer loads index.js, it sees the php script, but has no idea what to do with it.
A straightforward solution (though not the best) would be to output a <script> tag containing your variable inside from your php file— and then access it from your JavaScript file.

When your browser requests the Js file, the web server typically simply sends it the file in the response without processing it like a php file. It doesn't know you have php code in it. It does the same (just sends it to the requesting browser) for images, text files, etc.
You can try doing that in your php view/template/script (I would wrap the output in single quotes). Something like:
<script>var b = '<?php echo $h;?>';</script>
You could also make a JavaScript file with a php extension: index.js.php, and include this instead of index.js. You'll need to set some headers in the top of that file to let the browser know it's getting JavaScript:
header("content-type: application/javascript");
There is some slightly more advanced stuff you can do as well: use an htaccess file to parse certain requests (like for that Js file) using php, or using an asynchronous request (Ajax) to pull the value of 'b' from the server, but it looks like your doing something a bit more simple.

Related

Access a PHP array element by using a JavaScript variable as index

The code looks like this:
PHP file
<?php
...
$arrayName = ['ArrayValue_0', ..., 'ArrayValue_n'];
...
php?>
JavaScript
$('.elementClass').each(function(index, id) {
$(id).html('<?php echo $arrayName[index - 1]?>');
});
But you can't just insert a JavaScript variable like that into php tags so index is never received.
I know this can be done via AJAX but is there any other way? Thanks in advance.
Additional info:
I've been told to do this in PHP so there's no posibility of switching the array to a JS file.
You can define arrayName variable in JS and initialize it with the value from the server:
var arrayName = <?php echo json_encode($arrayName); ?>;
$(".elementClass").each(function(index, id) {
$(id).html(arrayName[index-1]);
});
What you're trying to do will not work. For example this:
$(id).html('<?php echo $arrayName[index - 1]?>');
The above will never, ever work, because PHP is run on a server, not on your user's browser.
What you need to do is send the variable somehow to the server. You have a plethora of options:
Use a form and read a $_POST variable
Append it to a URL and read a $_GET variable
Use AJAX and asynchronously send that variable to the server
Return the whole array from PHP to your Javascript code
etc. etc.
Remember, PHP runs on the server, which renders the page, which then in turn is read by your browser where you run Javascript. You can't paste PHP code into the page and expect it to be parsed by PHP!
You need to get back to the server if you wish to get info from it (PhP runs on the server), so either you create a javascript variable on-the-fly when loading the page with the complete content of your PhP array , either you use ajax to get back to the server without refreshing the whole page.

passing variable from javascript to php [duplicate]

This question already has answers here:
How can I pass variables from JavaScript to PHP?
(2 answers)
Closed 9 years ago.
I want to pass a variable from a function in JavaScript to PHP that is also inside the JavaScript function.
For Example:
myfunction('qwerty');
<script>
myfunctionjs(x)
{
<?php echo $x?>
}
</script>
note: code above is just a sample
Your code sample, while it expresses what you want quite clearly, should also show how impossible it is.
PHP is a server-side language whereas javascript is a client-side language. The only way for javascript to "talk" to PHP is to submit a request to the server. You can do this either through a standard HTTP-GET request or a POST request (through a form submission, or more commonly via Ajax).
The PHP isn't inside the JavaScript function. The PHP code is executed on the server.
When the Javascript is executed, the code looks like this:
myfunction('qwerty');
<script>
myfunctionjs(x)
{
alert(x); //or whatever $x is
}
</script>
If you want to pass 'x' to a PHP script, you'll have to make an AJAX request.
You can't have javascript telling PHP to do something inline. JavaScript runs client side, while PHP runs server side.
Instead, you need to have your javascript send the data to your server, and you'll have PHP do something when receiving that second request.
If you are using jQuery, have a look at the ajax method for example on how to send data: http://api.jquery.com/jQuery.ajax/
Passing variable from javascript to php right away is not possible. You will have to use AJAX for this. You have to understand the difference between server-side scripting and client-side scripting.
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-difference-between-server-side-and-client-side-programming
Read the above link and it will give you a full understanding of the process. if you have any issues let me know.
Read more

make a php variable equal a javascript output [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to pass value from javascript to php file
would something like this work?
<script>
var a;
a = 5;
<?php
$b = ?>a;
</script>
I am wondering if I can have javascript parsed by the client-side and have the output information be picked up by PHP as a variable that can be used elsewhere.
You could actually have your JS parsed with PHP if you:
configured your web server to parse .js files, or,
gave your JS file a .php extension and configured the response header with the appropriate content type
e.g.:
<?php header('Content-type: text/javascript');?>
You'd also need to have a PHP include or at least the relevant code to populate the required variables.
Note it's best practice to not use PHP short-tags - your php.ini should be configured to not allow them. i.e., do this:
<?php echo %b %>
instead of this:
<? echo %b %>
that way you cant. The file is first parsed by PHP on the server and then sent to the client-side, where the javascript is parsed.
Without ajax or other kind of requests, data is not sent back to the server.
no, you can't
<script>
var a;
a = 5;
<?php
$b = ?>a;
</script>
on the contrary, you can do this.
<script>
var a;
a = <?echo $b?>; // $b will be the variable of a in javascript (client side)
</script>

PHP variable inside a js file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to transfer an array between PHP and Javascript
How do I put the value of a PHP variable inside a Javascript variable?
This is what I have now in a js file:
test=<?php echo $country; ?>;
Don't forget to properly escape your variables before passing them to JavaScript. Use json_encode() for this, as it escapes and encodes your values in a way suitable for using with JavaScript:
test=<?php echo json_encode($country) ?>;
Never simply send the variable un-encoded, as it might break things, or, worse, if the value comes from untrusted sources, compromise your security.
Also, rename your file to .php instead of .js if you want to be able to insert dynamic PHP code inside it.
Remember that the browser doesn't care what the serverside (PHP) code was. It only cares what the rendered code (Javascript and HTML) looks like. So your PHP
test=<?php echo $country; ?>;
will come out something like this, presuming $country is a string:
test=USA
That is valid Javascript, but it doesn't set test to have the value USA. It sets test to the value of the variable USA, which is almost certainly undefined. You need to use quotation marks to make a Javascript string literal:
test="<?php echo $country; ?>";
This will be rendered as so:
test="USA";
and will do what you expect.
I see now that you've mentioned that the file is a js file. I presumed above that it was a standard PHP-with-HTML file. As it is, everything above is still valid. However, serving a PHP script as Javascript is only slightly tricky.
First, name your file filename.php (or whatever other name you want). This is by far the easiest way to get the webserver to know to parse it with PHP. Then use the following instruction to let the browser know that the file is Javascript content:
header('Content-Type', 'text/javascript');
Put that at the very top of your file, before any content is sent to the browser. You can then include PHP variables as you like.
First of all, to make sure that you understand this, because I see a lot of beginners stumbling over the difference between server side scripting and client side scripting, javascript is a client side scripting language, while PHP is server side. If you understand this, you can basically skip this paragraph. When the user requests a page, such as mysite.com/whatever.php, the request gets sent to the server. Because the user requests the PHP file, the server knows that it should parse the file before sending it to the user. When parsing a file, the server starts n HTML mode, which means that all the text it reads is going directly to the user. From the moment php encounters a or the end of the file. When the end of the file is reached, it sends the output to the user. This output may contain script tags in it's HTML. These peaces of javascript will be executed when they are red together with the HTML by the browser.
However, an external javascript file, doesn't need to have the .js extension, just like css. Therefore, you can also make a php file that outputs js, and do as one of the previous answers suggested, so to put this js code in a .php file:
var somevar = <?php echo $var; ?>;
as you can see, after the equals sign in the javascript, the php variable $var 's value will be printed. This value will therefore be assigned to the js variable called somevar when the output is red by the browser.
put your JS code inside a .php file and try like this:
<html>
<script language="JavaScript">
function echoSession(num)
{
window.document.newForm.mybox.value=num;
<?PHP echo $VAR ?>
}
</script>
</html>
The point is your file should be a PHP file to make server to parse it as php. if it is a .js file it will not work
In order for you to be able to use markup within a Javascript file, you must either:
1) Modify your .htaccess file to include *.js as a valid extension for files to be processed through the PHP Engine. (Google around for this)
2) Change the Javascript file extension from *.js to *.php.
3) Declare variables which are set through PHP within the main PHP/HTML file, rather than the external Javascript file.
There is the json_encode (http://php.net/manual/de/function.json-encode.php) method to print php variables for javascript.
test = <?php echo json_encode($value) ?>
Works even if $value is an array, but in your case if it's a string, too.
This is a problem I face often when dealing with js vs php. As my JS applications become more complex there is more and more a desire to keep all my JS in library files and keep my php as clean as possible. One solution I have started using is to do the following:
js file:
myNamespace.bootstrap = function( payload ){
...
// internally boot up all the modules that need
// the data, passing it where relavent
module.load( payload );
}
php file:
...
<script type="text/javascript">
myNamespace.bootstrap(<?= json_encode($payload_object); ?>);
</script>
</body>
This gives you one data injection point for all your scripts with one line of js in your actual php. Should allow you to easy manage data dependencies in your javascript since you can namespace them in php.

How to implement php tags in javascript for url's or anything

I was wondering how i could achieve using <?php?> in javascript for url's? There's a certain route you have to go, Anyone know?
the normal way for example:
$fetchContent = $('#div').load('website/members #content');
What i'm trying to do:
$fetchContent = $('#grav').load('<?php?> #poppu');
Yep, thats wrong as hell lol, but i'm sure someone knows
I would also like to know how to tie php with javascript, but thats probably a whole new topic
You said it right :)
Yep, thats wrong as hell lol, but i'm
sure someone knows
Anyway, from your php script, output the url as a javascript code anywhere in the script before the javascript used for ajax call, e.g.
<?php
echo '<script language="javascript"> var g_ajax_url = "'. $the_url . '";</script>';
?>
and in your javascript, use it this way
$fetchContent = $('#grav').load(g_ajax_url + ' #poppu');
What it simply does is define g_ajax_url as a global variable with the proper php value, and you can use that variable in your js as you use other variables.
To tie php with js directly, try looking into xmlrpc topic.
If javascript is in .php file you can use <?php echo $url ?> and if the file is .js you can't use <?php ?>
It is not clear to me what you are trying to achieve. I assume you are using the jQuery load() function, if yes, you should state so.
You can't load php during javascript execution because the php has already been processes and rendered as HTML and sent back to the client. As PHP is processes on the server it is logical that you cannot run it on the client side.
You could of course send an AJAX request to the server that runs a certain php page and you will be able to use the response as you please.
you can't necessarily "tie" them together because they operate in two different spectrums of processing, php being processed on the server, and javascript being processed in the browser.
You can however render javascript within a php file.
if your javascript is included within a <script> tag within your php page your example should work should actually work. The php would render the urls into the script before it is sent to the browser.
if you are wanting to load external javascript files with php inlcuded urls, you will need to set the proper headers and include the php file just as you would a normal .js file.
good article on this topic HERE
You cannot execute <?php ?> inside JavaScript, but inside PHP you can declare a global variable as:
var x = '<?php echo x;?>';
or, if it's an array, store it as JSON:
var x = <?php json_encode(x); ?>
then access the JavaScript variables inside the external JavaScript.

Categories