After form submission I want to redirect to another page where I need values from the Previous submitted form.
So in my redirect script I want to pass those values in GET
I am doing this :
<script>
var id = <?php echo $data['base_ini_id']."?&ext=".$data['ext']; ?>
window.location.replace("./edit_ini_custom/"+id);
</script>
OR Is there anything else with which I can do as required?
Get variables are (always) passed through the URL. So basically you should use:
var redirectUrl = "yourUrlWithVariables";
window.location.replcae(redirectUrl);
Now depending on the format of your target URL, the way you compose the target URL. Here are some common examples:
Format 1: baseUrl.com/page?paramName1=paramValue1¶mName2=paramValue2
var baseId = '<?=$data['base_ini_id'];?>';
var extId = '<?=$data['ext'];?>';
var baseUrl = "baseUrl.com/edit_ini_custom?base_ini_id="+baseId+"&ext="+extId;
Format 2: baseUrl.com/page/paramValue
var extId = '<?=$data['ext'];?>';
var baseUrl = "baseUrl.com/edit_ini_custom/"+extId;
Format 3: baseUrl.com/page/paramName/paramValue
var extId = '<?=$data['ext'];?>';
var baseUrl = "baseUrl.com/edit_ini_custom/ext/"+extId;
Format 4: baseUrl.com/page/paramName1/paramValue1/paramName2/paramValue2
var baseId = '<?=$data['base_ini_id'];?>';
var extId = '<?=$data['ext'];?>';
var baseUrl = "baseUrl.com/edit_ini_custom/base_ini_id/"+baseId+"/ext/"+extId;
Note that this are only guidelines, and in any case after you parse and build the target URL, you must call window.location.replace(baseUrl). Other option is just use:
window.location = baseUrl;
but using this will add that redirection to the history allowing users to hit "back", which I'm not sure is something you'd like.
Hope this helps
The form that's already submitted (in the previous page) cannot be accessed, as such, from the next page.
So, in short, the answer to your question is NO.
You need to implement in one of the ways:-
Store the values in the user's session object (if you already have login implemented)
Use a Http Cookie or Browser's localStorage to store the value
Persist the value to the server and fetch in the subsequent page, as hidden variables.
You can do a PHP redirect by setting the header Location
header("Location: ".$data['base_ini_id']."?&ext=".$data['ext']);
This will be a convenient way i guess than the one you suggested.
Finally Got an Answer:
<script>
var id = <?php echo $data['base_ini_id']; ?>
window.location.replace("./edit_ini_custom/"+id+"/"+<?php echo $data['ext']; ?>);
</script>
I can pass the PHP Variable as PARAMETER And On the Function Where I need it i Just Have to Do :
public function edit_ini_custom($id,$ext)
{
echo $ext;
//code
}
Related
I have an index HTML page that grabs a user's username and password from a form.
I want to base 64 encode this before passing it to a php file that makes a request to a server with the encoded credentials.
I tried doing something like:
<script>
// The below function calls the PHP file responsible for retrieving campaign details.
function getCampaignDetails() {
var username = $('#username').val(); //This successfully returns the username.
var password = $('#password').val(); //This successfully returns the password.
var authentication_string = <?php $username = urldecode($_GET['username']); $password = urldecode($_GET['password']); echo base64_encode($username.':'.$password); ?>;
$.ajax({
type: "GET",
url: "http://localhost/testing/get_campaign_details.php",
headers: { 'Access-Control-Allow-Origin': '*' },
data: {
"authentication_string": authentication_string
},
});
}
</script>
But I get an error about an unexpected token < which I'm assuming is a syntax error in the authentication_string value. If I add quotes around this value, the php doesn't execute and I get the whole string as is passed to the php file, rather than the encoded credentials.
Is there a way to use PHP in a basic HTML file that grabs a JavaScript variable value, uses a PHP function to get a new value, and then pass back this new value to the data in an Ajax request from the HTML file that is then subsequently utilized by another PHP file?
Or is there a way to base 64 encode something using an HTML/JavaScript function instead of PHP function?
Best,
You need to add quotation marks around the php that you're running to get the authentication_string.
var authentication_string = "<?php $username = urldecode($_GET['username']); $password = urldecode($_GET['password']); echo base64_encode($username.':'.$password); ?>";
Javascript is expecting a value that it can assign to the variable authentication_string after the = like an int or a string. When it see's < it doesn't know what to do with it so it throws an unexpected token error.
As a sidenote - passing a username and password in the querystring (the url) is not a good idea. Even though they are encoded it's better to keep those kind of things away from prying eyes. There's a post here that might be helpful on how to handle sensitive data like that. Best way to pass a password via GET or POST
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));
}
I need a page that when I load it check out the link typed for example:
www.test.com/myphp.php=10
if it finds certain number it redirects to another link for example:
found www.test.com/myphp.php=10 redirects to news www.test.com/news/10.php.
How can I do this and what technology should I use?
First off, your syntax for GET variables is a little off. I assume you mean starting URLs of test.com/myphp.php?redirect=10 or something similar? Because www.test.com/myphp.php=10 is bad syntax.
I'm assuming we're using GET variables as described above in my answer:
The simplest way to do this would be to just set the location header in PHP:
if(array_key_exists("redirect", $_GET)){
#set header to redirect to new location
header("Location: /news/" . $_GET["redirect"] . ".php");
#don't let the page do anything else
die();
}else{
#do something if the GET variable doesn't exist
}
Note that this way introduces a few security vulnerabilities, so you might want to do something more advanced (such as intval the GET variable so that they can't inject a script into your variable, or just addslashes() to the GET variable value).
You want to use a $_GET variable like so
http://www.test.com/myphp.php?p=10
and for your php you can do this.
header('Location: /news/' . $_GET['p'] . '.php');
die();
Url should be with a get parameter name.
http://www.test.com/myphp.php?news=10
if(isset($_GET['news']) && is_numeric($_GET['news'])) {
$newsUrl = 'http://www.test.com/news/' . (int)$_GET['news'] . '.php';
header('location: ' . $newsUrl);
// or
// header('location: /news/' . (int)$_GET['news']);
die;
}
Plain old javascript
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
If the url is www.test.com/myphp.php?id=10
Calling getQueryVariable("id") would return 10
Then you just reroute using
var number = getQueryVariable('id')
window.location = "www.test.com/news/"+number+".php";
By using below code on button click I get the href attribute value, until this everything is fine but when I got my href link on button click we want to store it in the session variable (i.e. var href) because we also use this variable elsewhere. Please suggest me how to store JavaScript variable in session.?
<script>
$(document).ready(function(){
$('.button').click(function(){
var href = $(this).val();
alert(href);
})
});
</script>
<button value="<?php echo $value['3']; ?>" class="button" style="background-color:#ff8c21;">Buy Now</button>
You can't set SESSION WITH JAVASCRIPT this is because its server side functionality so if you want to use this data some where else you can send a ajax request to server and there you can create session for this data.
JS:
$(document).ready(function(){
$('.button').click(function(){
var href = $(this).val();
$.ajax({
type: "POST",
url: url,//url to file
data: {val:href},
success: function(data){
//success
};
});
});
});
PHP:
session_start();
if(isset($_POST['val']))
{
$_SESSION['href'] = $_POST['val'];//created a session named "href"
}
//use session
if(isset($_SESSION['href']))
{
echo $_SESSION['href'];//use your session.
}
Please try it if you want to use session using jquery
First include jquery-1.9.1.js and jquery.session.js
$(document).ready(function(){
$('.button').click(function(){
var href = $(this).val();
$.session.set("yoursessioname", "storevalue");
})
});
alert($.session.get("yoursessioname"));
more detail http://phprocks.letsnurture.com/create-session-with-jquery/
If you want to store it in session which is SERVER side then you need use ajax pass variable and store it in php for example with
<?php
session_start();
!isset($_POST['var']) ?: $_SESSION['var'] = $_POST['var'];
but you can think of using cookies as well, then you don't need PHP it can be done only with JavaScript. There is nice Jquery plugin for that
JavaScript works in the browser and PHP sessions are activated on the server, so you can't change session variables without sending a request to the server eg via a url or by submitting a form.
BUT you could use sessionStorage, which is a similar principle but lives in the browser and is modifiable by javascript.
eg. (inside javascript)
sessionStorage.myvariable=myVal
etc. It will live as long as your tab is open (from page to page).
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.