pass variables from javascript to php with a cookie - javascript

this has been asked before, i want to do it so i can avoid refreshing the page caused by POST and GET, and ajax seems the right way
but i was wondering if i can make a cookie with javascript and then (from the same page) access it with php. is it possible?
small example:
//html code:
<form name="PLForm" onsubmit="myFunction()">
<input type="text" name="PLName"/>
</form>
//JS part:
myFunciton() {
var cname = "playlistName";
var cvalue = document.form["PLForm"]["PLName"];
document.cookie = cname + "=" + cvalue;
}
//in php:
<?php
$x = $_COOKIE["playlistName"];
//some code
?>

Related

"Undefined array key" when cookies are read in php script

My html code:
<form id="details" action="database_registration.php" class="form">
Full name: <strong name="name_1">ABC</strong><br><br>
ID No:<strong name="org_number_1">1</strong><br><br>
Mobile No:<strong name="ph_number_1">1234567890</strong><br><br>
E-mail: <strong name="email_1">abc#def.com</strong><br><br>
ID Card: <img src="preview.jpg" alt="preview" name="image" style="width: 100px; height: 100px;"><br><br>
<button id="go" onclick="submit()" type="button" value="submit">go</button>
</form>
My javascript:
function submit(){
var nme=document.getElementsByName("name_1")[0].innerHTML;
var id=document.getElementsByName("org_number_1")[0].innerHTML;
var phone=document.getElementsByName("ph_number_1")[0].innerHTML;
var email=document.getElementsByName("email_1")[0].innerHTML;
var img=document.getElementsByName("image")[0].src;
document.cookie="name =" + nme;
document.cookie="ID No =" + id;
document.cookie="Mobile No =" + phone;
document.cookie="Email =" + email;
document.cookie="Image =" + img;
}
My php code:
<?php
var_dump($_COOKIE['name']);
var_dump($_COOKIE['ID No']);
var_dump($_COOKIE['Mobile No']);
var_dump($_COOKIE['Email']);
var_dump($_COOKIE['Image']);
?>
I keep getting the error:
Undefined array key
for each of the $_COOKIE values. Why? I have searched for this error on the internet, and in most cases, it happens mostly because of the fault of the programmer in giving incorrect names. But in my case, all the keys are correct. Please help me in fixing this error.
EDIT: Taking #Not A Bot's suggestion, I've modified my javascript by using the fetch() api:
document.getElementById('go').addEventListener('click', submit);
function submit(){
var nme=document.getElementsByName("name_1")[0].value;
var id=document.getElementsByName("org_number_1")[0].value;
var phone=document.getElementsByName("ph_number_1")[0].value;
var email=document.getElementsByName("email_1")[0].value;
var img=document.getElementsByName("image")[0].value;
document.cookie="name =" + nme;
document.cookie="ID_No =" + id;
document.cookie="Mobile_No =" + phone;
document.cookie="Email =" + email;
document.cookie="Image =" + img;
const dForm = document.getElementById('details');
dForm.addEventListener('submit', function(e) {
e.preventDefault();
fetch("database_registration.php",{
method: 'post',
mode: 'cors',
body: // what should I add here?
}).then(function (response){
return response.text();
}).then(function (text){
console.log(text);
}).catch(function (error){
console.error(error);
})
});
}
Can I add the document.cookie in the body of the fetch API?
You should use setcookie in the PHP action instead of document.cookie (it works, the problem is this javascript must be executed before, so maybe, you could have problems with that).
You can receive your data in your submit action in PHP and use this line to set the cookie:
setcookie('name_of_your_cookie', 'value_of_your_cookie', time() + (86400 * 30)); // 86400 = seconds in 1 day
I recommend you write the name of your cookies with the snake case naming convention (name_of_your_cookie) and without spaces.
Changes in HTML Code:
Avoid using onclick() onClick in HTML is Bad Practice
Instead of using action inside form you can send data to the server using AJAX. You can use Fetch API or XHR or AXIOS or any other. Since your action part is executing and not the JavaScript, thus you are not able to set cookies via JavaScript.
Button does not have a value attribute. Even does not need the type attribute.
<form id="details" class="form">
Full name: <strong name="name_1">ABC</strong><br><br>
ID No:<strong name="org_number_1">1</strong><br><br>
Mobile No:<strong name="ph_number_1">1234567890</strong><br><br>
E-mail: <strong name="email_1">abc#def.com</strong><br><br>
ID Card: <img src="preview.jpg" alt="preview" name="image" style="width: 100px; height: 100px;"><br><br>
<button id="go">go</button>
</form>
Changes in JavaScript:
Use EventListener instead of onclick()
Cookie's name should not have space in between words. Example Mobile No as cookie name should be avoided as it will work in JavaScript but PHP will give you NULL. So change Mobile No to Mobile_No and so on.
document.getElementById('go').addEventListener('click', submit);
function submit(){
var nme=document.getElementsByName("name_1")[0].innerHTML;
var id=document.getElementsByName("org_number_1")[0].innerHTML;
var phone=document.getElementsByName("ph_number_1")[0].innerHTML;
var email=document.getElementsByName("email_1")[0].innerHTML;
var img=document.getElementsByName("image")[0].src;
document.cookie="name =" + nme;
document.cookie="ID_No =" + id;
document.cookie="Mobile_No =" + phone;
document.cookie="Email =" + email;
document.cookie="Image =" + img;
}
Your PHP is fine, still, to make output looks good you can use <br /> in-between var_dump.
<?php
var_dump($_COOKIE['name']);
echo "<br />";
var_dump($_COOKIE['ID No']);
echo "<br />";
var_dump($_COOKIE['Mobile No']);
echo "<br />";
var_dump($_COOKIE['Email']);
echo "<br />";
var_dump($_COOKIE['Image']);
?>
Your PHP output looks like something like this:
string(3) "ABC"
string(1) "1"
string(10) "1234567890"
string(11) "abc#def.com"
string(11) "preview.jpg"
Update With Fetch API
HTML Code:
<form id="details" method="post" class="form">
Full name: <input type="text" name="name_1" /><br><br>
E-mail: <strong name="email_1">abc#def.com</strong><br><br>
Mobile: <input type="tel" name="ph_number_1" /><br><br>
<button id="go">go</button>
</form>
JavaScript Code:
document.getElementById('go').addEventListener('click', function(event){
event.preventDefault()
var name=document.getElementsByName("name_1")[0].value;
var phone=document.getElementsByName("ph_number_1")[0].value;
var email=document.getElementsByName("email_1")[0].innerHTML;
document.cookie="Email =" + email;
fetch('database_registration.php', {
method : 'post',
mode: 'cors',
headers: {
'Content-Type': 'application/json', // sent request
'Accept': 'application/json' // expected data sent back
},
body: JSON.stringify({
full_name: name,
mobile: phone
})
})
.then((res) => res.json())
.then((data) => console.log(data))
.catch((error) => console.log(error))
});
PHP Code:
<?php
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
$fullName = $decoded["full_name"];
$mobile = $decoded["mobile"];
$email = $_COOKIE["Email"];
$responseToUser = array(
"result" => "success"
);
print_r(json_encode($responseToUser));
}
?>
The solution might be much simpler - I had the problem as well: You have to set the path in the cookie. If you redirect from page x to y you will not find the cookie set on x unless you have set the path.
Example:
/shopystem/cart will not work on /shopsystem/checkout
/shopystem/ will work on /shopsystem/checkout
/shopystem/checkout will work on /shopystem/checkout
Refer to this:
How to extract the hostname portion of a URL in JavaScript

redirect to another page with post instead of get data [duplicate]

This question already has answers here:
JavaScript post request like a form submit
(32 answers)
Closed 7 years ago.
Basically what I want to do is send POST data when I change the window.location, as if a user has submitted a form and it went to a new page. I need to do it this way because I need to pass along a hidden URL, and I can’t simply place it in the URL as a GET for cosmetic reasons.
This is what I have at the moment, but it doesn’t send any POST data.
if(user has not voted) {
window.location = 'http://example.com/vote/' + Username;
}
I know that you can send POST data with jQuery.post(), but I need it to be sent with the new window.location.
So to recap, I need to send api_url value via POST to http://example.com/vote/, while sending the user to the same page at the same time.
For future reference, I ended up doing the following:
if(user has not voted) {
$('#inset_form').html('<form action="http://example.com/vote/' + Username + '" name="vote" method="post" style="display:none;"><input type="text" name="api_url" value="' + Return_URL + '" /></form>');
document.forms['vote'].submit();
}
per #Kevin-Reid's answer, here's an alternative to the "I ended up doing the following" example that avoids needing to name and then lookup the form object again by constructing the form specifically (using jQuery)..
var url = 'http://example.com/vote/' + Username;
var form = $('<form action="' + url + '" method="post">' +
'<input type="text" name="api_url" value="' + Return_URL + '" />' +
'</form>');
$('body').append(form);
form.submit();
Construct and fill out a hidden method=POST action="http://example.com/vote" form and submit it, rather than using window.location at all.
Here's a simple small function that can be applied anywhere as long as you're using jQuery.
var redirect = 'http://www.website.com/page?id=23231';
$.redirectPost(redirect, {x: 'example', y: 'abc'});
// jquery extend function
$.extend(
{
redirectPost: function(location, args)
{
var form = '';
$.each( args, function( key, value ) {
value = value.split('"').join('\"')
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
});
$('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
}
});
Here is a method, which does not use jQuery.
I used it to create a bookmarklet, which checks the current page on w3-html-validator.
var f = document.createElement('form');
f.action='http://validator.w3.org/check';
f.method='POST';
f.target='_blank';
var i=document.createElement('input');
i.type='hidden';
i.name='fragment';
i.value='<!DOCTYPE html>'+document.documentElement.outerHTML;
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you are using jQuery, there is a redirect plugin that works with the POST or GET method. It creates a form with hidden inputs and submits it for you. An example of how to get it working:
$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
Note: You can pass the method types GET or POST as an optional third parameter; POST is the default.
The answers here can be confusing so i will give you a sample code that i am working with.
To start with note that there is no POST parameter to java script windows.location function that you are referring to.
So you have to...
Dynamically make a form with a POST parameter.
Dynamically put a textbox or textboxes with your desired values to post
Invoke the submit form you dynamically created.
And for the example.
//---------- make sure to link to your jQuery library ----//
<script type="text/javascript" >
var form = $(document.createElement('form'));
$(form).attr("action", "test2.php");
$(form).attr("method", "POST");
$(form).css("display", "none");
var input_employee_name = $("<input>")
.attr("type", "text")
.attr("name", "employee_name")
.val("Peter" );
$(form).append($(input_employee_name));
var input_salary = $("<input>")
.attr("type", "text")
.attr("name", "salary")
.val("1000" );
$(form).append($(input_salary));
form.appendTo( document.body );
$(form).submit();
</script>
If all is done well, you shall be redirected to test2.php and you can use POST to read passed values of employee_name and salary; that will be Peter and 1000 respectively.
On test2.php you can get your values thus.
$employee_name = $_POST['employee_name'];
$salary = $_POST['salary'];
Needless to say , make sure you sanitize your passed values.
Generic function to post any JavaScript object to the given URL.
function postAndRedirect(url, postData)
{
var postFormStr = "<form method='POST' action='" + url + "'>\n";
for (var key in postData)
{
if (postData.hasOwnProperty(key))
{
postFormStr += "<input type='hidden' name='" + key + "' value='" + postData[key] + "'></input>";
}
}
postFormStr += "</form>";
var formElement = $(postFormStr);
$('body').append(formElement);
$(formElement).submit();
}
This is quite handy to use:
var myRedirect = function(redirectUrl, arg, value) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="'+ arg +'" value="' + value + '"></input>' + '</form>');
$('body').append(form);
$(form).submit();
};
then use it like:
myRedirect("/yourRedirectingUrl", "arg", "argValue");
var myRedirect = function(redirectUrl) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="parameter1" value="sample" />' +
'<input type="hidden" name="parameter2" value="Sample data 2" />' +
'</form>');
$('body').append(form);
$(form).submit();
};
Found code at http://www.prowebguru.com/2013/10/send-post-data-while-redirecting-with-jquery/
Going to try this and other suggestions for my work.
Is there any other way to do the same ?
You can use target attribute to send form with redirect from iframe.
Your form open tag would be something like this:
method="post" action="http://some.url.com/form_action" target="_top"
SOLUTION NO. 1
//your variable
var data = "brightcherry";
//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id='"+product_id+"'");
SOLUTION NO. 2
//your variable
var data = "brightcherry";
//passing the variable into the window.location URL
window.location.replace("/newpage/page.php?id=" + product_id);
details

How can I share javascript var with php?

I have a php file. I click on and with onclick I call a javascript function with a parameter passed. This parameter is received on javascript function like a var, but into this function I want add this to $_SESSION php var.
script language="javascript">
<?php
session_start();
?>
function recargar(myVar){
var variable_post="Mi texto recargado";
<?php
$_SESSION['b'] = variable_post; //Here I want add myVar
?>
});
}
</script>
</head>
<body>
<div id="recargado">My text</div>
<p align="center">
recargar
</p>
</body>
</html>
I know that this could be a wrong way, how can I do this possible or in a similar way?
Thanks!!
You can only manipulate $_SESSION on the server, but JS code runs only on the client. The easiest way to do that would be with an ajax call, which will look like this, assuming you're using jQuery:
function recargar(myVar){
var variable_post="Mi texto recargado";
$.get("setsession.php?var="+variable_post);
});
}
This will run the setsession.php script on the server, without reloading the page. The setsession.php script will look like this:
<?php
$_SESSION['b'] = $_GET['var'];
?>
Of course, this code needs more work on error handling, but this is the general idea.
You won't be able to set php session through js but you can use cookies with javascript like this :
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
Just call setCookie to set cookie, getCookie to get it and checkCookie to check it.
Javascript, loaded on the client-side like this, cannot write into a PHP variable directly, because PHP resides in the server-side.
To do what you want you will need to pass your Javascript variable to PHP in the server-side, via an HTTP request. It can be, for example:
clicking on a link like Click, which will reload the page (and there you will be able to do $_SESSION['b'] = $_GET['myVar'] ),
having a <form> submit, just like the link above,
or without re-loading the page by using AJAX, meaning "background" calls from Javascript to other pages without leaving your page. You can do AJAX calls in many ways, some of the other answers mention jQuery, a Javascript library that makes it easy to do such things. This post seems to explain it well.
use ajax, passing the variable to a php file.
Just below created a index.php file name in the header receives a script with an ajax, you will see that it is sending the variable you created to another file name file.php that receive so that you can process and return to the index.php file so you may make an append to your html.
I will put an example that the script's been a for variable returned can be treated the way you want.
If you do not know a lot of ajax follows the link via ajax jquery documentation.
http://api.jquery.com/jquery.ajax/
//---------------------------------------------------------------------------
index.php
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function(){
var variable_post="Mi texto recargado";
$.ajax({
url:'file.php',
type:'post',
data:{variable_post:variable_post},
success:function(data){
$('h1').html(data);
}
});
}
);
</script>
</head>
<body>
<h1>Text Here</h1>
</body>
</html>
//---------------------------------------------------------------------------
file.php
<?php
$_SESSION['b'] = $_POST['variable_post'];
echo $_SESSION['b'];
?>
//---------------------------------------------------------------------------
Remembering that using the browser features, for example in Chrome Inspect Element -> NetWork, you can check out everything that is sent back to the ajax a php page.
If you have any questions let me know.

how can i use javascript var in scriplets

I am trying to learn jsp. I know a little bit java and I dont know much about html tags so I simple use java codes as much as I can. What I am trying to do there is getting data from variables from text boxes and using them as string.
var text1 =<% request.getParameter("locationId"); %>;
<%
if ((text1 != null && text2 != null) && (!text1.equals("") && !text2.equals(""))) {
kw1 = "'%"+text1+"%'";
kw2 = "'%"+text2+"%'";
.
.
.
}
%>
Scriptlet is executed before any data about webpage get sent from server to client. Whatever you want to do you need to send postback to server (with forms or ajax call). I usually use jQuery so my answer will use it but feel free to modify it to use native JS code. First, I would create a page on server called something like createJsonObject, call it from client with $.ajax (type: "POST") and passed my argument as object
{varID: varID}
On server I would place my JSP on that page, read argumants upon page load, execute function and return object with data to client. In .done() I would do something with that data (display them in form, save them in JS variables...).
Hope this helps you out.
Example (Just showing how you can use Ajax with form example)
HTML form:
<form name="formName" method="post" action="">
<input type="text" name="name" id="firstName" value="" />
<input type="text" name="lastName" id="lastName" value="" />
<input type="submit" name="Update" id="update" value="Update" />
</form>
Ajax Post:
$("#update").click(function(e)
{
e.preventDefault();
var firstName = $("#firstName").val();
var lastName = $("#lastName").val();
var dataObject = {};
dataObject.firstName = firstName;
dataObject.lastName = lastName;
$.ajax({
type:'POST',
data:dataObject,
url:'returnData.php',
success:function(data)
{
alert(data);
}
});
});
PHP:
<?php
$receivedObject = json_decode($_POST['data'], true);
$name = $receivedObject['firstName'];
$lastName = $receivedObject['lastName'];
echo $name . ' ' . $lastName;
?>
I've not test this, so there might be somewhere i've gone wrong. But try something like my example and just ask if you need any help.
Ali, you can not use a javascript variable into jsp scriplate.
<%
String locationId=request.getParameter("locationId");
if ((text1 != null && text2 != null) && (!text1.equals("") && !text2.equals(""))) {
kw1 = "'%"+text1+"%'";
kw2 = "'%"+text2+"%'";
.
.
.
}
%>
but vise versa is possible you can use JSP variable into you javascript code.like this.
<script>
var locationId='<%=request.getParameter("locationId")%>';
alert(locationId);
</script>

get post field by JavaScript

as you know we can get post field by server side language like php,for example in php
$var1 = $_POST['field1']now I wanna know is it possible to get it by JavaScript to?(or any Client Side Language like VBScript)
for example I have page which has got form
<form method = "post" action="test.php">
in test.php I wanna get field by JavaScript,not by php.
Is it possible and how can I do it if it's possible?
You cannot read $_POST data using JavaScript.
When you submit data through the GET method, the generated query string can be read through the location.search object. Another method to "post" data from page 1 to page 2 is by using hashes.
The location object (JavaScript)
location.href = http://example.com/test.php?formElem=value&another=true#hash
location.search = ?formElem=value&another=true
location.hash = #hash
Example (based on the URL at the previous paragraph)
<script>
var $_GET = (function(){
var query_string = location.search.substr(1); //Exclude the first character: `?`
var data = query_string.split(/&+/); //
var $_GET = {};
for(var i=0; i<data.length; i++){
var qs = data.match(/^([^=]+)(?:=(.*))?$/);
$_GET[qs[1]] = qs[2];
}
return $_GET;
})()
alert($_GET["formElem"]); //Alerts "value"
</script>
An alternative method to transmit data from a form to a JavaScript HTML page is by using hashes:
<form action="index.html#someHash" method="get">
<input type="submit" name="someName" value="someValue" />
</form>
After submission, the following page will be requested: index.html?someName=someValue#someHashThe hash is available through the location.hash property.
in your test.php file, echo your post fields as a JSON object.
echo '<script> var data = '. json_encode($_POST).' </script>' ;
It can be accessed as a dictionary in javascript then.
Output in test.php
<script>
var data = { 'field1' : 'value1' , 'field2' : 'value2' } ;
alert(data['field1']);
</script>

Categories