This is the form data.
<div>
<form name="payform" action="pay.html" method="POST">
<div>
<input id="customerName" name="firstname" ng-model="customerName" style="display:none"/>
<input style="display:none" id="txnid" name="txnid" ng-model="transactionid" />
<input type="submit" name="paybutton" id="payit" />
</div>
</form>
</div>
When i submit data the contents are posted to pay.html. How can I read those data using javascript on pay.html page?
Actually, you are sending data of the FORM through POST. If you are sending data through POST method, then you need a 'Server' which processes the data received from the HTML page and then forward the same data as response to the requested HTML Page.
If you change the Form data to GET, then you can read the data by using JavaScript.
If you still want to use POST, you can use Cookies to store and retrieve data on another page. Here are the steps!
Hope this helps.
The action attribute specifies where to send the form-data when a form is submitted and usually it's a server side method.
But,
If you don't use server-side programming, such as PHP or C#, or Java, you could use the query string, in order to GET search parameters.
For this, you have to use window.location.search property in order to get the search params.
var url_string = "http://www.example.com/t.html?a=1&b=3&c=4";
var url = new URL(url_string);
var c = url.search;
console.log(c);
get is not secure right? i cannot use method get. only allowed method
is post.
POST data is data that is handled server side. And Javascript is client side technology. The idea is that there is no way you can read a post data using JavaScript.
You can use localStorage in order to access data from anywhere.
You can send form data in URL, just set the form submission's method as "GET".
Then the url will be "localhost:XXXX/pay.html?firstname='himanshu'&txnid='1'".
Now at pay.html, you can read this URL from javascript methods and parse this url to get all the parameters.
Use window.location.search
You can use location.search
var params = {};
if (location.search) {
var temp = location.search.substring(1).split('&');
for (var i = 0; i < temp.length; i++) {
var dt = temp[i].split('=');
if (!dt[0]) continue;
params[dt[0]] = dt[1] || true;
}
}
console.log(params.abc);
console.log(params.xyz);
Related
I am working on a login system where you hash the password on the client side, before sending it to the server. I have got as far as grabbing the password and hashing it, and now I just need to insert it into the database and/or compare for a login.
<form action="javascript:;" onsubmit="return changeFormLogin()">
<p>Email</p>
<input id="username" type="email" name="username" placeholder="Enter Email" required>
<p>Password</p>
<input id="getPass" type="password" name="password" placeholder="••••••" required>
<input type="submit" name="login" value="Sign In">
<p id="demo"></p>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-sha256/0.9.0/sha256.min.js" ></script>
<script>
function changeFormLogin() {
var pass = document.getElementById('getPass').value;
var username = document.getElementById('username').value;
var getSalt = 123566;
var hashpass = sha256(pass+pass);
console.log(hashpass);
var tmp = validateLogin(hashpass);
if(tmp ==1){
//Welcome the user back, and load new form
}
else{
//Tell them to try again, notify them.
}
document.getElementById("demo").innerHTML = hashpass; //Used for testing
return true;
}
For simplicity I always use a FormData object when sending data
var fd = new FormData();
fd.append("Name", [VALUE]);
Then send that object in an XmlHttpRequest
Also, I don't really do security so I wouldn't know, but should the hashing be done server side?
Why not shift the entire encryption logic to the server side and insert into the database ? This way you just change action to your server page and POST it.
But if if you want to keep it this way, then you can do a ajax call in your JavaScript function.
Refer : https://www.w3schools.com/js/js_ajax_http_send.asp
Note: Although no one can reverse hash this thing, but still passwords will be visible from developer tools and brute force algorithm can be applied to get the password, so doing this thing in server is recommended
Edit :
Form submit with AJAX passing form data to PHP without page refresh
You could:
Send the information in a form using a POST or GET request (will result in a page refresh).
Use AJAX/XMLHttpRequest (without a page refresh).
Use a cookie.
Since you are trying to make a login system then I would recommend using a POST request (so it doesn't show the submitted info in the url bar) and a PHP session to check if the user has logged in yet (here's an example).
Not only that but if you want to keep your users login information private you shouldn't be using javascript for the authentication, search for tutorials on how to hash a password the right way, you'll find lots of related material on stackoverflow and information security.
PHP by default only supports bcrypt and argon but they are still better than SHA256 as SHA/HMAC is faster to computer and therefore faster to crack.
Here is a script.
It provides some select inputs which allow picking from various types of options. When the submit button is pressed it records the data in mats and pushes the mats array into an array called materialsUsed. Everytime the submit button is clicked a new array is added in materialsUsed.
I want to know how to send the materialsUsed array through a URL to php to extract the data there and insert it into an array created in PHP.
var mats = [name= "", thick= "", size= "", quantity= 0, price= 0];
mats.name = document.getElementById("mat").options[document.getElementById("mat").selectedIndex].value;
mats.thick = document.getElementById("thick").options[document.getElementById("thick").selectedIndex].value;
mats.size = document.getElementById("size").options[document.getElementById("size").selectedIndex].value;
mats.price = parseFloat($('#priceto').val()).toFixed(2);
mats.quantity = parseInt($('#quant').val());
materialsUsed.push(mats);
If you would like to simply load them as GET values into the URL just set them directly in the URL using location.href. Then simply use $__GET (IE: $__GET['mat']) in PHP to grab values.
var baseURL = "http://yourdomain.com";
window.location.href = baseURL + "?mat=" + mats.name + "&thick=" + mats.thick etc...
First you have to properly prepare your mats array and convert materialsUsed array into JSON format. Then you can call an ajax function like below, to send it to the php script.
var jsonString = JSON.stringify(materialsUsed);
$.ajax({
type: "GET",
url: "your_script.php",
data: {data : jsonString},
success: function(){
alert("Successfully sent the data!");
}
});
From the your_script.php file, you can perform this to extract the array.
$data = json_decode(stripslashes($_GET['data']));
Important
When using GET method, the amount of the data (length of url) is
limited. So, if your materialUsed array is too huge, you should use
POST method instead.
I think what you're looking for is making an ajax call to your php script providing your js array as its data.
You should listen for the form submission event in your javascript and launch an AJAX call to your PHP script providing your array. You may send your array via the URL (query string) using a GET or in the request body using a POST (that's an option you specify in your AJAX call). Then you would just retrieve your array in your php script an do whatever you want with it.
I suggest you read more on form submission events and AJAX calls in javaScript.
Quick hint : if you have the possibility to do so, try using jQuery as AJAX is way easier to use with jQuery.
You are trying to use associative array, but it's not possible in Javascript as far as I know.
I'd say the best way to do that is creating a object, parsing to json and sending to php. Does't look that hard.
Is it possible to catch the URL generated from a form when firing its 'submit' event?
I know I can generate the URL from data
I'm not talking about form's action URL
I mean the ?field=value&other-input-name=value& ... part
Scenario:
We have a form and a JavaScript script which sends an Ajax request to a PHP script.
I usually do like this:
Register for the form's submit event
Prevent the default behavior
Construct a URL from data
Open an HTTP request with the constructed URL
Now, I was wondering, when firing 'submit' normally (on non-Ajax requests) the URL gets constructed by the form, which then uses that URL to send data to the PHP counterpart.
How can I 'catch' that URL? There aren't any clues from the event itself which doesn't seem to store it, or at least I haven't been able to find it.
It must be somewhere!
This is possible and easy with the objects URLSearchParams and FormData.
FormData is an object representation of a form, for using with the fetch API. It can be constructed from an existing element like this:
let form = document.forms[0];
let formData = new FormData(form);
Then comes the URLSearchParams object, which can be used to build up query strings:
let search = new URLSearchParams(formData);
and now all you need to do is call the toString function on the search object:
let queryString = search.toString();
Done!
If you mean getting the form's action URL, that URL can be retrieved like this:
document.getElementById("form-id").action
If you are using jQuery and assuming you are doing an Ajax request, it would be like this:
var el = $('#form-id');
$.ajax({
type: el.attr('method'),
url: el.attr('action'),
data: el.serialize(),
context: this
}).done(callback);
To put it simply, you can't. The best you can do is to collect the form field values yourself, or using jQuery's .serialize() function, which returns those values exactly as you'd expect:
name=value&name2=value2
As already stated, you cannot get the generated URL containing the form values that the browser generates, but it is very easy to construct it yourself.
If you are using jQuery then use serialize(). If not, refer to the post Getting all form values by JavaScript.
var targetForm = $('#myForm');
var urlWithParams = targetForm.attr('action') + "?" + targetForm.serialize();
alert(urlWithParams);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="/search/" id="myForm" method="get">
<input name="param1" type="hidden" value="1">
<input name="param2" type="hidden" value="some text">
</form>
You can use javascript to generate it:
<script>
function test(frm) {
var elements = frm.elements;
var url = "?";
for(var i=0;i<elements.length;i++) {
var element = elements[i];
if (i > 0) url += "&";
url += element.name;
url += "=";
if (element.getAttribute("type") == "checkbox") {
url += element.checked;
} else {
url += element.value;
}
}
console.log(url);
return false;
}
</script>
<form onsubmit='return test(this);'>
<input name=field1 value='123'>
<input type=checkbox name=field2 checked>
<input type=submit>
</form>
I have a multi page form.
Page One has a few fields that get passed into the second form, via GET method, and it auto fills the first four fields of the second part of the form.
Page two has a few more questions, and when you submit it, it submits into our CRM(vanillaSoft), and leads to a thank you page.
My current issue:
I want to be able to take an affiliate link, such as:
http://something.com/step-one.html?AFFILIATE_ID=#affid#&SUB_ID=#s1#
I need to dynamically populate the AFFILIATE_ID parameter with a unique transaction ID, and the SUB_ID with a unique ID as well.
I currently have two fields on my first page with hidden fields, ex:
<input type="hidden" name="SUB_ID">
<input type="hidden" name="AFFILIATE_ID">
But that isn't working. I need this date to be sent into the CRM I use.
Any advice?
Thanks!!!
Your current setup will work if you set your form submit method to GET. You probably have it set to POST.
Setting your form method to GET will put those hidden fields in the URL, like you are expecting.
On the last form, set that one to POST (to POST to the server).
You can grab the Query string with JavaScript, like this:
var getParamValue = (function() {
var params;
var resetParams = function() {
var query = window.location.search;
var regex = /[?&;](.+?)=([^&;]+)/g;
var match;
params = {};
if (query) {
while (match = regex.exec(query)) {
params[match[1]] = decodeURIComponent(match[2]);
}
}
};
window.addEventListener
&& window.addEventListener('popstate', resetParams);
resetParams();
return function(param) {
return params.hasOwnProperty(param) ? params[param] : null;
}
})();
How can I get query string values in JavaScript?
You could also send both POST and GET methods. But POST can be done only on server side, where JavaScript is Client-side scripting language.
<form method="POST" action="form.php?a=1&b=2&c=3">
PHP -> Send both POST and GET in a form
How to read the post request parameters using javascript
I am trying to hardwire an on-the-fly created form to send JSON using the encoding type "application/json".
in jQuery, I would set this as 'contentType' in an $.ajax or a $.post - however for certain reasons, I need to be doing this manually.
I have the following code, but it just doesn't work. It still defaults the enctype to application/x-www-form-urlencoded
data = data;
var form = document.createElement("FORM");
form.style.display = "none";
form.action = url;
form.setAttribute('enctype', 'application/json');
form.method = "post";
Am I trying to set the wrong property, or am I just setting it wrong? Any ideas?
Not sure that 'application/json' is supported as a valid enctype. According to the HTML401 specification:
"W3C User agents must support the content types listed below (application/x-www-form-urlencoded, multipart/form-data). Behavior for other content types is unspecified."
http://www.w3.org/TR/html401/interact/forms.html#form-content-type
So I guess that support for this is down to the browser vendor.
If you want to mimic the way jQuery and other javascript libraries work then you'll be using an xmlhttp request to post your data instead of using a FORM element, you dont need to tell the server what kind of content type you'll be sending when you do this, the server will assume (rightfully) that you are using application/x-www-form-urlencoded .
I don't think a form can do that.
You'll need to do it on the server side. Or if you must do it on client prior to sending (not recommended) then look at a JSON library.
You should check out the w3Schools reference.
form.enctype = enctype;
EDIT - I didn't notice you wanted the form to encode the data into JSON...that's not going to happen. Either use AJAX or process it server side and return the response in JSON.
I believe that you should use
enctype="multipart/form-data"