I am trying to read the post request parameters from my HTML. I can read the get request parameters using the following code in JavaScript.
$wnd.location.search
But it does not work for post request. Can anyone tell me how to read the post request parameter values in my HTML using JavaScript?
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:
var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;
Then just access the JavaScript variable in the normal way.
Note there is no guarantee any given data or kind of data will be posted unless you check - all input fields are suggestions, not guarantees.
JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.
Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.
Use sessionStorage!
$(function(){
$('form').submit{
document.sessionStorage["form-data"] = $('this').serialize();
document.location.href = 'another-page.html';
}
});
At another-page.html:
var formData = document.sessionStorage["form-data"];
Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Why not use localStorage or any other way to set the value that you
would like to pass?
That way you have access to it from anywhere!
By anywhere I mean within the given domain/context
If you're working with a Java / REST API, a workaround is easy. In the JSP page you can do the following:
<%
String action = request.getParameter("action");
String postData = request.getParameter("dataInput");
%>
<script>
var doAction = "<% out.print(action); %>";
var postData = "<% out.print(postData); %>";
window.alert(doAction + " " + postData);
</script>
You can read the post request parameter with jQuery-PostCapture(#ssut/jQuery-PostCapture).
PostCapture plugin is consisted of some tricks.
When you are click the submit button, the onsubmit event will be dispatched.
At the time, PostCapture will be serialize form data and save to html5 localStorage(if available) or cookie storage.
I have a simple code to make it:
In your index.php :
<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>
In your main.js :
let my_first_post_param = $("#first_post_data").val();
So when you will include main.js in index.php (<script type="text/javascript" src="./main.js"></script>) you could get the value of your hidden input which contains your post data.
POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js
<script>
<?php
if($_POST) { // Check to make sure params have been sent via POST
foreach($_POST as $field => $value) { // Go through each POST param and output as JavaScript variable
$val = json_encode($value); // Escape value
$vars .= "var $field = $val;\n";
}
echo "<script>\n$vars</script>\n";
}
?>
</script>
Or use it to put them in an dictionary that a function could retrieve:
<script>
<?php
if($_POST) {
$vars = array();
foreach($_POST as $field => $value) {
array_push($vars,"$field:".json_encode($value)); // Push to $vars array so we can just implode() it, escape value
}
echo "<script>var post = {".implode(", ",$vars)."}</script>\n"; // Implode array, javascript will interpret as dictionary
}
?>
</script>
Then in JavaScript:
var myText = post['text'];
// Or use a function instead if you want to do stuff to it first
function Post(variable) {
// do stuff to variable before returning...
var thisVar = post[variable];
return thisVar;
}
This is just an example and shouldn't be used for any sensitive data like a password, etc. The POST method exists for a reason; to send data securely to the backend, so that would defeat the purpose.
But if you just need a bunch of non-sensitive form data to go to your next page without /page?blah=value&bleh=value&blahbleh=value in your url, this would make for a cleaner url and your JavaScript can immediately interact with your POST data.
You can 'json_encode' to first encode your post variables via PHP.
Then create a JS object (array) from the JSON encoded post variables.
Then use a JavaScript loop to manipulate those variables... Like - in this example below - to populate an HTML form form:
<script>
<?php $post_vars_json_encode = json_encode($this->input->post()); ?>
// SET POST VALUES OBJECT/ARRAY
var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
console.log(post_value_Arr);
// POPULATE FIELDS BASED ON POST VALUES
for(var key in post_value_Arr){// Loop post variables array
if(document.getElementById(key)){// Field Exists
console.log("found post_value_Arr key form field = "+key);
document.getElementById(key).value = post_value_Arr[key];
}
}
</script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
One option is to set a cookie in PHP.
For example: a cookie named invalid with the value of $invalid expiring in 1 day:
setcookie('invalid', $invalid, time() + 60 * 60 * 24);
Then read it back out in JS (using the JS Cookie plugin):
var invalid = Cookies.get('invalid');
if(invalid !== undefined) {
Cookies.remove('invalid');
}
You can now access the value from the invalid variable in JavaScript.
It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language.
So you can do something like this: (Code by Casey Chu: https://stackoverflow.com/a/4310087/5698805)
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
// use post['blah'], etc.
});
}
}
And therefrom use post['key'] = newVal; etc...
POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.
SITE A: has a form submit to an external URL (site B) using POST
SITE B: will receive the visitor but with only GET variables
$(function(){
$('form').sumbit{
$('this').serialize();
}
});
In jQuery, the above code would give you the URL string with POST parameters in the URL.
It's not impossible to extract the POST parameters.
To use jQuery, you need to include the jQuery library. Use the following for that:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
We can collect the form params submitted using POST with using serialize concept.
Try this:
$('form').serialize();
Just enclose it alert, it displays all the parameters including hidden.
<head><script>var xxx = ${params.xxx}</script></head>
Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.
Related
I did a searching in the similar questions, but I did not find a solution for my problem.
I would like to pass part of the URL from the index page to another function that is called if the user is autenticated. I can print the url variable in the next page, before the authentication. But since, the URL changes when the user is autenticated, I am getting a blank. How do I keep the value in the other page after the URL change?
In my index.php I call a js function that gey the course number when the page loads:
<body onload="myFunction()">
The myFunction is js code in data.js file that get part of the URL:
const url = location.href;
const urlCourse=url.split('=')[1];
document.getElementById("demo").innerHTML = urlCourse.toString(8);
}
In the callCourses.php, I have:
const course='<p id=demo></p>';
echo course; // It works!
if ($GLOBALS['authenticated'] ) { //here the URL will change because the user is now authenticated
echo course; // Error does not get the course number.
If the url is changed after authentication and if you have no access to changing that url, you will need to store that variable in one of the following places:
On the Server
Cookies
Session Cookies
// Before authentication
$_SESSION['courseNumber'] = getCourseNumberFromURL();
...
// In authenticated
$courseNumber = $_SESSION['courseNumber'];
Web Browser
Local Storage
Session Storage
// Before authentication
localStorage.set('courseNumber', getCourseNumberFromURL())
...
// After Authentication
const courseNumber = localStorage.get('courseNumber')
Edit - Expanded Answer
So, I think some clarification is needed here. PHP and JavaScript can't actually communicate with each other in the way I think you are understanding. You can use PHP to generate dynamic scripts, but once the html has been sent to the user, PHP can no longer interact with or manipulate that page. This means you can't access a JavaScript variable via PHP.
If we need to send JavaScript data over to our server, we perform one of two actions:
Create a custom form and send it to a PHP endpoint.
Make an XMLHttpRequest.
For 2, I recommend looking into fetch, which is highly supported in all modern browsers. (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
With that explanation out of the way, here is what I recommend doing for your case:
<?php
// Whatever you had before
// Store the courseNumber if we haven't already
if (!$_SESSION['courseNumber']) {
$_SESSION['courseNumber'] = $_GET['courseNumber'];
}
// More junk
// Now, let's check if authenticated:
if ($GLOBALS['authenticated'] ) {
// We are! Let's echo the courseNumber
echo $_SESSION['courseNumber'];
// Or, if you need to do it in a tag, try this:
// This directly inserts the data as the page is being generated to send by PHP
echo "<p id='demo'>".$_SESSION['courseNumber']."</p>";
// Or do this if you have to have the JavaScript insert the value for some reason
echo "<p id='demo'></p>";
echo "<script>document.querySelector('#demo').innerText = '" . $_SESSION['courseNumber'] . "'</script>";
}
?>
I want to to pass a js variable to another page ..what to do..code is given bellow..
Code
`
$('#disInfo').on('click','tr',function(){
var obj = $(this);
var result= obj.find('td').eq(1).html();
window.location.href='http://localhost/Trying/search_cus.php';
});
`
I want to send the value of result variable with page link and how to receive the value in another page
You could pass it via an url parameter. If result contains html or characters that cannot be used in an url then you need to encode it first.
$('#disInfo').on('click','tr',function(){
var obj = $(this);
var result = encodeURIComponent( obj.find('td').eq(1).html() );
window.location.href='http://localhost/Trying/search_cus.php?result=' + result;
});
On the target page you can get url parameters via window.location.search ... there's plenty of examples on stackoverflow on how to do that.
NOTE: be aware that the server will also get the request for ?result=whatever. If the server side code processes this (eg PHP: $_GET['result']) you must ensure it sanitizes the value to prevent malicious code injection.
BTW, other ways of passing data is via cookies, sessionStorage, localStorage, etc.
My question is, what are the best practices of passing the data from my server side to my client side?
For example, I have a cartId on my server side which I need to pass on to the client side.
How do I best do that? Right now it's done via the main layout:
<script type='text/javascript'>
(function() {
if (window.cart) {
cart.id = <?php echo Yii::app()->getUser()->getCartId() ?>;
}
})();
</script>
However, that seems like a bad thing to do. Will appreciate any feedback.
In php file write this YII code
YII Code
Yii::app()->clientScript->registerScript("cartid",Yii::app()->getUser()->getCartId());
SCRIPT
(function() {
if (window.cart) {
cart.id = cartid;
}
})();
Use AJAX to get the data you need from the server.
Echo the data into the page somewhere, and use JavaScript to get the
information from the DOM.
Echo the data directly to JavaScript.
With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:
get-data.php
/* Do some operation here, like talk to the database, the file-session
* The world beyond, limbo, the city of shimmers, and Canada.
*
* AJAX generally uses strings, but you can output JSON, HTML and XML as well.
* It all depends on the Content-type header that you send with your AJAX
* request. */
echo json_encode(42); //In the end, you need to echo the result.
//All data should be json_encoded.
index.php (or whatever the actual page is named like)
<script>
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest(); //New request object
oReq.onload = function() {
//This is where you handle what to do with the response.
//The actual data is found on this.responseText
alert(this.responseText); //Will alert: 42
};
oReq.open("get", "get-data.php", true);
// ^ Don't block the rest of the execution.
// Don't wait until the request finishes to
// continue.
oReq.send();
</script>
The above combination of the two files will alert 42 when the file finishes loading.
It's best practice to not write PHP in your JavaScript for one. Instead, take the data from PHP and pass it to json_encode (http://php.net/json_encode) and echo it out. You can read that straight into a variable if you like but it would be better to use ajax so it's asynchronous thus better page load.
The best option is to make AJAX calls to a PHP page which performs some action, and returns data. Once that PHP has all the data it needs to return, I echo the data (as an array) in JSON format.
Eg:
info.php
die (
json_encode(
array(
"id" => "27"
"name" => "rogin",
)
)
);
Then, you can use javascript to fetch the data into a json object.
JS
$.getJSON(
'info.php?',
function(jsonObject) {
alert(jsonObject.name);
});
If you just want to prevent javascript syntax highlighting error, quoting would do just fine.
(function() {
var the_id = +'<?php echo Yii::app()->getUser()->getCartId() ?>';
// ^ + to convert back to integer
if (window.cart) {
cart.id = the_id;
}
})();
Or if you like you could add it to an element:
<div id='foo' style='display:none'><?php echo Yii::app()->getUser()->getCartId() ?></div>
Then parse it later
<script>
(function() {
var the_id = +($('#foo').html()); // or parseInt
// or JSON.parse if its a JSON
if (window.cart) {
cart.id = the_id;
}
})();
</script>
I am using AJAX to send inputs from a webpage to a PHP file to then be entered into a database. Here is my JavaScript file:
var pageLoaded = function () {
var submitButton = document.getElementById("submit");
if (submitButton) {
submitButton.addEventListener("click", submit, true);
}
};
var submit = function () {
var xhr, changeListener;
var form = document.getElementById('item_form');
var inputs = form.getElementsByTagName('input');
// create a request object
xhr = new XMLHttpRequest();
// initialise a request, specifying the HTTP method
// to be used and the URL to be connected to.
xhr.open("POST", "../php/add_item.php", true);
console.log(inputs[0].value); // debugging
// Sends the inputs to the add_item.php file
xhr.send(inputs);
};
window.onload = pageLoaded;
Here I am trying to send inputs from a form to a PHP file called add_item.php located "../php/add_item.php" in my file system.
I am pretty sure this code works and sends the inputs to the PHP file in an array.
My question is, how do I then use $_REQUEST within that file to be able to use the inputs within the array to send to a database? Or, what is the best way of doing this?
The xhr.send() method only accepts a string. If you want to send an array you have to flatten it into a string before posting. You can do this easily using the JSON.stringify() method in javascript, then use json_decode() function in PHP on receiving it.
Also for PHP to receive the data properly in the $_POST[] variable (or $_REQUEST if you must, but not recommended) you need to set a name for the POST variable and URL-encode your JSON text like this:
var json_array = JSON.stringify(inputs);
xhr.send('myJSONData=' + encodeURIComponent(json_array));
On the PHP side you shouldn't need to use urldecode() because the server stack expects to receive POSTed name-value pairs url-encoded. But you will need to use json_decode on the posted variable to get the array back, e.g.:
php_array = json_decode($_POST["myJSONData"]);
You will see other methods to do this, including setting the xhr POST content-type header to JSON, but in my experience this is the path of least resistance.
Also note whilst it is possible to send an "array" of objects in an HTML form like this:
<input type="text" name="myArray[]" value="val1">
<input type="text" name="myArray[]" value="val2">
<input type="text" name="myArray[]" value="val3">
<input type="text" name="myArray[]" value="val4">
which will result in an array being available within PHP in the variable $_POST["myArray"], there is no easy equivalent of this using the XHR object (AJAX method). JSON.stringify() is IMO the easiest way to go.
The variables inside the $_REQUEST are stored as an array. To access them you would do something similar to this:
echo $_REQUEST['input_1'];
To view all the variables (in a nice format) sent by the JS you could use this code:
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
You can't do it in the way you are doing it. You send "input" array which is incorrect. You should prepare array of input values. Morover, I'd recommend you to use JQuery.
$(function (){
$("#submit").click(function (){
//the way to get input values and names
var arr = [];
$("input").each(function (index,value){});
arr.push([$(value).attr('name'), $(value).val()];
});
// it can be replaced also via serialize() funciton
//ajax
$.post( "../php/add_item.php", arr)
.done(function( data ) {
//data has been send response is in data object
});
});
});
In PHP you can get these values via $_POST. $_REQUEST is not needed here because you use POST method. For example if you have input
<input name="xxx" value="test">
to print value of this input in PHP you need use this code
echo $_POST['xxx'];
If you don't want to use JQuery then you still need loop through inputs and prepare proper array to send it via XHR.
I need to read the config file setting in javascript. I wrote the below code in my aspx page. It's returning empty.
<script type="text/javascript" language="javascript">
function GetFileLocationFromConfig(keyP) {
var FileLocationL = '<%=ConfigurationManager.AppSettings[' + keyP+ '] %>';
return FileLocationL;
}
</script>
You are confusing server side with client side.
The page is processed on the server and <% ... %> stuff is replaced with the result of computation serv side, then the generated page is sent to the client.
Part of the page computed can be Javascript code, but you must understand and discern what computation is done in Javascript on the client and what computation is instead done on the server by ASP.
In you specific case a solution would be writing ASP code that generates a Javascript "dictionary" object for example producing something like
var settings = {};
settings["!key1"] = "value1";
settings["!key2"] = "value2";
settings["!key3"] = "value3";
then the lookup function can be implemented in Javascript as
function getSettingsValue(key) {
return settings["!" + key];
}
Be careful in knowing and understading exactly what you are sending to the client side by inspecting the generated page. For example sending passwords or other security related infos to the client would be a bad idea.
You cannot pass javascript variable to PHP, ASP variables / methods.
You can do like this:
<?php
$arr = implode(",", ConfigurationManager.AppSettings);
?>
var s = '<?php echo $arr; ?>';
s = s.split(',');
var FileLocationL = s[ keyP ];