arma
arma

Reputation: 4124

Is it possible to post values to external javascript file?

Hay,

I was wondering if it's possible to execute php code in external javascript file? For example i need to read user language and such.

Upvotes: 2

Views: 242

Answers (4)

Derek Adair
Derek Adair

Reputation: 21935

It's not clear exactly what you want from your question...

But you can execute PHP/server-side languages via AJAX. If you are not already I would recommend using a javascript framework. (i prefer jQuery myself).

Here is a basic example of an AJAX call using jQuery.

PHP

//yourscript.php
echo "ajax is awesome!";

JavaScript

$.ajax({
  url: 'yourScript.php',
  success: function(response){
    //alerts "ajax is awesome!"
    alert(response);
  }
});

If you check out some of the documentation on the jQuery ajax method it should give you a good idea of what ajax is used for. It essentially works backwards from how your question is phrased. An ajax call is initiated on the server side, and the php script responds. So in essence it accomplishes the same goal.

The real trick is how you are going to format your data. I use XML but it seems that JSON is a bit more popular (not a fact at all... just my impression). But either way you are able to pass complex sets of data that greatly ease the data parsing process.

Upvotes: 0

niggles
niggles

Reputation: 1034

You can call:

<script src="myfile.js.php" type="text/javascript">

and execute PHP in that file.

Upvotes: 0

alex
alex

Reputation: 490433

You can run PHP in a js file if you add the PHP handler to text/javscript.

<Files *.js>
AddType application/x-httpd-php .js
</Files> 

Be sure to have your JavaScript file identify itself with...

 header('Content-Type: text/javascript');

But...

As you can imagine, every JavaScript file running through PHP isn't a good idea.

So what I would and do use, is this...

<script type="text/javascript">
var lang = '<?php echo $lang; ?>';

</script>
<script type="text/javascript" src="/js/common.js"></script>

Then inside of common.js, you can access lang variable.

Upvotes: 1

dkamins
dkamins

Reputation: 21918

You can run PHP to generate a JavaScript file, which the user's browser would then run.

But PHP runs on the server-side. There's no way to send PHP to a user to run.

Upvotes: 0

Related Questions