How to write a _REQUEST loop? - javascript

Here's what I'm doing now in php
$layout_type = $_REQUEST['layout_type'];
$aside_location = $_REQUEST['aside_location'];
$aside_style = $_REQUEST['aside_style'];
$nav_bg = $_REQUEST['nav_bg'];
$nav_bg_hover = $_REQUEST['nav_bg_hover'];
$nav_text_color = $_REQUEST['nav_text_color'];
There has to be a function that writes it for me with the same name?
Here's my ajax call
function generate_clicked()
{
var formData = $("#form").serialize();
$.ajax({
url : "process.php",
type: "POST",
data : formData,
}).done(function ( data ) {
try{
$('#preview').val(data.css);
}
catch(err)
{
console.log(err);
}
document.getElementById("my_iframe").src = data.live_preview_html_page;
});
}

This should work:
foreach ($_REQUEST as $Key => $Value) {
${$Key} = $Value;
}
However I advise against it from severe security implications. To make it secure, I'd recommend first checking the value against an array (white-listing it):
// Complete yourself...
$ValidValues= array("layout_type", "aside_location");
foreach ($_REQUEST as $Key => $Value) {
if (in_array($Key, $ValidValues)) {
${$Key} = $Value;
}
else {
throw new Exception("Security violation. Requesting non-existing variable " . $Key);
}
}
Although you ought to ask yourself why you need this, since your request makes no sense. Arrays are for storing this kind of data, not many individual variables, and you already have that in your $_REQUEST. So please, see down there in your code if you can just use the data straight forward, or provide some more code/context so we can help you further with your problem.

Current versions of PHP provide the extract() function to do what you want, although it's not advised to use it on $_REQUEST since any user can alter your form client-side and submit unexpected variables to your PHP script.
If you choose to use this function, it's strongly recommended that you use the EXTR_SKIP flag or provide a prefix to prevent existing variables from being unexpectedly altered.
extract($_REQUEST, EXTR_SKIP);
// the EXTR_SKIP flag will prevent variables from being overwritten
// or:
extract($_REQUEST, EXTR_PREFIX_ALL, 'prefix_');
// prepend all your new variable names for safety
That said, the safest way by far is to explicitly set each variable as you're doing now. That way, you know exactly what variables are being set when, and security risks are minimized.

Related

What is wrong with the way I am handling these variables in PHP?

Originally I wanted to use node.js, but after an entire day of frustration, I switched to using jquery and mySQL. The logins seem to be working, but something is wrong in the way it is handling variables. All I want to do is update the database with two things: score and name. Here is the code I modded for my project in PHP:
<?php
$db = "myDatabaseNameIsCorrect";//Your database name
$dbu = "soIsMyUsername";//Your database username
$dbp = "AndMyPassword";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
if(isset($_GET['name']) && isset($_GET['this.score'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$name = strip_tags(mysql_real_escape_string($_GET['name']));
$score = strip_tags(mysql_real_escape_string($_GET['this.score']));
$sql = mysql_query("INSERT INTO `$db`.`scores` (`id`,`name`,`score`) VALUES ('','$name','$score');");
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your score was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your score. Please try again later.';
}
}else{
echo 'Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
And here is the JS! that runs the PHP:
let gameoverScene = new Phaser.Scene('GameOver');
gameoverScene.create = function(){
this.laughSound=this.sound.add('laughSound')
this.gameW = this.sys.game.config.width;
this.gameH = this.sys.game.config.height;
this.goToTitle=function(){
var name = prompt('Enter your name');
jQuery.ajax({
type: "POST",
url: 'savescores.php?name=' +name +'&score=' + this.score,
dataType: 'text',
data: {functionname: 'add', arguments: [name, this.score]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
this.scene.start('Title')
};
I also tried changing the data type and that didn't work, but I'm not ruling it out yet as a problem.
Here are links to the project and the database:
www.igglepud.com/DeerDefender/Testing
www.igglepud.com/DeerDefender/Testing/getscores.php
This is the error I get:
gameover.js:20 Uncaught TypeError: Cannot use 'in' operator to search for 'error' in
Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.
at Object.success (gameover.js:20)
at fire (jquery.js:3268)
at Object.fireWith [as resolveWith] (jquery.js:3398)
at done (jquery.js:9305)
at XMLHttpRequest.<anonymous> (jquery.js:9548)
So, the error you're getting is because, in the JavaScript, obj (or the parameter in obj's position) is a string, not an array.
You can see some examples here of how you can properly check for and catch errors.
Edit:
So, in regards to your question about the score variable.
It's important to note that there are 2 types of variables at play here.
The first one is PHP GET variables. PHP GET variables are set via the following format:
var=value
You can set these variables by calling a PHP script like this:
script.php?var1=value1&var2=value2&var3=value3 // etc...
You can access them like this:
echo $_GET["var1"];
echo $_GET["var2"];
echo $_GET["var3"];
Which produces the result:
value1
value2
value3
The second variable at play is a JavaScript variable. Those can only be accessed in JavaScript. a JavaScript variable means nothing in PHP.
So, let's examine what you're doing from the JavaScript:
url: 'savescores.php?name=' +name +'&score=' + this.score,
For the purpose of explaining let's say name = Chipster, and this.score = 123.
What this code will do is try to open the following file:
savescores.php?name=Chipster&score=123
Remembering that PHP GET variables are set by the format script.php?var1=value1&var2=value2&var3=value3 // etc... we can see that there are 2 GET variables available from the PHP script called name and score. Thus, to access score from PHP you need to do it like this:
echo $_GET["score"];
This will output 123 in our example.
This may not solve your problem, but one issue I see with your code is calling strip_tags (or another function that alters the string) after it has already been quoted for insertion with mysql_real_escape_string may defeat the purpose of mysql_real_escape_string. It should be the very last function called on data before it's inserted.
Also, if score is an integer string, intval serves just as well as mysql_real_escape_string for sanitizing integers for insertion.
EDIT: You're also checking for GET variables in the PHP when the submission method used in the jQuery is POST. Try looking at $_POST instead of $_GET on the PHP side. You don't need to put variables in a query string if you're putting them in the request body via POST either.

Failing to send to $_POST but $_SESSION says something else

I do not know what is happening with my code, when I run it, sometimes SESSION says there is an array is stored and sometimes it doesn't. I am using a debugger to check the session. When I use isset($_POST), the return value is always false. I am using ajax to pass an array to php.
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
Javascript:
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
window.location.href = 'example.php';
var jExample = JSON.stringify(array);
$.ajax({
data:{'jExam':jExample},
type: 'POST',
dataType: 'json',
url: 'example.php'
});
});
EDIT:
Figured out why the arrays are stored into SESSION, once I click on the button that opens the other page, and then type in the page before in the url, the array is stored into the SESSION. Don't know why. Still can't figure out why ajax is not sending to post.
EDIT 2:
I created a file that handles the request called handle.php. So the php script on top is added into handle.php instead of the webpage. But I am getting a "Parse error: syntax error, unexpected 'if' (T_IF)". The code is still the same on top.
handle.php:
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
EDIT 3:
I am using the ajax to pass an array to php in order to store it into session, in order to use the array in another page. The problem is that the array is not passing into $_POST. What I am hoping is that the array can actually pass so I can use it on another page.
SOLVED:
All i did was add a form that has a hidden value. And the value actually post
<form id = "postform" action = "cart.php" method = "post">
<input type = "hidden" id="obj" name="obj" val="">
<input type = "submit" value = "Show Cart" id = "showcart">
</form>
In the Javascript:
$(document).ready(function(){
$("#showcart").click(function(){
var json = JSON.stringify(object)
$('#obj').val(json);
$('#obj').submit();
});
});
Thank you for everyone at has answered but hope this helps others.
If example.php is the php file which handles the request, you need to change your js code to
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
var jExample = JSON.stringify(array);
$.ajax("example.php", {
data:{'jExam':jExample},
type: 'POST',
dataType: 'json'
});
});
And you should add the complete-Parameter if you want to handle the response.
Your mistake is, you are redirecting the page using window.location.href before you even send your request. Therefore, your request never gets sent and the PHP-File is called directly instead, not via AJAX, not with the nessecary data. Therefore, you are missing the data in the PHP-File.
You will want to try and make this setup a bit easier on yourself so here are a few things that can help you simplify this. You may or may not have some of these already done, so disregard anything you already do:
Use a config file with concrete defines that you include on 1st-level php files
Just pass one data field with json_encode()
Don't send json as a data type, it's not required, troubleshoot first, then if you need to, make it default as the send type
Use a success function so you can see the return easily
Make functions to separate tasks
/config.php
Add all important preferences and add this to each top-level page.
session_start();
define('URL_BASE','http://www.example.com');
define('URL_AJAX',URL_BASE.'/ajax/dispatch.php');
define('FUNCTIONS',__DIR__.'/functions');
Form:
Just make one data that will send a group of data keys/values.
<button class="cart" data-instructions='<?php echo json_encode(array('name'=>'Whatever','price'=>'17.00','action'=>'add_to_cart')); ?>'>Add to Cart</button>
Gives you:
<button class="cart" data-instructions='{"name":"Whatever","price":"17.00","action":"add_to_cart"}'>Add to Cart</button>
Ajax:
Just send a normal object
$(document).ready(function(){
// Doing it this way allows for easier access to dynamic
// clickable content
$(this).on('click','.cart',function(e)){
e.preventDefault();
// Get just the one data field with all the data
var data = $(this).data('instructions');
$.ajax({
data: data,
type: 'POST',
// Use our defined constant for consistency
// Writes: http://www.example.com/ajax/dispatch.php
url: '<?php echo URL_AJAX; ?>',
success: function(response) {
// Check the console to make sure it's what we expected
console.log(response);
// Parse the return
var dataResp = JSON.parse(response);
// If there is a fail, show error
if(!dataResp.success)
alert('Error:'+dataResp.message);
}
});
});
});
/functions/addProduct.php
Ideally you would want to use some sort of ID or sku for the key, not name
// You will want to pass a sku or id here as well
function addProduct($name,$price)
{
$_SESSION['cart'][$name]['name'] = $name;
$_SESSION['cart'][$name]['price'] = $price;
if(isset($_SESSION['cart'][$name]['qty']))
$_SESSION['cart'][$name]['qty'] += 1;
else
$_SESSION['cart'][$name]['qty'] = 1;
return $_SESSION['cart'][$name];
}
/ajax/dispatcher.php
The dispatcher is meant to call actions back only as an AJAX request. Because of the nature of the return mechanism, you can expand it out to return html, or run several commands in a row, or just one, or whatever.
# Add our config file so we have access to consistent prefs
# Remember that the config has session_start() in it, so no need to add that
require_once(realpath(__DIR__.'/../..').'/config.php');
# Set fail as default
$errors['message'] = 'Unknown error';
$errors['success'] = false;
# Since all this page does is receive ajax dispatches, action
# should always be required
if(!isset($_POST['action'])) {
$errors['message'] = 'Action is require. Invalid request.';
# Just stop
die(json_encode($errors));
}
# You can have a series of actions to dispatch here.
switch($_POST['action']) {
case('add_to_cart'):
# Include function and execute it
require_once(FUNCTIONS.'/addProduct.php');
# You can send back the data for confirmation or whatever...
$errors['data'] = addProduct($_POST['name'],$_POST['price']);
$errors['success'] = true;
$errors['message'] = 'Item added';
# Stop here unless you want more actions to run
die(json_encode($errors));
//You can add more instructions here as cases if you wanted to...
default:
die(json_encode($errors));
}

What goes into Responce in jQuery AJAX?

I'm sorry to add this broad question here, but I cannot seem to google it myself, I tried, and I really can't grasp the idea behind this, so here goes.
So I have a web-site that uses AJAX to login a user without full page reload. I kind of understand how AJAX works, and I'm sorry for my ignorance, but in my case:
$.ajax({
url: './',
type: 'POST',
data: {auth: auth, login: login, pass: pass}
success: function(res){
// Code that checks if **res** is a specific string
},
error: function(){
alert("Error!");
}
I understand that this sends POST request to the same page with 3 parameters. What I don't understand is what specifically does it get as a responce? In my case, in res is the $_SESSION element that contains the string message.
My question is: how do I know what gets in the responce? If I would just echo something in my function, would that get in the responce? Is there like a documentation about what can be passed to the arguments of success function?
I'm really confused about this.
The "res"... or commonly "data" in most examples, is simply the reply data from your page that your posting to..
So say in the case of PHP... you yes would simply echo anything back to it.
commonly people use JSON, so with php you would create a array with all the data you want to send back and then simply do
YOUR PAGE THAT SENDS THE POST
<script>
// JUST USING SUCCESS HERE ATM (Tthis does not show the full ajax command)
// Refer to original question for full javascript
success: function(res){
var myData = $.parseJSON(res);
if(myData.hasOwnProperty('name')){
alert(myData.name);
}
if(myData.hasOwnProperty('object1') && myData.object1.hasOwnProperty('items')){
alert(myData.object1.items.one);
}
},
</script>
YOUR PHP PAGE THAT RESPONDS
<?php
$myResponse = array();
$myResponse['name'] = "John Doe";
$myResponse['number'] = 123456789;
$myResponse['other'] = "and so on";
$myResponse['object1'] = array();
$myResponse['object2'] = array();
$myResponse['object1']['name'] = "john";
$myResponse['object1']['items'] = array();
$myResponse['object1']['items']['one'] = "one one 1";
$myResponse['object1']['items']['two'] = "two two 2";
$myResponse['object2']['name'] = "jane";
echo json_encode($myResponse);
?>
By using a "multidimensional" array in php, you can then treat each part of the array as a separate section/object
This might help: http://www.thecave.info/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/
Well, I think that what you "echo" is what you will retrieve in the "res",
try to see it in the console with:
console.log(res);
Or with an alert
alert(res);
try console.log(res); and check the browser console
ctrl + shift + k (firefox)
f12 (Chrome & IE)
For you task I would recommend using getJSON, instead of .ajax. It's just a shorthand for the same function, but really handy.
$.getJSON('/ajax-get-session/login/value/pass/value', function(json){
if (!json.error) { //check if there wasn't error on the server side
console.log(json.session);
} else {
console.log(json.error);
}
});
And on the server side.
$response = array();
try {
$response['session'] = $_SESSION;
}
catch (e) {
$response['error'] = e;
}
echo json_encode($response)

Call different PHP functions from javascript

I realize that calling database from JavaScript file is not a good way. So I have two files:
client.js
server.php
server.php has multiple functions.
Depending upon a condition, I want to call different functions of server.php.
I know how to call server.php, but how do I call different functions in that file?
My current code looks like this:
function getphp () {
//document.write("test");
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// data is received. Do whatever.
}
}
xmlhttp.open("GET","server.php?",true);
xmlhttp.send();
};
What I want to do is something like (just pseudo-code. I need actual syntax):
xmlhttp.open("GET","server.php?functionA?params",true);
Well based on that premise you could devise something like this:
On a sample request like this:
xmlhttp.open("GET","server.php?action=save",true);
Then in PHP:
if(isset($_GET['action'])) {
$action = $_GET['action'];
switch($action) {
case 'save':
saveSomething();
break;
case 'get':
getSomething();
break;
default:
// i do not know what that request is, throw an exception, can also be
break;
}
}
Just do something like this, i hope this will work
xmlhttp.open("GET","server.php?function=functioName&paramsA=val1&param2=val2",true);
You will most likely need to create the mechanism yourself.
Say the URL will look like server.php?function=foo&param=value1&param=value2
On the server side you will now have to check whether a function with such a name exists, and if it does, call it with these parameters. Useful links on how to do it are http://php.net/manual/en/function.function-exists.php and http://php.net/manual/en/functions.variable-functions.php
Otherwise, if you don't want to have it like this, you can always go with if/switch and simply check that if $_GET["function"] is something, then call something etc.
You can use jQuery too. Much less code than pure js. I know pure js is faster but jQuery is simpler. In jQuery you can use the $.ajax() to send your request. It takes a json structured array like this:
$.ajax({
url: "example.php",
type: "POST",
data: some_var,
success: do_stuff_if_no_error_occurs(),
error: do_stuff_when_error_occurs()
});
Here's a dynamic way to solve this issue:
xmlhttp.open("GET","server.php?action=save",true);
PHP Code:
<?php
$action = isset($_GET['action']) ? $_GET['action'] : '';
if(!empty($action)){
// Check if it's a function
if(function_exists($action)){
// Get all the other $_GET parameters
$params = array();
if(isset($_GET) && sizeof($_GET) > 1){
foreach($_GET as $key => $value){
if($key != 'action'){
$params[] = $value;
}
}
}
call_user_func($action, $params);
}
}
?>
Keep in mind that you should send the parameters in the same order of function arguments.
Let's say:
xmlhttp.open("GET","server.php?action=save&username=test&password=mypass&product_id=12",true);
<?php
function save($username, $password, $product_id){
...
}
?>
You can't write the API Call that way:
xmlhttp.open("GET","server.php?action=save&password=mypass&username=test&product_id=12",true);
Keep in mind that it's really bad to send "function namespaces" along with the parameters to a back-end. You're exposing your back-end and without proper security measures, your website will be vulnerable against SQL Injection, dictionary attack, brute force attack (because you're not checking a hash or something), and it'll be accessible by almost anyone (you're using GET using of POST and anyone can do a dictionary attack to try to access several functions ... there's no privileges check) etc.
My recommendation is that you should use a stable PHP Framework like Yii Framework, or anything else.
Also avoid using GET when you're sending data to the back-end. Use POST instead.

How to read the post request parameters using JavaScript

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.

Categories