using javascript in PHP [duplicate] - php

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
i have this php and js code:
<script type="text/javascript">
function StartScript(script)
{
<?php require("StartScript.php"); ?>
}
</script>
Start
How can i get the "script" from the javascript function onto the end of the php file?
for example rather than:
<?php require("StartScript.php"); ?>
to have:
<?php require("StartScript.php?script=scriptname"); ?>

The full excerpt (provided that StartScript.php at the same level of current page, otherwise add absolute path):
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function StartScript(script) {
jQuery.getScript('StartScript.php?script=' + escape(script));
}
</script>
This will call StartScript.php with the parameter script. StartScript.php will generate the JavaScript code which will be executed in the client browser.
Reference: http://api.jquery.com/jQuery.getScript/

It's impossible to write server-side code (PHP) with a client-side code (Javascript). This will not work unless you use something like Ajax.

Maybe I misunderstood your question but this seems pretty easy...I would include all the js in the php file so the html side of things would have only....
<?
$script = "Page1";
include("StartScript.php");
?>
and the php would be...
<? if ($script == "Page1"){ ?>
function StartScript(script)
{
alert("IN");
}
</script>
<? } ?>

The problem is that you're mixing up the client (JS) and the server (PHP). PHP is executed on the server and produces some HTML which gets sent to the browser ("the client"). Browsers cannot run PHP because it's a server-side language.
You should evaluate what the desired interaction is between the client and the server here. For example, if you just need to execute some PHP to pass data to JavaScript, you can build up a JavaScript object:
<script type="text/javascript">
<?php // include script that gives you back some data, e.g.: ?>
<?php $somePhpData = array('red', 'yellow', 'blue'); ?>
<?php $jsonData = json_encode($somePhpData); ?>
var dataFromPhpScript = <?php echo $jsonData; ?>
// do something with the data
</script>
Otherwise, if you really need JavaScript to trigger a PHP script running, you're essentially doing AJAX. You'll likely want some sort of REST API. The idea is that you expose a URL from PHP that the JavaScript can call:
<script type="text/javascript">
jQuery(document).ready(function() {
function startScript(scriptName, success) {
$.get('/path/StartScript.php?script-name=' + scriptName)
.done(success)
.fail(fail);
}
startScript('name-of-php-script', function(data) {
// trigger some JavaScript that relies on the output of the PHP script
});
});
</script>

Related

How to call function from jquery to php?

PHP:
$product_code = $_GET['product_code'];
$countryCode = getCountryCode();
<script src="js/register_script.js" type="text/javascript"></script>
Jquery:
function getCountryCode() {
countryCode = qrcode_getinfo(qrCode1,"mfg_c_a_code",0)
return countryCode;
}
I want to get my country code from the jquery to perform some validation task, however, i wasn't able to retrieve the country code. Any idea what should i do for it to work? please note that the library is already been called. (I had read up on examples but dont really understand how it works..)
It is not possible to directly call PHP function from JavaScript and vice versa. Part of the reason for this is that as #Pekka indicated JS runs clientside (in your browser) while PHP runs server-side (on your server).
It is however possible to use AJAX for your purposes:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function getCountryCode()
{
countryCode = qrcode_getinfo(qrCode1,"mfg_c_a_code",0)
return countryCode;
}
function doAjax(){
var countryCode = getCountryCode();
$.ajax({
'url' : '<THE_URL_TO_YOUR_PHP>?countryCode=' + countryCode,
'method' : 'GET',
'success' : function(data){
console.log(data);
// do your handling here
},
'error' : function(data){
console.log(error);
// this function is executed on an HTTP error
}
});
}
</script>
PHP
This is your php file that would do your validation. In principle it is a different file than the file that outputs the html as shown above.
$countrycode = $_GET['countryCode'];
# handle countrycode
echo "<What you want to return to JS>";
Edit
On the additional question of how to get session variables to js.
Would I navigate to your page in my browser, the following would happen: If I requested a file with an .php extension, the PHP processer gets run on it. This processer identifies all code between the tags <?php and ?> as PHP, and thus runs all this code. If it encounters an echo statement, it echo's out the specific value at the location of the php-block.
After PHP is done processing, the page is served (given) to your browser, where it will be interpreted as a combination of HTML/javascript/... Javascript interprets everything between the tags <script> and </script> as javascript.
So, what if we where to make a request to index.php?par=val on your server, and index.php looks like
<script type="text/javascript">
function doStuff(){
var param = <?php echo json_encode($_GET['par']);?>;
}
</script>
(the json_encode function ensures that the variable is in proper json format. Of course you can change the `$_GET['par']; to be whatever you would like.)
Remember, PHP only cares about whats between the <?php and ?> tags, so this would output:
<script type="text/javascript">
function doStuff(){
var param = "val";
}
</script>
You will need to edit this to match your requirements of course, but this is the basics of passing parameters from PHP to client-side (JS)

In jquery use php variable to execute the jquery

I am loading some jquery within a Wordpress page, the jquery works as I want it to but now I need to have that jquery only fire if a php variable exists.
In php I would just do:
if( $foo ) {
do this;
}
In Wordpress I am enqueuing the a file bla.js that contains this:
jQuery(document).ready(function($){
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
});
I am confused as how to add the php check if $foo exits. There seems to be several approaches but all I end up doing is producing an unexpected token error.
Javascript exists only on the clients computer in their browser; PHP only exists on the server, far away from their browser, so your JS can't just use the PHP variable. You can do it two ways:
Only include the JS if the variable is true:
<?php if ($foo) : ?>
jQuery(document).ready(function($){
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
});
<?php endif; ?>
Or set a JS variable from the PHP variable:
jQuery(document).ready(function($){
var foo = <?php echo $foo; ?>;
if (foo) {
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
}
});
Note that in either case, the page is "created" on the server with PHP. Once it's displayed in the browser, you can't use PHP variables. If you need to call another PHP page to check some additional stuff, look at Ajax.
So php is a server side language, javascript is a front end language. So basically php runs then javascript runs...so basically if $foo exists output the jquery you want to run and it will display on the front end. If it doesn't exists output different jquery that you want to run....here is as simple example...
<!-- JS -->
var foo = <?php echo $foo; ?>
if (foo == 'test'){
} else {
}
// More PHP based
if ($foo == "test"){ ?>
javascript function() <!-- Note how I closed php -->
<? } else { ?>
javascript function2()
<? } ?>
PHP and jQuery (which is a framework written in Javascript) run in entirely different scopes.
PHP is executed on the server and the generated result is the HTML page (which will likely include some Javascript code).
That resulting page is then delivered from the server to the browser and when the browser renders it, the jQuery/Javascript will execute.
The key part is that the PHP code is actually generating the HTML and Javascript code.
So, if you'd like to run some jQuery code only if a PHP variable exists:
<?php
if( $foo ) {
?>
<script type="text/javascript"> /* Some jQuery stuff here */ </script>
<?php
} else {
?>
As an example, I generate this text in the "else" condition.
<?php
}
?>
If $foo is true then PHP will generate this HTML:
<script type="text/javascript"> /* Some jQuery stuff here */ </script>
otherwise, PHP will generate this:
As an example, I generate this text in the "else" condition.
Keep in mind that once PHP has delivered the page to the browser, it is no longer running, and the generated result will be "permanent". At that point, the page is loaded into the browser DOM (document object model) and the DOM can only be changed through Javascript.
Put the Javascript inside the PHP conditional.
<script type="text/javascript>
...
<?php
if ($foo) : ?>
jQuery(document).ready(function($){
$('#someID.some-class > a').append('<div class="caption"></div>');
$(".caption").text("Add this text");
});
<?php endif ?>
...
</script>
Usually i just create a hidden input like so:
<input type='hidden' id='some_id' value='the_value'>
Note that I don't add the name attribute so it doesn't get posted (if it happens to be in a form).
Then you can access it with jQuery by its id.
if($('#some_id').val() == what_you_want)
{
do_something();
}

I need to declare a PHP function after called it from javascript [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I've a problem with disposition of function declaration using a mix of javascript and php language.
<script>
//some JS code
<?php getVideos() ?>
//some JS code
</script>
<?php function getVideos()
{
//some code
}
?>
The problem is that the function is declared in another part of the html code, and the page won't work until i don't move it before the JS code.
There is a solution without need to move the php code?
EDIT: i wanna precise that my html file is with a php extension (index.php) and i can access to php variables along the entire document normally
You have to call function using ajax call. Post to your php file using jQuery.post and in server use die to return data. PHP run at server-side
Example:
In javascript:
<script>
$(document).ready(function()
{
$.post(this.uri,{},function(){});
});
</script>
In php:
<?php
if (isset($_POST))
{
getVideos();
die("1");
}
function getVideos()
{
//some code
}
?>
i don't think you can call a php function from javascript. Javascript cannot run a php code, since PHP codes will run before the webpage loads, and the javascript runs after webpage loads.
Anyway, you can still use ajax to run an external PHP file like this:
$.ajax({
url:'php/ajax_post.
type: 'post',
data: {function: "any_function"}
success: function(data)
{
window.alert(data);
}
});
In your PHP file, add an if statement, like this:
if(isset($_POST['function']) && $_POST['function']=="any_function")
{
//Run your function
}
This will run your requested function, and alert the result.
You can use PHP's include() function to "import" functions from other PHP files.

about pass php variable to javascript [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I got a html5 upload script from
http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/
can i pass php variable to js?
in this html5 upload script
the script.js call the post_file.php to upload file
in post_file.php
$rand = time();
i set the rand is the filename
for example uploaded filename: 1331956640.jpg
can i pass this $rand to script.js?
because i can't print the result in php, only can print something in script.js
this is the html5 upload script download link from tutorialzine
enter link description here
sorry my english not good, thank
<script>
var my_javascript_var = <?php echo $rand; ?>
</script>
or
<input id="my_rand_value" type="hidden" value="<?php echo $rand;?>" />
in js do so
var my_javascript_var = $("#my_rand_value").val():
It's not actually about "passing" a variable from PHP to JavaScript.
Remember that PHP is a server-side scripting language, and JavaScript resides on a client's browser.
So, you could actually... write directly any javascript you wish from your PHP script.
Let's say, you've got a $a variable... then you could simply enter it in your javascript code like this :
<script type='text/javascript'>
var a = <?php echo $a; ?>
</script>
However :
If what you mean is to actually use the $a var while the page has loaded, or retrieve the result in some way, WITHOUT reloading, then what you probably need is Ajax.
To use AJAX, I would either suggest :
the jQuery load method
using some ready-made AJAX object
You can do this
<script>
var javascriptvar = <?=$rand ?>
</script>
You dont need to ....
<script>
var rand = new Date().getTime();
</script>
this uses only JavaScript to get the same result
You can do it this way:
<script language="javascript" type="text/javascript" src="your.js"></script>
...
<img src="your_button.gif" />

php in javascript?

i need to have some php code inside javascript
<script ...>
<?php
echo " ... ";
?>
</script>
but this doesnt work. how can u implement php inside javascript that is in a own file javascript.php?
That doesn't do what you probably think it does. It'll work, but the PHP gets run once, when the page is loaded, not every time the JavaScript function is called.
Just for clarification, this is what will happen
index.php
<script type="text/javascript">
<?php echo "alert('hello!');"; ?>
</script>
output html in browser
<script type="text/javascript">
alert('hello!');
</script>
If that is what you want to do, then you can output all the javascript you like. What you cannot do is execute PHP code in the user's browser.
your can use php to dynamically generate javascript code, but you cannot execute php client side. If you need to execute php you will need to postback or use AJAX
There seems to be a good bit of misunderstanding of the question... Here is what you want to do to generate JS from PHP on the server:
file javascript.js.php
<?php
header('Content-Type: text/javascript');
?>
// javascript code here
function PrintTime()
{
alert("The time is " + <?php echo json_encode(time()); ?>);
}
Now, include it on the HTML page using normal script tags:
<script type="text/javascript" src="/url/to/javascript.js.php"></script>
The server will process the PHP file, and return javascript from it.
You can't run PHP inside a javascript file. Primarily because PHP runs server side and is processed before the client is sent any actual http info. JavaScript is processed by the browser on the client side and is sent as text.
It looks like you want to pass some kind of dynamic info to the JavaScript. You can do this by passing a variable like this:
<?php $variable="its me"; ?>
<script>
alert('<?php print($variable)?>')
</script>
The output passed to the client is:
<script>
alert('its me')
</script>
What are you trying to accomplish and maybe we can help you come up with a better solution?

Categories