How to get data sent from 1 page to another? - javascript

I have two page - 1. Index.html
2. Main.html
I want to sent a data from index to main. Which i can do like this:
<form action="Main.html" method="POST">
<input type="text" name="q">
</form>
I want to display the data sent from Index.html on Main.html
I know two methods of doing it -
1. using method="GET" in the form tag and get the data from the src(link).
2. Using side languages like php.
I dont want to use the first method to do this thing.
Please someone give me the codes of php for doing this.
It would be more help if you can tell any other way of doing this

Change your Main.html to Main.php
To get data in the Main.php with post method is just: $_POST['q'].
If you want to display your input text, just echo it: echo $_POST['q'].
Or you can save it into a variable too: $var = $_POST['q'].
Or if you don't want to use PHP, you can save input's value into a cookie and get that cookie's value in the Main.html with just JavaScript.
// function to get cookie || Parameter is your required cookie's name
function getcookie(cookiename)
{
var name = cookiename+"=";
var cookiearray = document.cookie.split(';');
for(var i=0; i<cookiearray.length; i++)
{
var c = cookiearray[i].trim();
if(c.indexOf(name) === 0)
{
return c.substring(name.length, c.length);
}
}
return "";
}

You have another option, if you don't want to use server side language...
you can use JavaScript, or it's library like jQuery to do that.
One HTML file:
<form method="POST">
<input type="text" name="q">
</form>
Other HTML file:
<div id="here"></div>
The jQuery file:
var result = $("input[name=q]").val();
$("#here").text(result);
if you want to use it, read more about JavaScript and jQuery... (Google)

Related

How do you pass a Javascript variable through POST to use in Flask?

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 () {}'
}

Add # and ! to URL plus text from submitted search form

I need submitted text added to a URL from a search from. I found some code here Add text to parameter before sumbit form , which partially works but some of the text I need added includes #! and ? which translates to %23%21 and %3F when added to the url.
Code from stack overflow (best answer):
<form action="http://example.com/search" method="get" onsubmit="return addText();">
<input type="text" name="q" id="q">
<input type="submit">
</form>
<script>
function addText(){
document.getElementById("q").value += " BBBB CCCC"; // Whatever your value is
return true;
}
</script>
My URL needs to return something like this:
http://example.com/?search=TEXT#!summaryList?skipMake=true&skipModel=true
The url up to TEXT comes through (TEXT is the q value submitted from the form), but the #! before summary and ? before skip do not and the whole string is needed for the URL to function correctly.
Is there an easy way to make it work using the code above or would I be better off finding a PHP script?
Thank you!
Use encodeURIComponent() to encode your URL (to format #):
encodeURIComponent(myUrl)
Use decodeURIComponent() to decode your URL:
decodeURIComponent(myUrl)
var myUrl = 'search=TEXT#!summaryList?skipMake=true&skipModel=true';
console.log('Encode URL', encodeURIComponent(myUrl));
console.log('Decode URL', decodeURIComponent(myUrl));
Anything after # is not sent to the server. If you need to send it to the server, you will need to place it in it's own parameter (I used extra as the name). You will then need to also make sure that it is encoded properly, otherwise it could send that data as key/value as well.
http://example.com/?search=TEXT&extra=summaryList%3FskipMake%3Dtrue%26skipModel%3Dtrue
On your server side, you will then need to decode it, and grab the key/value pairs

how to read form data using javascript?

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);

Submit to external form with "action:javascript" using javascript

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&param2=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.

Get the URL generated from a form on submit with JavaScript

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>

Categories