I am trying to add some additional tracking information to a site. I want to place a hidden field on every page that pulls in the URL of the initial page the person landed on, and submit that value to a form on another page, without ever leaving the landing page.
So for example, someone lands on a blog post and this hidden field submits that value to the form but the client never leaves the page. This person clicks through to various areas of the site, and decides to submit a form. That form submission will then contain the value of the initial page that was landed on. This would only be able to happen on the initial page though, because if it re-submits the value on every page the person visits it will not show the initial page the person started on.
Hopefully that makes sense. Any ideas, or am I pretty much just looking at buying expensive software that already does this type of thing?
$(function () {
$('#form-track').submit();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/schedule-service" method="post" id="form-track">
<input name="form-source" value="THIS URL IS DYNAMICALLY GENERATED" type="hidden">
</form>
Try this... the value will then be set in a cookie called "landingURL"
if (document.cookie.indexOf("landingURL=") < 0) {
URL = insert URL HERE...
document.cookie = "landingURL="+URL;
}
Related
I have a complex form; within it there's also an 'add more items' link that takes the user to another form-page (independent). What happens at the moment is that when they have edited the main form without saving it and they go to the independent form, when they come back to the main form page they have lost the edits.
<form id="form_1">
[...]
Add something else.
<input type='submit'/>
</form>
add-something-else page:
<form id="form_2">
<input type='submit'/ onsubmit='go_back_to_form_1'>
</form>
Saving everything in sessionStorage would be overkill (I think), and scripts like FormPersistence.js mess about with other functionalities of my form (i.e. Django formset). I have tried to achieve what I want by attaching this function to my 'add something else' button:
$.when(document.forms["form1"].submit()).then(function(){
window.location.pathname = '/add-something-esle/'
})
For some reasons, though, when I go back to form1 I see that the form wasn't saved. How can I achieve what I want?
A <form> is made up of input elements, and you can persist all the <input .../>s to session/local storage and recover them all on page reloads; I remember answering a similar question before; but here is the summary from that answer:
basically you set an event listener on input elements you want (i.e. query selector); make sure they have id (or something similar) unique because we are going to use it as key t store the value;
here is an example:
function persist(event) {
// `id` is used here
sessionStorage.setItem(event.target.id, event.target.value);
}
// you may use a more specific selector;
document.querySelectorAll("form input").forEach((formInput) => {
// `id` also used here for restoring value
formInput.value = localStorage.getItem(formInput.id);
formInput.addEventListener("change", persist);
});
this snippet will persist all <form> tag's inputs values into session storage;
you can also use more specialized selector in .querySelectorAll() to meet your need
Full page reloads clear all form state. You need a way to persist the state between full page reloads. You can use sessionStorage for that.
Am a newbie, a hardcore one.
I am in a need of reloading page with passing variables; so when the page is reloaded it would already have those variables before initializing some of the elements (as u can guess, those variables will be used there).
I need this because I am working with an old videoplayer, which can't be reset on-the-fly, the whole page has to be reloaded to re-initialize it with new params.
Also these variables cannot be passed through url, because they are too long.
I would be glad to see any help and to answer clarifying questions as well.
Thanks!
UPD1: There's no real need to delve into specifics of my code thus not posting it; Just imagine a simple page with a textfield and a button, where user enters a string, presses the button, then the page reloads getting that string into a global variable.
UPD2: Found this code on a related page:
$.ajax({
type: "POST",
url: "packtypeAdd.php",
data: infoPO,
success: function() {
location.reload();
}
});
That is how I post the data and reload. But how do I get it after reload then? How is this data accessible?
What about making a simple HTML form with attributes action="" and method="post" like:
<form action="" method="post"> <!-- in action specify where you want the content to be sent, the method speaks about his self -->
<input type="[type]" name="[name]"> <!-- in the name attribute define the name with which you can call the data in PHP via $_POST[name] -->
...some input fields...
...submit btn probably...
</form
Note: clicking the submit button automatically send the information to the page and redirects you to it. If you leave action empty like above it will redirect you to the same page (refresh it) and receive the data from the form.
Also if you don't want to use a form you can simply set cookies with PHP. For example:
setcookie($name, $value, $expireDate, $path(e.g "/");
And then just take information from the cookie with:
$_COOKIE[$name]
Note: in order to make cookies work, you need to refresh the page, so they can be set!
I am learning JavaScript to make a large form that stays completely local( no web server involved what-so-ever ). I am very familiar with PHP, but JavaScript is new to me. I have a form that has 100+ checkboxes and text fields. Some of the fields show as "[X] Other: [/text field/]" so when you select the "other" selection, you have to enter an input. I am making a validation to make sure you, A: enter text if you selected "other." B: make sure you selected the check box if you have entered text. When the validation function finds something wrong, it shows an alert box. Then, the page reloads( Not sure why ) and all of the data put into the form is wiped. So, I need to find a way to store this form data to load it upon page reload. I started with cookies, but then it came upon me that there is limits to the number of cookies and their sizes. What else can I do??? Please help!
Your submit button is reloading the page.
For example, if your form is set up like this:
<form name="main" method="post">
<!-- Lots of input fields -->
<button type="submit" id="subbutton">Submit!</button>
</form>
This is doing a POST to an undefined server because your form has no action
If you're sure that you don't need any server interaction at all, it's not necessary to use a form element
This means you can remove the form and submit elements from your page and use a button element instead
<!-- Lots of input fields -->
<button id="clientaction" type="button">Click me</button>
From MDN:
The HTML element represents a document section that contains
interactive controls to submit information to a web server.
<form action="/devilmaycry/register?action=addtocart" method="post">
<input type="hidden" name="user" value="<%=user%>"/>
<input type="hidden" name="pid" value="<%=pid%>"/>
<input type="submit" value="Add to cart" onclick="add();"/>
</form>
i am using the above code to submit a form and add a product to cart
the java code it calls is as follows:
else if(n.equals("addtocart"))
{
String user = req.getParameter("user");
int pid = Integer.parseInt(req.getParameter("pid"));
k=o.addintocart(user,pid);
if(k==1)
{
pw.println("<h3>Added to cart !!!<h3>");
}
else
{
pw.println("<h3>Errror , try again <h3><br>");
}
it does add the product to the table but it changes the jsp page ... i tried to use requestDispatcher but the URL has many parameters so i want something else through which i can retain the same page and update the table also
In order to stay on the same page you need to use AJAX rather than submit the form in the traditional way. HTTP works in a request-response fashion, so when the user submits the form, the browser expects to receive a new page in the response from the server, and will thus refresh the page and render the new HTML it receives.
You have two options here:
Stick with the traditional HTTP form submission request-response approach, and when you receive the request on the server to add an item to the card, after you add the item to the card, rebuild the URL of the page that is showing the information to the user. In this case it is important to use the 'Redirect-After-Post' approach (i.e. in the response to the form POST you put a redirect to the page). Otherwise if the user refreshes the page by pressing F5, the form data will be resubmitted again and the item added again to the cart.
Go for an AJAX approach. In the add() function, you need to submit the form using Javascript. If you are using JQuery it makes it very easy for you to do this. There are various questions / examples if you search around, such as the one here.
In the latter case you will need to change a bit how you process the information from your Servlet but its the only way to get the browser to stay on the same page (without reloading it). You also have the success and error handlers, which you can use to show a message on the screen to display the result.
I am writing code for a small webproject using js and jquery. In it, at some point, onclicking a button, i create a dialog. the dialog has a form within it with a name field and some number fields. I am supposed to check user inputs and send them to server, along with appending the name field to a list in the browser, to intimate user, one more item has been added. Two strange things are happening -
1) After posting the form, the dialog box closes on its own without me issuing a dialog('close') anywhere in the submit button handler.
2) The name entry doesn't get appended to the list. Its as if the whole page refreshes after the submit. With the original default entries of the list of names.
Anyone has any ideas on why this is happening? Would post some code for your aid.Please don't suggest to use Ajax instead. I think this reflects some fundamental flaw in my understanding of JS ways and would like to clear it first than just switching to some other technology.
<div id='dialog' title='Define New Matrix'>
<form name='form1' id='form1' method='post'>
<fieldset>
<label for="Name">Name</label>
<input type='text' name='nameofmatrix' id='Name' class='whitepanes'><br>
<label for="a11">a11</label>
<input type="text" name='a11' id='a11' class='whitepanes number-field'><br>
<label for="a22">a22</label>
<input type="text" name='a22' id='a22' class='whitepanes number-field'><br>
<button id='submit_button'>Submit</button>
<button id='cancel_button'>cancel</button>
</fieldset>
</form>
<p id='tip' style='color:red;'><i>All fields are required</i></p>
</div>
<script>
//#button_define is a button on whose clicking the dialog opens.
$('#button_define').click(function(){
$('#dialog').dialog('open');
$('#tip').html("<p style='color:red; font-size:small'>All fields are mandatory</p>");
});
$('#submit_button,#cancel_button').button();
$('#cancel_button').on('click',function(){
$('#dialog').dialog('close');
});
$('#submit_button').click(function(event){
event.preventDefault();
var name=$('input[name=nameofmatrix]').val();
//Validate is a function which returns a bool if validation proceeds correctly
var isCorrect = Validate();
if(isCorrect){
//if validated correctly then add to list
$('#form1').submit();
//$('#dialog').dialog('close');
$('#selectable').append("<li class='ui-widget-content'>",name,"</li>");
}
});
</script>
Its as if the whole page refreshes after the post. with the original entries.
That's precisely what happens. Though I'm not sure where you're submitting the POST request to since there's no action attribute on your form. But a standard non-AJAX request triggered by a form sends the request to the server and then renders the response from the server. If the response is this same page again, then this same page will be rendered again.
JavaScript isn't going to remember the state of the previous page when it loads this new response. Even if they're the same page, they're two separate responses from the server. So...
1) After posting the form, the dialog box closes on its own without me issuing a dialog('close') anywhere in the submit button handler.
The dialog isn't closing. After the page refreshes you're in an entirely new page context. It didn't close, it just hasn't been opened yet in this context.
2) The name entry doesn't get appended to the list.
There's nothing that would cause this to happen when the page loads, so in the new page context it doesn't happen. Your server-side code would need to include this content in the response to the POST request.
I think this reflects some fundamental flaw in my understanding of JS ways and would like to clear it first than just switching to some other technology.
Included in that misunderstanding is the fact that AJAX is part of JavaScript. (The "J" in "AJAX" stands for "JavaScript.") It's not "switching to some other technology." It's taking advantage of the capabilities of the technology you're already using. All AJAX does, really, is send requests and receive responses to/from the server without refreshing the page context.
You are not properly appending the name. The concatenation operator is not a comma, but a + in javascript:
$('#selectable').append("<li class='ui-widget-content'>" + name + "</li>");
Next, the form refreshes because you are submitting the form using $('#form1').submit();. If you do not want the page to refresh while submitting, use ajax.