I have a javascript function which redirects to another page with the parent page contents. My issue is when i used form.submit,I am getting redirected to error page. When I tried with window.open, it works. Please help me what is the exact difference between these two. And whether form.submit also works here? Please see the Javascript code below. When I uncomment the window.open and comment the frm.submit, it works.
function Check() {
var frm = document.forms[0];
var target = frm.target;
var action = frm.action;
var HPPSFeild='<%=HPPSURLFeild.ClientID%>';
var HPPSValue=document.getElementById (HPPSFeild).getAttribute('value');
frm.target = "_blank";
frm.action =HPPSValue;
alert (frm.action);
frm.submit();
frm.target = target;
frm.action = action;
//window.open(HPPSValue);
}
form.submit();
window.open('url');
is same when you using form submit method=GET
because window.open(); always makes GET request
but if you are using POST method to submit your form then it different from window.open() method.
Form.Submit will pass input type controls with value to the action URL defined in form and windows.open will open new window with given URL
if you want value to be passed to new page I will suggest you to use form.submit method
<form method='post' action='URL'>
<input type=""
....
....
....
</form>
In script when you write form.submit it will open URL and value of input type will be passed in query string
See this below code
<form action="file.php" method="post" target="foo" onSubmit="window.open('', 'foo',
'width=450,height=300,status=yes,resizable=yes,scrollbars=yes')">
That onSubmit is helps to call any server side event or javascript function (like Post to a method) , but the windos.open is helps to open next page (same as Response.Redirect in c#`,Like GET a Method )
You need to change
//,......code
frm.submit()
{
window.open(HPPSValue);
}:
//,......code
Related
I'm having the weirdest problem right now. I have this JS code:
function CreateChat() {
var chatName = document.getElementById("chatName").value;
window.location.href = "https://localhost:44321/CreateNewChat/CreateChat?ChatName=" + chatName;
}
Thing is, as it is, I can't make it work. It obviously should be calling a controller method, but it just won't work. If I hit that url with the project running and put anything at the end of it, like https://localhost:44321/CreateNewChat/CreateChat?ChatName=TestName, that test name variable will get to the controller without a problem. If I hardcode to the code the "TestName" instead of passing the chatName variable I define earlier, it will get to the controller, no problem. Hell, if I debug the script, the chatName variable gets loaded correctly with my input, and if I console.log the url it will show up correctly (in fact, I can copy/paste that url and it will hit the controller method correctly). But, as the code is presented above, it will never, by any means, hit the controller. It will reach that point, and cut the execution as if there was an error in the JS code. Do you guys have any ideas on this? It's driving me mad, really.
Just in case, this is how I define the text input in the HTML:
<input type="text" required class="form-control" id="chatName" aria-describedby="nameHelp" placeholder="Name your chat!">
Edit: encodeURIComponent on the chatName doesn't work either.
try using window.open with _self instead:
window.open ('https://localhost:44321/yadayada','_self',false);
You have a submit button (and I assume this button is inside a form)... when you click on the submit button the form is submitted to the submit action of the form, this is the default behavior for the submit action.
Now if you don't want your page to be submitted, you can change the button type to button:
<button type="button" onclick="CreateChat()" class="btn btn-primary">Create a New Chat!</button>
Alternatively if you actually need a submit button then you need to prevent the default behavior in order to change window.location:
function CreateChat(event) {
e.preventDefault(); // <-- don't submit the form
var chatName = document.getElementById("chatName").value;
window.location.href = "https://localhost:44321/CreateNewChat/CreateChat?ChatName=" + chatName;
}
You need to pass the event to CreateChat function:
<button type="submit" onclick="CreateChat(event)" class="btn btn-primary">Create a New Chat!</button>
I have a script that gets throught parameter the new page andthe redirects to this page.
my function:
function openPage(page) {
alert("Pressed the button!"); //working
window.location.href = "http://localhost:8080/Edas/" + page; //not working
}
and my button:
<button id="btnViewMonthlyPurchaseReport" onclick="openPage('monthlyPurchaseReport.html')">View Monthly Purchase Report</button>
I think my problem is in my base URL ("localhost:8080/Edas/"), but really don't know how to fix it.
Thanks!!
Out of the comment the problem was that the button was inside of a form element.
The problem is that a button without a type attribute will submit the form, which would (not sure if in every browser) result into the described problem, that the window.location.href = ... has no effect and that the page would be redirected to the url defined in action. If action is not defined in the form then it is the the current url.
You have different options to solve this:
You could move the button out of the form (if it would not affect usability)
Change the type of the button to button (<button type="button">View Monthly Purchase</button>) - the default behavior without a type is submit
You could place a return false; at the end of your openPage function to prevent the default behavior (this is similar to 2. but with the difference that the button would still be marked as a submit button which could be important for usability in some situations).
Do this:
JS
var url = window.location.href;
var dirnames = url.split('/');
function openPage(page) {
alert("Pressed the button!"); //working
window.location.href = "http://"+ dirnames[2] +"/Edas/" + page;
}
I imagine you're correct in saying that your issue is in the URL.
Where is your monthlyPurchaseReport.html? If it is in the same directory as where the html with your button is, simple use:
function openPage(page) {
alert("Pressed the button!");
window.location.href = page;
}
My problem was: my button was wrongly inside a form, which #t.niese clearly explained why.
Thank you all for the help!
In my html document I have this:
<button onclick="doFunction()" type="submit" ...>Button</button>
The function looks like this:
doFunction() {
var goToThisUrl = "www.spring_controller_method.com?redirectUrl=this_page";
window.location.href = goToThisUrl;
}
The the url in the doFunction() is the url of a Java Spring controller method. In that method it manipulates the database and returns a string to redirect to the page it came from: return "redirect:" + redirectUrl.
The problem is that the button doesn't work. When I click the button, the page refreshes but the data in the database isn't manipulated. The reason I know this isn't a problem with the spring controller method is because of two reasons:
I have a breakpoint in the controller method and it isn't being hit.
When I take the same doFunction() code and run it on the Chrome developer console, the controller method breakpoint is hit, and the data in the database is changed.
Is there any idea as to why this would be happening?
Remove type submit from button like
<button onclick="doFunction()" type="button" ...>Button</button>
type="submit" is used for form submission that's why onclick not working.
Add return false; to prevent the default form submission.
doFunction() {
var goToThisUrl = "www.spring_controller_method.com?redirectUrl=this_page";
window.location.href = goToThisUrl;
return false;
}
I have a scenario where a user when clicks on a link, they are directed to a page in which I want to add a code to fetch a variable and redirect to another page.
i.e. user clicks on click here
on sample.tpl I want to write a code to redirect him to another page
<script>
window.location="http://example.com/?page_id=10"
but I want to send a variable too on this new link without appending it to the URL for security reasons.
How can I do it with some safe procedure?
Do ask me questions if it is not clear.
You could create a form with method="post", a hidden input with the value you want to pass and a submit button styled as a regular link (if you want to also manually send the form).
Then just submit the form manually or programmatically through the submit() method
Example (with automatic redirect after 3 seconds after page load)
http://jsbin.com/avacoj/1/edit
Html
<form method="post" action="http://mydomain.com/" id="f">
<input type="hidden" name="page_id" value="10">
<noscript><button type="submit">Continue</button></noscript> /* see below */
</form>
Js
window.onload = function() {
var frm = document.getElementById('f');
setTimeout(function() {
frm.submit();
}, 3000);
};
As a side note you may consider to insert a submit button inside <noscript></noscript> tag so the redirect will be possibile even when js is not available on the user device, so the page is still accessible.
Further to Fabrizio's answer someone has written a javascript function which will allow you to build the form and send it via POST at runtime.
POST is like GET (Where the variable is appended to the url) except the variable is sent via the headers. It is still possible to fake a POST request so you must perform some kind of validation on the data.
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
Used like so:
post_to_url("http://mydomain.com/", {'page_id':'10'}, "post");
Source: JavaScript post request like a form submit
I have HTML two forms, one that submits data upon entry to a database using PHP, the other directs the user to a paypal payment page, my problem is that the user would have to submit both forms which of course I do not want them to have to do. Is there anyway to use one submit button for two forms?
(Javascript is welcome)
You should be able to do this with JavaScript:
<input type="button" value="Click Me!" onclick="submitForms()" />
If your forms have IDs:
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
If your forms don't have IDs but have names:
submitForms = function(){
document.forms["form1"].submit();
document.forms["form2"].submit();
}
A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:
var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));
document.forms.payPal.submit();
You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.
In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)
If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.
I recommend you use/generate a single request which you can transact server-side.
The currently chosen best answer is too fuzzy to be reliable.
This feels to me like a fairly safe way to do it:
(Javascript: using jQuery to write it simpler)
$('#form1').submit(doubleSubmit);
function doubleSubmit(e1) {
e1.preventDefault();
e1.stopPropagation();
var post_form1 = $.post($(this).action, $(this).serialize());
post_form1.done(function(result) {
// would be nice to show some feedback about the first result here
$('#form2').submit();
});
};
Post the first form without changing page, wait for the process to complete. Then post the second form.
The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).
I didn't test the code, though.
If you have a regular submit button, you could add an onclick event to it that does the follow:
document.getElementById('otherForm').submit();
if you want to submit two forms with one button you need to do this:
1- use setTimeout()
2- allow show pop up
<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);
}
</script>
<form target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>
javascript doesn't submit two forms at the same time. we submit two forms with one button not at the same time but after secounds.
edit: when we use this code, browser doesn't allow pop up.
if you use this code for your software like me just set browser for show pop up but if you use it in designing site, browser is a barrier and code doesn't run.