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.
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.
Is it possible to store form data using an external PHP file that does the processing and then use echo values from the PHP result to update an HTML element on the same page without using javascript,jquery, or ajax? Do I have to return html data like this: Your post is <?php echo htmlspecialchars($_POST["email"]); ?>.<br> If so how do I do that and still keep all the other elements on the page the same way they are currently formatted. Related to this, how do I load the HTML page with some elements already bound to values extracted from the database using an external PHP file?
What is best practice for doing this kind of thing. The objective is to allow a user to input text in a textbox, click submit to have the text stored in a database, and then at the same time update an element that displays the latest sumbmission, kind of like a forum post. I know you can use ajax, javascript, jquery to do this kind of thing on the client side, but I have seen html pages with the <?php echo htmlspecialchars($_POST["email"]); ?> type syntax and wanted to experiment with that for simplicity.
"Is it possible to store form data using an external PHP file that does the processing and then use echo values from the PHP result to update an HTML element on the same page without using javascript,jquery, or ajax?"
Answer: No, you must send the data to the same page, ( action="" )
Then include the processing file at the top/beginning of the script. Please feel free to ask for more help.
IF YOU WANT TO SEND THE DATA TO THE DATABASE AND WANT TO DISPLAY THE DATA: Just retrieve the data from your database on the page you want to display it on.
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
?>
I am working on a basic HTML page that requires the user to send details to a script located on a third-party website. What I require is for the user to fill out a form on my web page, and have that information submitted to another third-party form.
I do not wish to return anything to the user, other than whether the submission was successful or not. I also do not want the user to have to go to this third-party site to submit using their form.
It was suggested by the website itself to use an iframe and hold its form on your page, but I was wondering what other, preferably better methods are available to me. It'd be nice if there were some form of jQuery/js code I could use to do such a thing.
It'd be nice if there were some form
of jQuery/js code I could use to do
such a thing.
One way is to use jQuery's $.ajax or $.post methods like this:
$.ajax({
url: url,
success: function(data) {
alert('succeeded');
}
});
Maybe you could try cURL with CURLOPT_POST and CURLOPT_POSTFIELDS?
well it depends if you have control over the other website as well. as in you are able to access the code.
If you are you can use JSONP to pass the values and get a response, but to do it you will have to assign a callback that is sent and then formatted at the front of a JSON object for it to work (they do this for security).
The other option is to use a php ob_start() function. (Note: this will only work if the form you are trying to submit these values to allow $_GET to be used to proccess the form)
ob_start();
include('http://wwww.anotherwebsite.com?key1=value1&key2=value2&key3=value3');
$returnString = ob_get_contents();
ob_end_clean();
So then from here $returnString is the result, which you can basically search (strpos() to see if true is how I would do it) in php to find key words to see if it was successful or not or what ever you need to check for.
But again, this only works if the form on the remote server uses $_GET and not $_POST (or allows both through globals).
I know this is a php solution, but a warning is that for security purposes, there are serious restrictions on what javascript can do cross server.. the best javascript way to do cross server is JSONP, which jQuery does support so you might want to look into that.. but as I mentioned, for it to work you need to have a callback be able to be sent back with the response, and the response needs to be in a jsonp object format.. (basically you either need to 1. have the other server have a jsonp api for you to use or you have control over the other server's server side files to make the changes needed).
Do you want like that? It's simple form submitting to another website. But, I can't check whether it's successfully submitted or not.
<form action="http://www.another.com">
<input name="myInput" type="text">
<input type="submit" value="Submit">
</form>