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);
});
Related
This is the HTML page, I am working on:
<div class="container">
<form id="script-approval-form" action="" method="post">
<h3 class="title-submitted">Script Approval</h3>
<h5> Below you will find the script that needs to be approved before being used: </h5>
<fieldset>
<textarea id = "textarea-script-approval" class="textarea-approval"
type="textarea" tabindex="1" required autofocus></textarea>
</fieldset>
<fieldset>
<input class="email-box" placeholder="Your Email Address (if clarification is needed)"
type="email" pattern=".+#COMPANY.com"
oninvalid="this.setCustomValidity('E-mail MUST end with #COMPANY.com')"
value="{{ user_info.email }}" tabindex="2" required>
<button id = "what" class="submit-btn" type="submit"><a id = "submit-lnk" class="submit-link"
href = "#"
>
Submit for Approval</a>
</button>
</fieldset>
</form>
</div>
It's a form with a pre-filled text-area and a submit button. The text-area is automatically filled in with this JS script:
const url = window.location;
const urlObject = new URL(url);
const script = urlObject.searchParams.get('authorize')
var decodedScript = window.atob(script);
document.getElementById("textarea-script-approval").value = decodedScript;
It gets the encoded base64 URL parameter (EXAMPLE: url.com/script_approval?authorize=DScdsaCs) and puts it as normal text in the page textarea. However, if the user clicks the submit button/link, he will be sent to another page. I need to pass the script in text form to the next page as well, so for this reason I have to:
Get current textarea value
Encode it in base64
Change href link to /script-sent?script=${encoded_string}
The next page will be opened with the same URL parameter
I will then use my old JS script to decode and get the string into my other pages textareas/input places
What I tried:
<script>
document.getElementById("submit-lnk").onclick = function() {
var script=document.getElementById("textarea-script-approval").value;
var encodedScript = window.btoa(script);
document.getElementById("submit-lnk").href = `/script-sent?authorize=${encodedScript}`;
return false;
};
</script>
I know for sure that the encodedScript contains the correct value. The problem comes after that when I change the href. Even though its written syntactically correct, the page just reloads or nothing happens. I tested the templated string and it shows fine as well. Can someone please give me any guidance? Thank you!
You can remove the anchor tag from within the button.
<button id = "what" class="submit-btn" type="submit">
<!-- remove this -->
<a id = "submit-lnk" class="submit-link" href = "#">Submit for Approval</a>
</button>
Instead of replacing the href you can simply redirect to the page directly
<script>
document.getElementById("submit-lnk").onclick = function () {
var script = document.getElementById("textarea-script-approval").value;
var encodedScript = window.btoa(script);
// instead of replacing the href you can simply redirect to the page directly
window.location.href = `/script-sent?authorize=${encodedScript}`;
return false;
};
</script>
Looks like the action on the form is blank. Try entering the path to the next page there.
Or use local storage to pass data in browser cache.
You should be able to do what you need to do with jQuery
jQuery('#what').click(function(){
jQuery('#script-approval-form').attr('action','insert link here');
jQuery(this).click();
};
I am trying to submit a form via ajax using the post method and a FormData object.
Here is a simplified version of the JavaScript:
var form=…; // form element
var url=…; // action
form['update'].onclick=function(event) { // button name="update"
var xhr=new XMLHttpRequest();
xhr.open('post',url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var formData=new FormData(form);
formData.append('update', true); // makes no difference
xhr.send(formData);
xhr.onload=function() {
alert(this.response);
};
};
The form has:
a button (type="button" name="update") to run the script
no action and method="get"
My PHP script has the following:
if(isset($_POST['update'])) {
print_r($_POST);
exit;
}
// more stuff
print 'other stuff';
When I try it, the PHP falls through to the rest of the code, and I get the other output, rather than what I expect from the print_r statement.
I have tried the following variations:
new FormData() (without the form). This does work if I add the update data manually.
new FormData(form). This does not work, whether I add the update manually or not.
changing the form method to post.
Firefox, Safari & Chrome on MacOS; all current versions.
The from itself looks something like this:
<form id="edit" method="post" action="">
<p><label for="edit-summary">Summary</label><input id="edit-summary" name="summary" type="text"></p>
<p><label for="edit-description">Description</label><input id="edit-description" name="description" type="text"></p>
<p><label for="edit-ref">Reference</label><input id="edit-ref" name="ref" type="text"></p>
<p><label for="edit-location">Location</label><input id="edit-location" name="location" type="text"></p>
<p><button type="button" name="update">OK</button></p>
</form>
What should I do to submit the get this to work?
No jQuery, please.
The content type when sending a FormData object is multipart/form-data not url encoded.
Further more the proper boundary must be set for the request, which the user is unable to do. For this XMLHttpRequest sets the correct content type with the required boundary.
So all you have to do is not set the content type and it'll work.
var xhr=new XMLHttpRequest();
xhr.open('post',url,true);
//xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");<--don't do this
var formData=new FormData(form);
formData.append('update', true); // makes no difference
xhr.send(formData);
xhr.onload=function() {
alert(this.response);
};
Change the name of the button to something other than "update" (and change it in your form['update'].onclick... as well). I think its clashing with the value you are trying to set on the FormData to trigger the PHP code.
I have a page where Ajax updates the feed every once in a while. Under each post there's a textarea for a reply. JQuery/Ajax can post the reply to the database without any problems when the textarea is active. I press the submit button and everything goes well.
However, if I click somewhere else on the page and the textarea becomes inactive, the submit button doesn't work anymore like it should: it submits the form to root and doesn't run the Ajax function.
Can you figure out what's wrong in my code? Thank you for your help!
There are as many forms as there are messages on the pages. The forms look like this:
<form class="reply-form">
<textarea id="reply-11123" name="comment" class="plain-editor"></textarea>
<input type="submit" class="submit" value="Reply" />
<input type="hidden" value="URL HERE" name="url" />
</form>
Ajax code (at <head>) looks like this:
<script type="text/javascript">
$(document).ready(function()
{
$('.reply-form').on('submit', function (event) {
event.preventDefault();
var $form = $(this),
message_data = $form.find('textarea[name="comment"]').val(),
url = $form.find('input[name="url"]').val();
var postData = {};
var prefix = 'data';
postData[prefix + '[message]'] = message_data;
var posting = $.post(url, postData);
});
}
</script>
If your forms are being added to the page dynamically then you need a different event binding that will attach itself to all current and future forms. The current binding you have is called a direct binding, but what you really need is a delegated binding. A different usage of on() will give you that:
$(document).on('submit', 'form.reply-form', function (event) {
...
});
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.
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.