"Undefined array key" when cookies are read in php script - javascript
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
Related
Send Data to php file with javascript
I am trying to send form data to another PHP file. its working but once data is submitted the page is not redirecting to that specific page. Like it work in php. function codeverify() { var code=document.getElementById('verificationCode').value; coderesult.confirm(code).then(function (result) { if (confirm("OTP Confirmed!")) { var number=document.getElementById('number').value; $.post("confirm-phone-reg.php", { status: number }); //send data to file //document.location.href = "http://localhost/test/new/confirm-phone-reg.php"; } else { window.location.href = "http://localhost/test/new/try-again.php"; }; var user=result.user; console.log(user); }).catch(function (error) { alert(error.message); }); } How can I make sure when I send data to the confirm-phone-reg.php the post data and my page will be opened there. I searched too much on internet but failed to search for answer. I hope you guys will help me.
var number = document.getElementById('number').value; var url = 'register.php'; var form = $('<form action="' + url + '" method="post">' + '<input type="text" name="phone" value="' + number + '" />' + '</form>'); $('body').append(form); form.submit(); For those who are also stuck like this. This is the easiest way to send data to another file and also redirect at the same time.
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 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>
pass variables from javascript to php with a cookie
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 ?>
using WinJS.xhr to post variables to a URL
Am trying to create a login page for my windows 8 app, am using Html5 and javascript.. so have tried to use winjs.xhr to post what is in the textboxes as variables to a specific url which is a php script so this is my example of the url "http://example.com/api/username=username&password=password" am using winjs.xhr to post these variables to the url but am not getting any response even in the console.log this is my code <script> function handlelogin(){ document.getElementById("box").onsubmit = function(){ if(document.getElementById("email_address").value ==""){ document.getElementById("errormessage").innerHTML= "Please Provide Your Email Address"; return false; }else{ var email_address = document.getElementById("email_address"); var password = document.getElementById("password"); var formparams = "?username=" + email_address.value + "&password=" + password.value; document.getElementById("errormessage").innerHTML = ""; WinJS.xhr({type: "POST", url: "http://example.com/api/", data: formparams, headers: { "Content-type": "application/x-www-form-urlencoded" } }).then( function (success) { console.log(success.statusText); if(success == 1703){ WinJS.Navigation.navigate("home.html"); } }, function (error) { console.log(error); } ); } }; } window.onload = function () { handlelogin(); } </script> <form id="box" method="post" name="loginform"> <p>Email address</p> <div class="email_address"><input type="text" id="email_address" /></div> <p>Password</p> <div class="password"><input type="password" id="password" /></div> <p><span id="errormessage"></span></p> <div class="button"><input type="submit" id="login" value="Sign In"/></div> <p>ForgotPassword?</p> </form>
First - don't use a submit button. Use a input type="button". No submit required, you are simply reading the values on the page. Second - attach the event handler for the button's click event. Doing this 'onload' for the window isn't the right place. Third - don't use 'onsubmit' for your 'box' element. There is no form submission going on here. There shouldn't usually be a form submit in WinJS - that's for a browser posting the page to the server. You already are POSTing your data. See the updated code: I highly recommend putting ALL javascript into separate files, as you'll get bytecode optimization that way. Inline Javascript isn't optimized for the next load. A common way you could do this is include the onload code below (where I assign onclick) in your js file like so app.onactivated = function (args) { .. .. .. args.setPromise(WinJS.UI.processAll().then(function () { document.getElementById("login").onclick = handlelogin; })); .. .. } }; But the answer directly for your question above is: <script> function handlelogin() { if (document.getElementById("email_address").value == "") { document.getElementById("errormessage").innerHTML = "Please Provide Your Email Address"; return false; } else { var email_address = document.getElementById("email_address"); var password = document.getElementById("password"); var formparams = "?username=" + email_address.value + "&password=" + password.value; document.getElementById("errormessage").innerHTML = ""; WinJS.xhr({ type: "POST", url: "http://example.com/api/", data: formparams, headers: { "Content-type": "application/x-www-form-urlencoded" } }).then( function (success) { console.log(success.statusText); if (success == 1703) { WinJS.Navigation.navigate("home.html"); } }, function (error) { console.log(error); } ); } } window.onload = function() { document.getElementById("login").onclick = handlelogin; }; </script> Check out some of the sessions in App Builder where they discuss JavaScript projects http://aka.ms/stackbuilder