Get htaccess URL params in JavaScript - javascript

Is there any way in Javascript to get the parameters ume modified URL with htaccess?
As an example: www.website.com/argument/1/argument/2
Where "/argument/2" = &product_id=2
There is some way to pick up these parameters in JavaScript?

You can export these properties by simply printing the map as JSON. I'm going to show this in PHP.
<script>
var GET = <?= json_encode($_GET); ?>;
</script>
Then you can access the values as GET['product_id'].

Related

How to receive HTTP POST parameters on vue.js? [duplicate]

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.

Making Json objects using Session Variables in another file

I was trying to make a Json Object of some variables Which I am using as Session variables, But I am not geting the proper Response To make it as Json Object ..
Some Code which I tried (for Reference) Sharing Below..
//Passing the Variable To another PHP File
session_start();
$_SESSION['EmailIds']=$strEmailIds;
$_SESSION['SCHOOL_NAME']=$SCHOOL_NAME;
//sending data to another php page ..
header('Location: ../SecondPage.php');
In second file SecondPage.php Where i was Using This Session..
session_start();
$SCHOOL_NAME = $_SESSION['SCHOOL_NAME'];//1
$EmailIds= $_SESSION['EmailIds'];//1 <br>
Now trying to make this Session Variable in Json OBject...????
var OBJ = jsonObj.(SCHOOL_NAME+EmailIds);// Confuse with THis Line<br>
Actuaaly Not Getting What is the Good Approach To make this variables as Json Objects..
AS I Made this Json Object I can Use This AS another Purpose Like to send as Ajax Data and etc..
You can use json_encode method like this :
$someArray; //can be array of your values or $_SESSION
$jsonObj = json_encode($someArray);
get session data in an array like :
$data['SCHOOL_NAME'] = $_SESSION['SCHOOL_NAME'];
$data['EmailIds']= $_SESSION['EmailIds'];
then encode it like
$json_obj = json_encode($data);

What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing

THE QUESTION
What is the most efficient and correct way of handling PHP array variables within JavaScript and being able it obtain those values using indexing.
I have a MYSQL database and have a PHP script that creates an indexed row array of the database information.
Now that this information is within the array i am comfortable about echoing this data on screen from within PHP.
i.e.
echo $lastplayed[1]['artist'];
My next step is to take the array into JavaScript so that i can use the variable information to display data on screen, make calculations and create an Ajax timer that looks for a value from a variable and refreshes the page..
Its basically a internet radio station that will display what is and has been played and when a counter reaches zero will refresh the page. (the counter being time left of a song)
I could echo each variable into a separate PHP script and then use JavaScript to call each of those PHP scripts that contain the different variables (This seems long-winded) AND puts unnecessary request strain on the MYSQL server
**I really feel that there must be a better way of transferring and handling the data, surely there must be some type of bridge between PHP and JavaScript, should i be looking into JSON ?
So my end result is to be able to take an indexed array from PHP, transfer this array into JavaScript and be able to call on different variables from within the array using indexing (i.e call the variable that resides in result 3 column 3)
And while this is happening i will be using separate PHP and JavaScript files...
Here is my code for the PHP part.
<?php
date_default_timezone_set('Europe/London');
require_once("DbConnect.php");
$sql = "SELECT `artist`, `title`, `label`, `albumyear`, `date_played`, `duration`,
`picture` FROM historylist ORDER BY `date_played` DESC LIMIT 5 ";
$result = $db->query($sql);
$lastplayed = array();
$i = 1;
while ($row=$result->fetch_object()) {
$lastplayed[$i]['artist'] = $row->artist;
$lastplayed[$i]['title'] = $row->title;
$lastplayed[$i]['label'] = $row->label;
$lastplayed[$i]['albumyear'] = $row->albumyear;
$lastplayed[$i]['date_played'] = $row->date_played;
$lastplayed[$i]['duration'] = $row->duration;
$lastplayed[$i]['picture'] = $row->picture;
$i++;
}
$starttime = strtotime($lastplayed[1]['date_played']);
$curtime = time();
$timeleft = $starttime+round($lastplayed[1]['duration']/1000)-$curtime;
$secsremain = (round($lastplayed[1]['duration'] / 1000)-($curtime-$starttime))
?>
Any thoughts on this would be greatly appreciated and thanks so much for your time.
Justin.
PROGRESS:
Thanks for the comments, i really need to take a JavaScript course at this point...
Now i have created a new output.PHP file that does the following
<?php
require_once("dblastplayedarray.php");
echo json_encode($lastplayed);
?>
So this file now echo's out the data i need in a JSON format from my array $lastplayed.
#VCNinc you say that i now can use the following code to take the data into JavaScript
<script>
var array = <?=json_encode($lastplayed)?>;
</script>
Please could you detail where i put the path information in this code so that the program knows where to look for the .PHP file output.php
Am i doing this right.. should i be printing the data into another .PHP file and then use your code to take the array into JavaScript..
Thanks
Justin.
JSON is the bridge!
You can "export" the variable to a json string and print on the output:
echo json_encode($lastplayed);
TIP: if the php file is used to show a html GUI AND you still want output a JSON too, you can create a GET variable like "&json=1" and, before output your HTML GUI, you do a IF. This way tou can use the same php file to output a GUI and the JSON. WHen you do the request via ajax, you call using the "&json=1".
if(isset($_GET['json']) && $_GET['json']==1){
echo json_encode($lastplayed);
exit;
}
Then, use AJAX to download this JSON string by calling your php script.
$.getJSON(url, function (json) {
//here the 'json' variable will be the array
//so you can interact on it if you want
$.each( json, function( key, value ) {
alert( key + ": " + value ); //here you can do anything you want
});
});
If you have a PHP array $array, you can easily export it into JavaScript like this:
<script>
var array = <?=json_encode($array)?>;
</script>
(and from that point you can manipulate it as JSON...)

Access MyBB PHP variable with Javascript

Is it possible to grab a MyBB PHP variable with Javascript? I am an userscript coder, and right now I use:
var uid = $("#panel").find('a').attr('href').replace(/[^0-9]/g, '');
To grab the user id (uid) of the current user. However, if I were to grab the UID from the user with PHP, it would look like this:
<?php echo {$mybb->user['uid']} ?>
Now to the actual question. Is it possible to grab the UID through Javascript, using the $mybb->user['uid']?
My answer is Yes, you can but it has some limits.
Well, if you remember in every headerinclude templates always have these code:
<script type="text/javascript">
<!--
var cookieDomain = "{$mybb->settings['cookiedomain']}";
var cookiePath = "{$mybb->settings['cookiepath']}";
var cookiePrefix = "{$mybb->settings['cookieprefix']}";
var deleteevent_confirm = "{$lang->deleteevent_confirm}";
var removeattach_confirm = "{$lang->removeattach_confirm}";
var loading_text = '{$lang->ajax_loading}';
var saving_changes = '{$lang->saving_changes}';
var use_xmlhttprequest = "{$mybb->settings['use_xmlhttprequest']}";
var my_post_key = "{$mybb->post_code}";
var imagepath = "{$theme['imgdir']}";
// -->
</script>
You can use MyBB's variables in any template with one condition: it's must be defined in the correlative PHP file. (Of course that variable must be inside the brackets { })
For example, the correlative PHP file with headerinclude template is global.php.
That's it. Have fun with MyBB :)
You can add a plugin to your forum. It is called template conditionals. Once you have that installed you can use the Mybb->user variable in all templates. There are many applications of this plugin, but for your code you can do:
<setvar uservar>$mybb->user['uid']</setvar>
var {$tplvars['uservar']} = $("#panel").find('a').attr('href').replace(/[^0-9]/g, '');
The plugin is on the MyBBHacks forum at the link below.
http://mybbhacks.zingaburga.com/showthread.php?tid=464
First, you will not be able to directly access a php server side variable in javascript, but there are several work arounds you could do.
The first one that comes to mind is to put this in your html page somewhere
<script type="text/javascript">
<?php echo "var uid = '". $mybb->user['uid']."';" ?>;
</script>
The downside to this is that this variable is now directly view able and editable in the DOM.
If you are using (or can use) a template you may place a PHP variable in a JavaScript variable defined within that template's content. If you plan to run this JavaScript on every page you must add the variable definition to the script block in the headerinclude template.
<script type="text/javascript">
<!--
var userID = {$mybb->user['uid']};
// -->
</script>
That example script will place the user's uid in the JavaScript variable userID.
Please note that <?php echo $mybb->user['uid']; ?> will not work as MyBB's template system does not allow PHP tags within it. You may instead use {$mybb->user['uid'} as an alternative.
Also, take note that if you are using a plugin and eval'ing the template in a function in your plugin file you will also need to globalise the PHP variable you are going to use.

In PHP how to use $_REQUEST to retrieve an array of inputs to enter into a database

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.

Categories

Resources