How to do "HTML FORM action=location.replace('nextpage.html')"? - javascript

The title is actually a failed attempt to achieve my goal. Specifically, I want to
1. Go to a page from main.html (say, to page1.html).
2. Collect data in a form on page1.
3. On Submit, go to page2.html (which saves data to database using PHP and announces result).
4. Click on "Ok" and go back to main menu page.
Seems reasonable, right?
Step 4 above is my problem.
Things I've tried:
1. Invoke history.back on Ok click in page2.
This goes to page1 not main
2. Invoke javascript location.href=main.html on "Ok" in page2
This works and goes to main but clicking on Back button in main brings user back to page1. (not good)
3. Many variations of using javascript history.replace() in action= and onSubmit() of page1.
This works works and but inputs from form are not passed in query string to page2)
4. Clear history.
This appears to be impossible because of security concerns.
5. Programmatically composing the query string for history.replace (from form inputs) on page1.
This works but is very laborious, error-prone and horribly inelegant
Any suggestions will be greatly appreciated.
========= MY SOLUTION 4/8/16 ==============
I'm posting my final solution below for anybody that's interested.
In page1.html:
<script type="text/javascript">
function addarg(q,addend)
{
qnew = q + addend;
return( qnew );
}
function Next()
{
// GET INPUT VALUES FROM FORM
frm = document.forms["MainForm"];
first = frm.first.value;
last = frm.last.value;
phone = frm.phone.value;
// COMPOSE QUERY
query = "processForm.php";
query = addarg( query, '?first='+first );
query = addarg( query, '&last='+last );
query = addarg( query, '&phone='+phone );
location.replace( query ); // chain to processing page
}
</script>
<form action="javascript:Next()" name="MainForm" method=GET>
...
</form>
When history.back() is issued from processForm.php, it returns to Main Menu as desired.

It seems the easier way to achieve this is to place a simple <a href=main.html>Ok</a> on your page2.html.
Then associate a flag (maybe a cookie) on this main.html which "instructs" page1.html to clear its form elements if it is not called by main.html, but from a "back" button (by refreshing meta, for example, or by loading page1.html#randomnum, where randomnum is a value you find real time to force your browser understand this is not the "old" page1.html but a "new" page1.html, helping browser not to get this from cache but from web).
The principle is: if page1.html is called by "back", it have to be a "clear" page1.html, not showing any data input user eventually entered.

Related

How to use information from the URL to click on specific button?

I'm working on a group project for a class, and we have a webpage that is split into different tabs, so it is only one webpage, but appears to be different pages using Jquery so the page doesn't have to reload when switching between tabs. The problem I am having is that one of the tabs has a form to get information from the user, then after the user clicks the submit button, the info is sent to the database using php, causing the page to reload. Then depending on if the information was successfully sent to the database, there will be either "success" or "invalid" appended to the end of the URL. If the user submits this form, we want them to automatically come back to this tab on the reload, and I have tried doing this by using a script like this:
<script>
document.getElementById("baseTab").click();
window.onload = function() {
var theurl = document.location.href;
if (theurl.includes("success") || theurl.includes("invalid") {
document.getElementById("infoTab").click();
}
};
</script>
The baseTab is the tab we want to load whenever someone first loads the webpage, unless they have just submitted the form on the infoTab page. This code structure works on a simple test webpage I run on my computer, but when I try to push it to our project repository, it will only do the "baseTab".click, and not click the "infoTab" button even if theurl includes "success" or "invalid". I tried doing it without the window.onload(), but that doesn't work either. Also, if I do
if (theurl.includes("success") || theurl.includes("invalid") {
document.getElementById("infoTab").click();
}
else {
document.getElementById("baseTab").click();
}
then neither of the buttons get clicked. If their is an easier way to do this or you see where I am going wrong, any help would be appreciated. Thanks!

page reloads on chrome extension message send?

So I'm running a data collection project by injecting a html form into a third party website, via a chrome extension, which instructs users to describe the data they see and submit it to my server.
For some bizarre reason, however, whenever the user clicks the "submit" button to send the form contents to the background page (and from thence to the server), the underlying page reloads, and, not only that, but it reloads with the contents of the form I injected showing up in the url after reload. Which is kind of bizarre behavior.
I don't know if this is something in my code, or even if it's something in the underlying web page's code (maybe it redefines chrome.runtime.sendMessage or something as some kind of anti-extension technique?!!?). I'd really like to stop this behavior if possible... does anyone have any ideas?
The relevant parts of my code, stripped down a little:
var cururl = window.location.href
var codestring= "[A HTML FORM TO INJECT]"
var raformvalues = {};
function codeValues() {
$.each($('#mainCoding').serializeArray(), function(i, field) {
raformvalues[field.name] = field.value;
});
}
function sendValues() {
let pageinfo = {"page": document.documentElement.outerHTML,
"url": cururl,
"title": document.title,
"timestamp": String(Date.now())};
let tosend = $.extend({"type": "doctype"}, pageinfo, raformvalues);
chrome.runtime.sendMessage(tosend);
chrome.storage.local.set({'lasturl': pageinfo.url});
$("#pgcodediv").empty();
location.href = cururl; // note: I added this line to try to stop the reloading and url/changing behavior. behavior is the same with and without it.
}
function appendCodingInfo() {
$("#headerID").append(codestring);
$( ":checkbox, :radio" ).click( codeValues );
$( ":text" ).change( codeValues );
$( "#codingsubmit" ).click(sendValues);
}
appendCodingInfo()
when the user hits the submit button (#codingsubmit, of course), the message gets passed and the background page handles it correctly, but the page refreshes unbidden, and the contents of raformvalues show up in the URL of the refreshed page (i.e., when I call window.location.href from the console the contents of that object show up as parameters to a get request, i.e., http://url?prop=value&prop2=value2 -- no clue why.
If you click a button with type="submit" in a form, by default browser will reload the page after the form is submitted.
To prevent the page reloaded, either replace type="submit" with type="button" or call e.preventDefault() inside sendValues handler.
Appendix:
According to MDN, the default value for button is submit.
type
The type of the button. Possible values are:
submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
reset: The button resets all the controls to their initial values.
button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
menu: The button opens a popup menu defined via its designated element.

javascript history.back losses the search result

Page A:
$(document).ready(function () {
bindData();
});
function bindData() {
$('#searchbtn').bind('click', function () { SearchResult(); });
}
function SearchResult() {
ajax call...
}
Page A HTML:
<input type="button" id="searchbtn" />
Page B Details---> this page comes after selecting a specific search result from page A search list
Back<br />
Now when I go back to the Page A I can see my search criteria's as they were selected but the result Div is gone. What I am trying to do is I want the search list to stay when the Page comes back.
I think what I can do here is some how call the searchbtn click event again when the page comes back so the list will come-up again. Can anyone tell me how to fire the searchbtn click event only when the page comes back from Page B. or point me in the right way of doing this..
Thanks
The Browser Back button has long been problematic with AJAX. There are scripts, workarounds, and techniques out there (depending on the framework that you want to use).
Since it appears that you are using jQuery (based on your posted JavaScript syntax), here is a link to another Stackoverflow post regarding back button jQuery plugins.
history.back() will return you to the last URL visited, meaning that any ajax calls made during the user's visit will not be automatically repeated. Your browser may automatically restore your form selections, but the SearchResults() function is only called by a click event, not a selection event.
You can bind URLs to ajax states using a framework like sammy.js. That way, history.back() would take you to a URL associated with SearchResults().
function bindData() {
var chkinput1 = $("input:checkbox[name=x]:checked").length;
var chkinput2 = $("input:checkbox[name=y]:checked").length;
if (chkinput1 > 0 && chkinput2 > 0) {
SearchResult();
}
$('#searchbtn').bind('click', function () { SearchResult(); });
}
I know this is the worst way to achieve this result but I think instead of using any other plugins to add complexity we will go with this for now. If anyone else is looking for the same question let me tell you again this is not the best practice as on returning back to the history we are calling the search result again depending upon the cached input selection of checkboxes and generating the whole ajax call again to display the list. On the first request I am caching the list and setting sliding expiration so its not taking anytime to comeback and so everyone lives happily.

Strange issue with form onsubmit and javascript xmlhttprequest

I have a strange issue with my code I can't seem to figure out. I'm relatively new to js and utilizing http requests to retrieve json data however I've been able to come up with code that works, for the most part.
Essentially the workflow is as follows: I have a user enter some form field values and select the submit button. Onsubmit the the apiCall() function is called which then calling the createXMLHttpRequestObject() and constructApiURL(searchtype) functions creates, populates, and sends the xmlHttpRequest Object via the proxy to the search api url. Once the result is returned the handleResults() function is called which then parses and displays the results in the apropriate div container using the handleResultsContainer() function.
Everything works when I step through the code via firebug. The object is created, sent via the proxy to the search api, the results are returned and displayed but once the focus returns to the function onsubmit(event) {callApi();} and the contents then clear!?! I don't know if the page is reloaded or something else is going on.
Now if I change the initial trigger from a form submit to a button onclick it works without issues. The user selects the button, the search results are retrieved and displayed until the user selects the button again at which point the results are cleared and the new results are displayed. The problem is that I have to hard code the parameters I would normally be getting from the form.
Has anyone experienced this or sees something with how the code is being read by the browser that could cause this? My Pseudo code is below.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function createXMLHttpRequestObject() {
-- code to create the XMLHttpRequestObject based on browser type --
}
function constructApiURL(searchtype) {
-- code to create the api url using the form values & proxy url --
}
function handleResultsContainer () {
-- code to create/remove search results display div
}
function handleResults(jsndata) {
-- code to parse and display results here --
}
function callApi() {
-- code to create XMLHttpRequestObject, populate it, and send it --
}
</script>
</head>
<body>
<form id="basicform" name="mashsearch" onsubmit="callApi()">
-- Code for user input fields which are then used by constructApiURL --
<input type="submit" id="searchbtn" value="Search!"/>
</form>
//Div displaying a Search Results Loading… message which is hidden/displayed//
<div id='loadingDiv' style="display:none">Search Results Loading...</div>
//Div used to display the search results
<div id='json'></div>
</body>
</html>
Change your onsubmit to :
onsubmit="callApi();return false;"
Alternatively you could add return false to the bottom of your callApi() method and change your onsubmit to be onsubmit="return callApi()"
If you do not the page will submit and reload as its normal behaviour would.

redirecting to next page

I wrote a javascript function to go to a particular page if it came from a particular page.
Function:
function proceed()
{
if( document.referer == "http://abcd.com/index.php?action=SignUp")
{
return document.location.href = "http://abcd.com/editprofile.php?action=editprofile";
}
}
Submit button for a form in current page(b):
What i want is to go through a sequence of pages a->b->c , where a is previous , b is current , and c is next in my case. b has a form, on submitting values to the form, it should also call the javascript function and then go to the page c.
Can anybody help me find out where is the mistake? Any help would be highly appreciated. Thanks.
Since you have a form I guess there's also some php/cgi script that will handle the form's data!?
In that case your form won't continue to that script if you override your submit button via javascript in such way that it loads another page (other cases like validation do work that way, of course).
So
Your submit button has spaces next to the onclick attribute: onclick = "javascript... should be onclick="javascript....
Your function proceed() should return true for the submit to perform.
Even after all syntax correction, there's still something odd. After all, you can only give one "next page" functionality to your submit button. So what should the form call:
your php or cgi script? Then you can build a redirect to page "c" into that one.
your page "c"? Then what do you need the form for?
both, but independently? In that case I suggest a javascript popup from proceed() displaying page "c" and returning true so the form continues with its script.
To be more accurate you will have to provide more of your application's code.
Solution seems to be the following. Use the submit attribute for your button:
<button type="button" onclick="proceed(); alert('You are not authorized to execute this action!');">Click Me!</button

Categories