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>
Related
So I have a JS variable that is created after pressing a button, and I need to pass it to my app to process in flask. I'm currently trying to do it with query strings but I'm not really sure what I'm doing.
In the html I have a form set up like this:
<form action="/deleteBook" method="POST" onsubmit="deleteBook()">
<input type="submit" value="Delete" />
</form>
which calls this function to apply query string:
function deleteBook() {
var existingUrl = window.location.href;
window.location.href = existingUrl + '?itemID=' + itemToRemove;
};
and then I want to process that variable through flask:
#app.route('/deleteBook', methods=["POST"])
def deleteBook():
if(request.method == "POST"):
itemID = request.args.get('itemID')
In my mind the code should detect the form submission (basically single button click), call deleteBook() which should then append a query string to the URL which can then be processed in flask.
I'm aware that I'm lacking some basic knowledge about html/js/processing data so I'm not really sure where to go from here. Should I use PHP to process the request somehow? Or should I not be using a form at all? Or maybe in flask there is an easier way to get data without using POST? I'm not sure so any suggestions are appreciated, thanks!
Well I for one find your style for a question like this unique so I'll try my best to explain my idea of the answer.
Firstly, I would just have the form calling the function
Secondly, I would have the function call an 'XMLHttpRequest' with 'POST' configuration
The HTML
<form onsubmit="deleteBook()">
<input type="submit" value="Delete " />
</form>
The JavaScript
function deleteBook () {
var xhr = new XMLHttpRequest();
xhr.open('POST', existingUrl + '?itemID=' + itemToRemove, true); //The second argument is the url you wish to 'POST' to
xhr.send(); //if you want to do something if your flask returns something, 'xhd.onload = function () {}'
}
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);
I have a form on one page (one.html) that has a javascript funtion as its submit action:
<form id="the_form" action="javascript:myfunc('input_text');" method="post">
<input type="text" id="input_text" name="input_text">
<input type="submit">
</form>
I have another page (two.html) with a button that when clicked I would like to submit the form on one.html, along with a value for input_text. Is this possible with ajax or any other way for that matter? If possible, I would also like to redirect to the page I submit the form too although this is optional.
this code should be on second form:
$(document).ready(function(){
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
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 first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
return query_string;
}();
if(QueryString.preview){
console.log(QueryString.preview);
}
});
this sample read query and parse.
So, first you can send your form as GET, like http://asd.com/?param1=a¶m2=b
and then just use QueryString.param1 and QueryString.param2 in your another page.
Based on the comment under this post, I'm asuming you want to send it info from pageA to a php file that returns a resulting file:
download file using an ajax request
How to download file from server using jQuery AJAX and Spring MVC 3
Downloading file though AJAX POST
Based on the comments under your question, I'm assuming you want to post from pageA to new page (pageB) with javascript.
Quick answer: Not possible (in a userfriendly way).
More useful answer:
It requires a bit more work, but based on the info given, this might work:
Submit the form from pageA via either GET or POST to pageB
Create hidden fields (<input type="hidden"/>) and fill those with the corresponding GET or POST values. This might be easier with a serverside language like PHP, but isn't impossible in JS
Set a hidden input and name it like <input type="hidden" id="linkedSubmit" value="1" />
Create some javascript to see if $('#linkedSubmit').val()==1, if so continue to submit the form on pageB
This isn't the prettiest solution and on a slow connection the user will see page hopping. And because it is javascript it's clientside, thus a user can manually change the value to 1 and trick your page. This should not become a security problem.
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 working in ASPDotNetStorefront on an XML package (largely irrelivant). Basically I have a form with a bunch of fields and a button that 'submits' the form. I would actually like to have the button convert the values of the fields into a querystring and then perform a GET instead of a POST.
I would imagine that I could do something like this with JavaScript, perhaps jQuery, but I'm not sure how I would do that. Ideally, I would like a simple function I could call.
I should note that I'm using ASP.Net and I only want to convert the actual values of the fields to a query string, not any state information. This is for a search form.
With jQuery:
$.ajax({
url: 'url/Action',
type: 'GET',
data: $('#formId').serialize()
})
using:
jQuery ajax
jQuery serialize
Response.Redirect("Webform2.aspx?Name=" +
this.txtName.Text + "&LastName=" +
this.txtLastName.Text);
in WebForm2.aspx you can do like this
for (int i =0;i < Request.QueryString.Count;i++)
{
Response.Write(Request.QueryString[i]);
}
for jquery you can use AJAX to send data between pages. Here is the sample code
This is the best article i have found Using jQuery for AJAX in ASP.NET : codeproject
example of using AJAX
<div style="width:350px">
<div style="background:#CCC"> Edit</div>
<div id="divView"><asp:literal id="litName" runat="server"/></div>
<div id="divEdit" style="display:none"></div>
</div>
var options = {
method: 'POST',
url: 'ChangeName.aspx',
after: function(response) {
$("div#divView").html(response).show();
$("div#divEdit").empty().hide();
$("a#editName").show();
}
};
//bind to form's onsubmit event
$("form#ChangeName").ajaxForm(options);
Example without AJAX.Simple Javascript with Query String
<script lang=”javascript” type=”text/javascript”>
function testQueryStrings()
{
window.location = “search.aspx?q=abc&type=advanced”;
}
</script>
<input type=”button” id=”btn” value=”Test Query Strings” onclick=”testQueryStrings()” />
for search.aspx
<script lang=”javascript” type=”text/javascript”>
var qrStr = window.location.search;
var spQrStr = qrStr.substring(1);
var arrQrStr = new Array();
// splits each of pair
var arr = spQrStr.split(‘&’);
for (var i=0;i<arr.length;i++){
// splits each of field-value pair
var index = arr[i].indexOf(‘=’);
var key = arr[i].substring(0,index);
var val = arr[i].substring(index+1);
// saves each of field-value pair in an array variable
arrQrStr[key] = val;
}
document.write(“<h1>Search parameter: “+arrQrStr["q"]+”. Extra parameter: “+arrQrStr["type"]+”</h1>”);
You could do this:
<input type="submit" value="get">
With (since you tagged this jQuery):
jQuery('input[type=submit]').click(function () { this.form.method = 'GET'; });
… but forms that might go to bookmark-able data or might make significant changes sound like they would be confusing to the user (and I can't think of any other reason to switch from post to get on the fly in end user controls).
If you always want to GET data, then you should modify the source sent to the browser instead of twiddling the DOM on the fly with JS.
Really, you just need to change the method attribute of your <form> tag in your HTML.
If you don't have direct control over the markup that your .NET component generates, you can always manipulate the <form> tag and set the attribute with JavaScript when the page loads.
Or, you can bind a click event to the form's submit button, and cancel the event (by returning false for example), and do a GET yourself.
You could just se <form method="GET"> instead of <form method="POST">. No Javascript needed (unless you do not want to refresh the page).