This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
I'm trying to include JavaScript variables into PHP code as PHP variables, but I'm having problems doing so. When a button is clicked, the following function is called:
<script type="text/javascript">
function addTraining(leve, name, date)
{
var level_var = document.getElementById(leve);
var training_name_var = document.getElementById(name);
var training_date_var = document.getElementById(date);
<?php
$result = "INSERT INTO training(level, school_name, training_date) VALUES('level_var', 'training_name_var', 'training_date_var')" or die("Query not possible.");
?>
</script>
Is it possible?
PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.
What happens in a nutshell is this:
You click a link in your browser on your computer under your desk
The browser creates an HTTP request and sends it to a server on the Internet
The server checks if he can handle the request
If the request is for a PHP page, the PHP interpreter is started
The PHP interpreter will run all PHP code in the page you requested
The PHP interpreter will NOT run any JS code, because it has no clue about it
The server will send the page assembled by the interpreter back to your browser
Your browser will render the page and show it to you
JavaScript is executed on your computer
In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.
The only way to do what you are looking to do is either:
do a redirect to a PHP script or
do an AJAX call to a PHP script
with the values you want to be insert into the database.
<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php $abc = "<script>document.write(jvalue)</script>"?>
</script>
<?php echo 'php_'.$abc;?>
You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data.
-don
PHP runs on the server. It outputs some text (usually). This is then parsed by the client.
During and after the parsing on the client, JavaScript runs. At this stage it is too late for the PHP script to do anything.
If you want to get anything back to PHP you need to make a new HTTP request and include the data in it (either in the query string (GET data) or message body (POST data).
You can do this by:
Setting location (GET only)
Submitting a form (with the FormElement.submit() method)
Using the XMLHttpRequest object (the technique commonly known as Ajax). Various libraries do some of the heavy lifting for you here, e.g. YUI or jQuery.
Which ever option you choose, the PHP is essentially the same. Read from $_GET or $_POST, run your database code, then return some data to the client.
I had the same problem a few weeks ago like yours; but I invented a brilliant solution for exchanging variables between PHP and JavaScript. It worked for me well:
Create a hidden form on a HTML page
Create a Textbox or Textarea in that hidden form
After all of your code written in the script, store the final value of your variable in that textbox
Use $_REQUEST['textbox name'] line in your PHP to gain access to value of your JavaScript variable.
I hope this trick works for you.
You can take all values like this:
$abc = "<script>document.getElementByID('yourid').value</script>";
You can do what you want, but not like that. What you need to do is make an AJAX request from JavaScript back to the server where a separate PHP script can do the database operation.
Related
I have an idea for "using", or "referencing" PHP variables in Javascript. This would apply to a webpage that will send an email. A simplified example is shown below. Note: this is called via AJAX, so it is not the case that I am trying to call a PHP variable from a script that has already been executed.
The javascript will include a "$midSection" string in the body of the email to be sent, and then send the entire body to a PHP script. The PHP script will store this String, create and assign a value to $fmidSection, and send the body string in an email. If it works, the resulting email would include the main body sent from the client side, with an inserted "midSection" in the middle of the email (perhaps, depending on the person's name and info stored in a database).
It seems to me that this should work, given my understanding of PHP. However, it also seems to me that this will open a window for attack similar to an SQL injection (where' perhaps, we can trick the script to assign a different value to $midSection, for example). Has anyone taken this approach, and if so, can you validate whether this will work, and open up any security holes?
Thank you.
EDIT: The application is for a mailing list, not a contact form. I have an admin panel which allows me to send emails to the mailing list, and I am thinking that this is a good way to include variables from the PHP in a similar way that I would on the PHP script, by putting the $var in the string itself. I understand how passing variables from JS to PHP works, I want JS to reference a PHP variable, essentially. I am not using this for validation purposes, I am using this for an easy way to insert information, rather than doing string parsing manually. The variable will be created and stored server side on a script that I have created.
Also, the JAVASCRIPT will be performing an AJAX call on the PHP script. Therefore, the Javascript will be executed first. I'm essentially sending an email template to the PHP, where the PHP will loop through the email list and add information dynamically, such as first name, last name, etc. Instead of doing string processing, I'm thinking of sending "Hello, $firstName $lastName....." essentially, in the hopes that the PHP script will insert the variable information.
From the comments above I can see what you're trying to do, but it won't work.
Consider the following code:
$(document).ready(function() {
$.ajax({
url: 'ajax.php',
data: {'name' : 'andy'},
method: "POST",
}).done(function (data) {
console.log(data);
});
});
This is ajax.php:
<?php
echo $_POST['name'];
?>
All you're doing in the javascript is making a POST request to ajax.php. It's able to give you the output "andy" in your console because you're passing this data string - not a reference to anything. So far, so simple.
Now imagine if you change data: in the jquery to the following:
data: {'name' : '$var'}
In your console you would get a string "$var".
Even if you had this in ajax.php:
<?php
$var = 'foo';
echo $_POST['name'];
?>
You will never get the output "foo".
This is because PHP and javascript are completely separate. So if you pass $var, it's just going to treat it as a string. There's no way of asking javascript to mean a PHP variable or some reference. You have to pass the data itself.
In the case of your application, what you'd typically do is pass something in the ajax request that PHP can refer to (like the primary key ID for a particular record). PHP would then generate all of the required content and send it back to the browser. If you need to do things with a template, str_replace is your friend.
I want JS to reference a PHP variable
Impossible.
They are different programs running on different computers. By the time the JS starts running, the PHP program will have finished and its variables will no longer exist.
The closest you could come would be to store the data somewhere (e.g. a database) with an identifier. Then send that identifier to JS. Then, if you want to get the data in JS, use Ajax to request it.
I am using a php file to create a page that allows me to manage mysql entries. The page fetches the entries from the database and lists them which I have working fine. I am trying to add a button that allows me to "accept" an entry which changes its status value to 1 from 0.
It is working fine, except when I refresh the page, it automatically is executing the javascript function which should be an onclick event. Am I missing something incredibly simple or something. I have been looking at this for 2 days now and have rewritten it several times without success as well as extensive googling to find an answer.
My button:
<input type='submit' name='acceptbut' id='acceptbut' value='Accept'></input>
I am thinking the problem has something to do with either the location.reload or something else.
<script type="text/javascript">
function setAccept() {
<?php
$query = "UPDATE regiments SET status=1 WHERE memberID=$mid";
mysqli_query($connect, $query);
?>
location.reload(true);
}
document.getElementById('acceptbut').onclick = setAccept;
</script>
I have also tried messing with an inline onclick but it is not working either
My confusion is why is the function running if im not actually calling it.
Your PHP executes on the server every time the page is requested. The fact that the PHP is located inside a Javascript function is not relevant.
The PHP server parses the file, finds any PHP in it, runs the PHP on the server, then sends the result to the browser.
If you want to execute some PHP only when a Javascript function is executed in the browser, then you have to make an Ajax call from the Javascript to your server and have the Ajax call request a PHP page that can then run the desired PHP and return a result (if necessary) back to the browser's Javascript.
Keep in mind that in your setup, PHP executes on the server, then the resulting page (without any PHP in it) is sent to the browser. The browser then executes appropriate Javascript in the web page as events occur. The only way to execute code on the server at that point is to make an Ajax call to the server.
You are confusing Client and Server side. Look at this:
function javascriptFunction()
{
<?php echo date("Y"); ?>
return true;
}
The above block of code gets executed in PHP. How? Each line of the above code is treated as a sequence of characters and is sent to the cout (standard output). The small snippet inside the <?php...?> gets executed by PHP and if there are any output, it also is sent to standard output. Only when the characters are sent from server to the client side (browser), the browser starts interpreting them. Which results in a code inside <script type='text/javascript'>..</script> to be interpreted as a JS snippet. Now, bear in mind: EVERY PHP CODE GETS EXECUTED BEFORE THERE ANY THING AS JS, CSS or HTML. PHP SEES EVERYTHING AS EITHER String, Integer/Double or Boolean (etc.).
What you should do?
Learn what is AJAX, and try to learn its best practices. You'll amaze at its excellence.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
My web app sends data from PHP to javascript as a JSON string.
To avoid writing the string as text in the rendered file, the architecture I thought of using is setting data on cookies with PHP, then reading with JS.
It works well so far, but I was thinking if maybe users have cookies disabled, then it won't work.
So I have two questions, one, if users do disable cookies much or if it's ok to use cookies as my data-keeping method.. is there a study about cookie-disabling behaviour? I googled but couldn't find any recend data.
Second, is there another way to send data from PHP (I'm using laravel) to javascript without having to write it out on the file? (I can't make another ajax request to the server and then load the data, as it would kill user interaction, the data must return with the first request)
Thanks
First almost no one disables cookies. If you disable cookies, half of the websites you visit won't work anymore.
If you want to "pass data to javascript" without writing to a file (usually you never write to a file to pass data to javascript anyway) you can simply do:
<script>
var mydata = '<?=$mydata?>'; # take care of escaping single quote of course
</script>
In this way you don't make an additional AJAX request.
If you are using Laravel's blade then:
<script>
var mydata = '{!! $mydata !!}'; # take care of escaping single quote of course
</script>
As pointed out in comments, if you are passing json then simply remove the quote:
<script>
var mydata = {!! $mydata !!};
</script>
This question already has answers here:
How to get JavaScript function data into a PHP variable
(5 answers)
Closed 8 years ago.
<script type="text/javascript">
var a=10;
</script>
<?php echo $value; ?>
I want to get the value of variable "a" to PHP variable "$value" without ajax request.
javascript is variable value you can't store it to php variable the reason behind is php is a server site language and javascript is only a client language both are independent.
for this you can use ajax to send the ajax request to a page with the javascript variable value and there page you can use php code to get the value of that variable like $_GET['a'].
may this help you!
PHP runs on the server side, while JavaScript runs in the client's browser. This means that the PHP code gets executed before the JavaScript, so it isn't possible to directly pass a variable from JavaScript to PHP.
You should look into either sending it via a GET or POST request or, if you need to do it without a page reload, using AJAX. This tutorial might be helpful:
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
The Javascript is executing on the browser and the PHP is executing on the server so you will have to pass the value to the server somehow. Putting it in the querystring is one easy way, for example:
var url = 'http://mysite/file.php?value=' + escape(a);
It depends on what you are doing of course, but if you are making ajax calls or just posting form values, you need to send the value in the server requests.
You could do this in one of two ways, either by performing a POST or GET request, or by using a cookie. Both would require a the page to reload however because PHP runs before the page is loaded.
Client goes to example.com/form.html where a html POST form is displayed
Client fills the form with specific information and submit it to example.com/form.html
When example.com/form.html receives the POST request redirects the Client on example.com/redirected.html
Is possible to retrieve the variables that the client filled and POSTed to example.com/form using javascript ? The javaScript being deployed on example.com/redirected.html only . I presume that can be some "back" controls iframes and ajax involved but I couldn't find a reliable solution yet.
The operation will take place on the same domain so no cross domain issue is involved
Nope, I don't think this is possible.
You have to either
Store the posted value in a cookie
Store the posted value in a session variable on server side
Add the posted value as a GET parameter to the new URL
Use GET to post the original form, and painfully extract the posted value from document.referer on the new page
With HTML5, use localstorage. (The answer describes how to store object in localstorage- you could store an object of your form fields in there).
But you have to store the data on posting with js at example.com/form.html and then can get it on example.com/redirected.html. Without js at form.html, this is not possible with this method.
This works if you plan to use html5 and do not store too much data in it, iirc it has a limit of 5-10mb depending on the browser.
I don't think there is a way to do this by using plain html. With some server-side language (like PHP) it can be done with no problem.
I have been in a similar situation before, and the way I managed to give the data to JS is by including the data in a tag while preparing the output using PHP.
Assuming the redirected to php script receives the POST data from the script it's being redirected in. I would include this in the php code:
<?php
echo '<script type="text/javascript">';
echo 'var postData = '.json_encode($_POST).';';
echo '</script>'
?>
This will have the javascript know what the POST values contained.
To access the values from js:
//assuming you need the value for $_POST['foo']
var foo = postData.foo;
// or if json is encoded as just an associative array
var foo = postData['foo'];
If the POST data is not being passed to the redirected to script (haven't checked if this happens automatically), you could write the $_POST data in a $_SESSION variable, in the first php script:
<?php
$_SESSION['postdata']=$_POST;
?>
and then get it back from SESSION from the redirected to script.
<?php
$postdata = $_SESSION['postdata']; //use this to create the inline script in the html
unset($_SESSION['postdata']; //empty this from the SESSION variables
?>