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.
Related
Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am fairly new to php so this functionality stumps me, I'll give you a picture for context. layout of application for reference image
So I can query my data base and set each bit of data to an individual variable (maybe not the best way for this situation?)
But I don't know how to $_post that data (in variable form... :) probably bad idea, and I'll have to set the data as variables where ever I work with the formulas and only send information over ajax) back to the displayed page (note: I don't want my page to ever have to refresh)
And I foresee another problem, and its due to lack of knowledge and google failing to answer my questions, how can I have php Run my algorithms and keep the original data in the page every time my users change one field on the page, I want them to all run on the server and not in browser so I'm planing on having ajax send all the data including the changed data to a php file every time they change something and have it reset the information on the page after it runs its formulas. i have been studying $_post and get and request ect. and not been able to mentally layout how the transmission of data would be the most efficient and easiest to work with.
Sorry for the ramble, I hope for some constructive criticism, solutions and explanations to a newbie at php and thank you for any and all help.
HI it works like this in jQuery
$.post('url', {input}, function(data){
});
The javascript will make a web request, same as if you put url in the browser, right ( if it's $.get that is, obviously we cant send post data using the browser url bar, however you could go to the page just without the post data ). Now because it's AJAX anything returned goes into data. It's asynchronous, which means your JS wont wait for the request, for example if you put
$.post('url', {input}, function(data){
});
alert(data.result);
It wont work, for 2 reasons, one is scope ( data is a function input parameter not accessible outside the function ). The other is that the alert will fire before the post completes, even though it is written after the $.post request. Because of this, you have to use the data in the call back function.
Now on PHP side where ever that url is it gets ran just like you went there normally. Essentially there is no difference to the server its AJAX or a browser request. It's just like submitting a form. The interesting things you can do is return your data as JSON. by using the application JSON header and by using json_encode() in PHP. This is essentially JavaScript String Object notation. ( not sure if I remember that right ) but that is what it is.
There is no magic in the request. Most people don't really understand that anything the server returns is only text. Be it a PDF file, a JPG, a webpage, anything its only text. JSON allows you to keep the structure of your data, such as an array. It's a special format of text that JavaScript understands as object and arrays.
I explained this to one of my Junior Developers the other day. That if you set the correct headers you can generate CSS files with PHP, images etc. Because it's all just Text. The web is very simple. You only have get and post for requests and text as a response. That's it for the most part.
Anyway,
Right, so now in PHP ( for a quick example )
header('Content-Type: application/json');
$a = array('one'=>1);
echo json_encode( $a );
With json_encode() it becomes ( this is the response sent back from the server )
'{one:1}'
And in JS on the client side ( inside the $.post callback ) its
data.one;
We can take this data in the callback then you can just use some basic jQuery to replace the values of inputs or content of HTML tags with your returned data.
$('#input').val(data);
$('#htmlElement').text(data); // or data.one - whatever you had in php array keys.
Make sense? Above, we take a PHP array use json_encode(), to make it a JSON string, and then (with the correct header ) we can access that normally in JS using its dot syntax. Remember what I said above about only returning text from the sever, this is why we have to convert it to a JSON string. The dot in JS is like the -> in PHP. You could also use data['one'] which is even more like PHP, but that is technically not the correct way if you know what one is.
The process flow is also simple, just like we only have post get, and text. We only can make requests from the client and responses from the server. So it always goes
Client Request -> Sever Response -> Client receives response.
We cannot for example call the Client from the sever.
Sever Call-> Client receives
This doesn't work without things like NODE.js or a socket server.
For reference ( about json responses )
Returning JSON from a PHP Script
This is an odd situation and my current thought is that it doesn't work this way, but I need to some other eyes on this.
A different website I don't have control over has a form with a hidden field in it. The form action is a POST and to send it to a url on my website and I need to be able to get the value of that hidden field using javascript.
As a GET that would be included in the url and I think I would just be parsing that apart. But since it's a POST being sent to me I'm not entirely sure how to get the value of that hidden field out.
Is this doable? If so, where should I be looking to do it?
Thank you!
If your server that is receiving the sended form data uses PHP, you can get all form values using:
<?php
print_r($_POST);
?>
If the page in your server is a static html page, then you cannot get the POST data. Or you can, but then you have to make html pages to be executed as php pages (not recommended however).
You talk about that you need this value be accessible by javascript. Simply do something like:
<script>
<?php
echo 'var input_field_value="'.htmlspecialchars($_POST['name_of_input_field']).'";';
?>
</script>
The question doesn't provide information what server software is used, so I assume that is PHP.
EDIT: after Saturnix's comment I added a call to htmlspecialchars() to make it safe to execute in javascript.
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.
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
?>