Replacing GET with POST - javascript

Here I am trying to redirect new page and I want to send a variable. It uses GET.
How can I do it with POST?
window.location.href = 'start.php?userid='+userid;
start.php
<?php
$user_id=$_GET['userid']; //should be post
?>

You will have to submit the data to the server, not just redirect the browser.
In your case, as it looks like you want full page refresh anyway just create a form on the fly:
var oForm = document.createElement("form");
oForm.method = "POST";
oForm.action = "start.php";
var oInput = document.createElement("input");
oInput.name = "userid";
oInput.value = userid;
oForm.appendChild(oInput);
document.body.appendChild(oForm);
oForm.submit();

You need to declare a fake form in HTML and a link that will trigger javascript to submit the form, like below
<form action="start.php" method="post">
<input type="hidden" name="userid" value="[userid]">
</form>
<script type="text/javascript">
function submitlink()
{
document.forms[0].submit();
}
</script>
<a class="buttondown" onclick="submitlink()">Submit Link</a>

I think this answer may help you:
How do you force a web browser to use POST when getting a url?
You just need to create a form on demand using javascript to send data with POST method when clicking a link.
So basically it's just this part:
<script type="text/javascript">
function submitAsPost(url) {
var postForm = document.createElement('form');
postForm.action = url;
postForm.method = 'post';
var bodyTag = document.getElementsByTagName('body')[0];
bodyTag.appendChild(postForm);
postForm.submit();
}
</script>
this is my post link

I was in the same problem you had. If you are using jquery.redirect.min.js as your jquery plugin, You can use as below. It gives you POST method.
$().redirect("myPhp.php", { name: "John" });
All you need is to download jquery.redirect.min.js file from here and link it with your php file, and use as above. That's it. Hope I helped.
Works fine for me.

You can post form by html tag and . Otherwise, see "jQuery.post" for async post.
For the 1st case you create FORM tag, put INPUT type="hidden" inside and set its value that will be posted.

Related

Document.write on a different html page

Hmm is it possible to document.write on other html page?
For example I create a two html page, the first page have a textfield and submit button. I enter a text in a textfield and after I click the submit button the value of the textfield will be transfer to the second html page and load the html page and write the value on it.
Just a beginner to javascript so bear with me please :D
You can do this by using Query String.
window.location = "Pass.aspx?variabletopass=test";
Use this line of where you are trying to redirect your page,and value of your textfield in query string.
Since you're using pure javascript and HTML, I assume server-side things are out of the picture. So Felix Kling's comment is actually, I think, a good way to go. Here's one way you could use localStorage to make this work:
/* index.html */
<form action="result.html" onsubmit="submit()">
<input type="text" id="input">
<input type="submit" value="Submit">
</form>
<script>
function submit() {
var input = document.getElementById("input").value;
localStorage.input = input;
}
</script>
/* result.html */
<div id="result"></div>
<script>
document.getElementById("result").innerHTML = localStorage.input;
</script>
Without using php you can document.write() submitted text on other html file as follows.
<html>
<script>
var a = document.location.toString();
var b = a.slice(a.indexOf("?")+1,a.length);
var c = b.split("&");
for(i=0;i<c.length;i++){
document.write(c[i]);
}
</script>
</html>
If you are working on Single page Application you can quite easily achieve this, by just storing the value in correct scope.
If you are on multiple page application you can achieve this by any of the following ways:
sending parameter in url
storing value in localStorage/sessionStorage
storing it in cookie(Not recommended)
sending it to server in forms param(Not recommended)

Send single hidden field with form using javascript

Currently I'm working with ASP.Net and a nested form. My problem is,
that ASP.Net only allows one form per page, but I need a kind of sub-form
to redirect to another page.
My idea was to create a submit using JavaScript, but I don't get how to set the
content of the post, which will be send.
For example I've tried to use the following code:
<div>
<input type="hidden" value="ABCDE" />
<input title="Send Form" onclick="this.form.method = 'post'; this.form.action = 'https://externpage/url'; this.form.submit();" type="submit" />
</div>
My problem is, that the content of the request should only be the hidden fields containing ABCDE and not all fields on the page. How can i achieve this using JavaScript and HTML?
Thanks a lot!
Use FormData() to do the encoding.
sendForm=(e)=>{
let data = new FormData();
let hidden = document.querySelector('button').parentNode.firstChild.value;
data.append('hidden',hidden);
let xhr = new XMLHttpRequest();
xhr.onreadystatechange=()=>(xhr.readyState == 4) ? console.log(xhr.response) : null;
xhr.open('POST','http://yoururl.com');
xhr.send(data);
}
document.addEventListener('DOMContentLoaded',()=>{
document.querySelector('button').addEventListener('click',sendForm);
});

Sending form data to HTML Page and Retrieving it with Javascript without any PHP/Python

I've read a few articles and a question thread on sending form data to another html page, but the solutions didn't solve the issue for me.
Basically, I have a form with a bunch of data:
<form id="registration" name="registration" action="register.html" method="POST">
In register.html, I tried accessing an input text field with id and name as "username" with this:
var x = document.getElementById("registration").elements.namedItem("username").value;
The console stated that it cannot read property of null. How can I access these values with Javascript only? Frameworks are fine but not PHP /Python.
I'm sure that none of this can be safe, so use caution.
If you don't care about the info being super obvious, then you can make the action of the the form the new page you want, and the method can be 'GET'.
EDIT: I should mention this will go through the url, as such
domain.com?someKey=someValue&someOtherKey=someOtherValue
On the new page, you can parse the url for the query string for everything.
You can grab that stuff out of the 'href' property from the location.
window.location.href
// * Credit for this puppy goes to theharls, nice and fast
var params = window.location.search.slice(1).split("&");
//=> ["say=Hi", "to=Mom"]
Another option on (modern ?) browsers is Local Storage.
Use javascript to to set things like,
localStorage.setItem('foo', 'bar');
Great reference for local storage here.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I ran into something like this the other day. Turns out you can just get the values with jQuery.
var userName = $("input[type=text][name=username]").val();
Just put it into a function that's called in the form's onsubmit.
<script>
function getFormData() {
var userName = $("input[type=text][name=username]").val();
// Do what you want with the data
return true;
}
</script>
<form id="registration" name="registration" action="register.html" onsubmit="return getFormData();" method="POST">
<input type="text" name="username" />
</form>
However, this doesn't keep the data when you load the next page. To do that, just commit the value into sessionStorage.
function saveFormData() {
var userName = $("input[type=text][name=username]").val();
sessionStorage.setItem("user", userName);
return true;
}
And then on the next page (the one you're calling resgister.html) you can use this code to retrieve it.
var userName = sessionStorage.getItem("user");
I hope this helps!
A webpage can't receive POST data. Send it using method="GET" instead, then retrieve it on the target page using JS as follows:
<script>
var params = window.location.search.slice(1).split("&");
// params is ["say=Hi", "to=Mom"]
</script>
You can easily target the selectors by querySelector. The value will no longer be null.
<form id="registration" name="registration" action="register.html" method="POST">
<input type="text" class="username" value="abcdefg">
</form>
<script>
var x = document.querySelector("#registration .username").value;
//check your code in devtools
console.log(x);
</script>
jsfiddle

How to open an https website on a button click javascript?

The piece of code I am using is
window.location.href = "https://www.google.com/";
But i stays on the same page,doesn't go to google.com.I was able to get this work with an http page.
window.location.href = "http://www.tutorialspoint.com/mongodb/mongodb_insert_document.htm";
This is the complete code for the same
<form name="form1" onsubmit="submis()" action="/post.php" method="POST"
and the function submis()
function submis()
{
window.location.href = "https://www.google.com/";
}
and post.php
if (!empty($_POST))
{
//saving the contents of the post request to a file.
}
<script>
function goto(){
window.location.href = "https://www.google.com/";
}
</script>
in html code go to google
it works
I was able to make this work by changing the code to,
window.top.location.href="https://www.google.com"

Bug in IE when using Javascript to change a form action, when method=get and URL contains a hash

I'm using Javascript to change a form's URL when you submit the form. If that URL contains a hash string (#), then Internet Explorer ignores it and just submits to the part of the html before that. Firefox and Chrome are fine.
Demonstration:
<script type="text/javascript">
function changeURL() {
var myform = document.getElementById('myform');
myform.setAttribute("action", "page2.html#hello");
return false;
}
</script>
<form id="myform" action="page1.html" method="get" onsubmit="changeURL()">
<input type="submit">
</form>
If I change the method to a "post" then it's fine. If I use a "get", IE lands on page2.html but without the #hello in the URL.
This happens regardless of if I use jquery or only javascript, tried each of the following:
myform.action = "page2.html#hello";
myform.attr("action", "page2.html#hello");
myform.get(0).setAttribute("action", "page2.html#hello");
Any suggestions (assume that I have to keep the method as a 'get', and that I must use a hash in the URL, and that I must use Javascript to change this action dynamically)?
Testing on my own in IE8 reveals that it does insist that the hash (#hello) come after the query string (?foo=bar) in a URL. Sadly, your form doesn't do this for you and there's no way to force it to do so when submitting the form.
Try encoding the hash in the form instead:
<script type="text/javascript">
function changeURL() {
var hidden = document.createElement('input');
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "hash");
hidden.setAttribute("value", "hello");
var myform = document.getElementById('myform');
myform.setAttribute("action", "page2.html");
myform.appendChild(hidden);
// return false;
}
</script>
<form id="myform" action="page1.html" method="get" onsubmit="changeURL()">
<input type="submit">
</form>
And at the top of page2.html, extract it back out:
<script type="text/javascript">
var qs = window.location.search.substring(1);
var qsarr = qs.split("&");
for (var i=0; i<qsarr.length; i++) {
var tarr = qsarr[i].split("=");
if (tarr[0]==="hash") {
window.location.hash = tarr[1];
}
}
</script>
I believe that IE just behaves differently with the hash and I don't think it is is meant to be used in this manor.
No javascript in the following will produce the same results...displays in FF and not in IE
<form action="#test" method="get">
<input type="text" value="test" />
<input type="submit" />
</form>
At least you know it's not a javascript problem. I lied about the question mark lol oops.
In the end we decided we could just update window.location.href to go to the new location rather than submit the form. This might seem like an odd answer, but actually the way we were handling our form meant this wasn't a problem to do. i.e. we were disabling all our form fields (hence no querystring being appended to the URL normally), then generating one of several different SEO-friendly style URLs based on what the form fields contained, then updating the form action and submitting the form. So now we do all that but don't bother submitting the form, just change the page location.

Categories