sending javascript variable value to php within the same page [duplicate] - php

This question already has answers here:
How to get JavaScript variable value in PHP
(10 answers)
Closed 9 years ago.
I just want to know if sending value of a javascript to php is possible.
here is the simple code of what i am trying to say.
<script language="javascript" >
var id = "data"
</script>
<?php
$getthevalueofid = var id;
?>
thanks!

Not the way your code sample is structured, no. PHP is a server-side language and Javascript is a client-side language. PHP is out of scope by the time any client-side script executes.
If you need to pass an object from the browser to your server you can use XMLHttpRequest (commonly referred to as AJAX).

To send a Javascript variable back to PHP, you need to do an AJAX request:
<script language="javascript" >
xmlhttp.open("GET","getvalue.php?id="+id,true);
xmlhttp.send();
</script>
And in getvalue.php you'd have:
<?php
$getthevalueofid = $_GET['id'];
?>

No way to do this. Use Ajax to pass javascript variable to php

Related

using javascript in PHP [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 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>

Send PHP variable to JavaScript function [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 have a php file that generates a variable and I would like the variable to be put into a JavaScript function which is called by onclick on the main page. Is this possible to send from PHP to JavaScript?
You can do the following:
<script type='text/javascript'>
document.body.onclick(function(){
var myVariable = <?php echo(json_encode($myVariable)); ?>;
};
</script>
Just write:
<script>
var my_variable_name = <?php echo(json_encode($php_string)); ?>;
</script>
Now it's available as a JavaScript variable by the name of my_variable_name at any point below the above code.
Your JavaScript would have to be defined within a PHP-parsed file.
For example, in index.php you could place
<?php
$time = time();
?>
<script>
document.write(<?php echo $time; ?>);
</script>
If I understand you correctly, you should be able to do something along the lines of the following:
function clicked() {
var someVariable="<?php echo $phpVariable; ?>";
}
A great option is to use jQuery/AJAX. Look at these examples and try them out on your server. In this example, in FILE1.php, note that it is passing a blank value. You can pass a value if you wish, which might look something like this (assuming javascript vars called username and password:
data: 'username='+username+'&password='+password,
In the FILE2.php example, you would retrieve those values like this:
$uname = $_POST['username'];
$pword = $_POST['password'];
Then do your MySQL lookup and return the values thus:
echo 'You are logged in';
This would deliver the message You are logged in to the success function in FILE1.php, and the message string would be stored in the variable called "data". Therefore, the alert(data); line in the success function would alert that message. Of course, you can echo anything that you like, even large amounts of HTML, such as entire table structures.
Here is another good example to review.
The approach is to create your form, and then use jQuery to detect the button press and submit the data to a secondary PHP file via AJAX. The above examples show how to do that.
The secondary PHP file receives the variables (if any are sent) and returns a response (whatever you choose to send). That response then appears in the Success: section of your AJAX call as "data" (in these examples).
The jQuery/AJAX code is javascript, so you have two options: you can place it within <script type="text/javascript"></script> tags within your main PHP document, or you can <?php include "my_javascript_stuff.js"; ?> at the bottom of your PHP document. If you are using jQuery, don't forget to include the jQuery library as in the examples given.
In your case, it sounds like you can pretty much mirror the first example I suggested, sending no data and receiving the response in the AJAX success function. Whatever you need to do with that data, though, you must do inside the success function. Seems a bit weird at first, but it works.
You can pass PHP values to JavaScript. The PHP will execute server side so the value will be calculated and then you can echo it to the HTML containing the javascript. The javascript will then execute in the clients browser with the value PHP calculated server-side.
<script type="text/javascript">
// Do something in JavaScript
var x = <?php echo $calculatedValue; ?>;
// etc..
</script>

Dynamically passing PHP variables [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'm trying to accomplish a JavaScript form that will load the result from a PHP request on an external website, after a text box is filled out.
Right now, I have
<script type="text/javascript"/>
function sendrequest() {
document.location="myphpsite.com/submit.php?tb="+document.getElementById("tb").value;
}
</script>
<form>
<input type="text" id="tb" onChange="sendrequest()" />
</form>
This code is going nowhere, because from my current knowledge, you can only load PHP variables on startup, by using "script src=... ", and by having the php page return some javascript code.
What I'm looking for is a way to request/receive php variables dynamically, something that would work like this:
<script type="text/javascript">
function getdata() {
return document.get("myphpsite.com/submit.php?tb=hi");
}
</script>
In other words, is there a function that dynamically "reads" a website, and returns the raw text?
http://w3schools.com/ajax/default.asp
You should go read this and then read it again, AJAX is what you need.
best example with PHP and AJAX -
http://www.w3schools.com/php/php_ajax_database.asp

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 constants in a javascript file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pass a PHP string to a Javascript variable (and escape newlines)
I'm working on a project and it's already done, but it needs one more midification and its applying language constants in javascript files.
consider we include a javascript file and in that we have something like this
alert("YOU Have VOTED BEFORE");
easy like that , the script will alert that text
but what if we need to alert a language constant of it :
alert("<?php echo _VOTED_BEFORE?>");
this will be worked only if echo the script like inline of my php codes ...
but, how can we read and include php constants or $vars for a outside JavaScript file ???
For a cleaner structure, I think the best way is to set all the data you get from PHP in one place, i.e. in the HTML you serve via PHP:
<script>
var MyNameSpace = {
config:
something: "<?php echo _VOTED_BEFORE ?>"
}
}
</script>
In the JavaScript file you include afterwards, you can access the value via MyNameSpace.config.something.
This makes it also easier to reuse the message.
There is a way of doing this using a query string in the script path
See my answer here
How to pass variable from php template to javascript
Unfortunately this will break the cache for your js file so weight your options first
<script type="text/javascript" src="script.js?flag=<?php echo _VOTED_BEFORE?>"></script>
for the sake of not writing too much code refer to the link to see how to retrieve the value
Actually, what you had was close to being proper.
<?php
// Valid constant names
define("VOTED_BEFORE", "false");
?>
<script type="text/javascript">
alert("<?php echo VOTED_BEFORE;?>");
</script>
If it's not a PHP file, you cannot include PHP echo functions in it. I suggest that if you want to use a PHP variable in your external js files then declare it as a global in your PHP
file before you reference the external js.
<script type="text/javascript">
var globalvar = '<?php echo _VOTED_BEFORE ?>' ;
</script>
<script type="text/javascript" src="externalfile.js"></script>
Though it's not always a good idea to clutter the global namespace.
You can use cookies to save these constants and read them in via JavaScript or you will have to use AJAX

Categories