I have a form on one page (one.html) that has a javascript funtion as its submit action:
<form id="the_form" action="javascript:myfunc('input_text');" method="post">
<input type="text" id="input_text" name="input_text">
<input type="submit">
</form>
I have another page (two.html) with a button that when clicked I would like to submit the form on one.html, along with a value for input_text. Is this possible with ajax or any other way for that matter? If possible, I would also like to redirect to the page I submit the form too although this is optional.
this code should be on second form:
$(document).ready(function(){
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
return query_string;
}();
if(QueryString.preview){
console.log(QueryString.preview);
}
});
this sample read query and parse.
So, first you can send your form as GET, like http://asd.com/?param1=a¶m2=b
and then just use QueryString.param1 and QueryString.param2 in your another page.
Based on the comment under this post, I'm asuming you want to send it info from pageA to a php file that returns a resulting file:
download file using an ajax request
How to download file from server using jQuery AJAX and Spring MVC 3
Downloading file though AJAX POST
Based on the comments under your question, I'm assuming you want to post from pageA to new page (pageB) with javascript.
Quick answer: Not possible (in a userfriendly way).
More useful answer:
It requires a bit more work, but based on the info given, this might work:
Submit the form from pageA via either GET or POST to pageB
Create hidden fields (<input type="hidden"/>) and fill those with the corresponding GET or POST values. This might be easier with a serverside language like PHP, but isn't impossible in JS
Set a hidden input and name it like <input type="hidden" id="linkedSubmit" value="1" />
Create some javascript to see if $('#linkedSubmit').val()==1, if so continue to submit the form on pageB
This isn't the prettiest solution and on a slow connection the user will see page hopping. And because it is javascript it's clientside, thus a user can manually change the value to 1 and trick your page. This should not become a security problem.
Related
I have a problem. i have a website am working on. I have created a php script to fetch all the receipts id from the data base using pagination, and all works fine. But the problem is every receipt id, i have added a link so as when clicked a specified results will be displayed without loading the page.
The links are like :
G145252 G785965 and when each link is clicked will show http://test.com/?go=any#G145252
When clicked the page will not reload.
So what i need help with is how can i get G145252 from the url after when the link is clicked using javascript and print it using html?
i need to pass the value to the process.php as a $GET value so the i can load the receipt detail of the clicked id with out reloading the page.
Please note: there are a lot of get values before the #value i need to get out of the url address.
You should not be using the fragment identifier section of the URI for server side related tasks. This section is intended for client-side manipulation only. More info here.
You can use some other means such as query parameters to access this data.
For example, turn this:
http://test.com/enter code here?go=any#G145252
Into this:
http://test.com?go=any&hash=G145252
Then:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
console.log(getQueryVariable("go")); // any
console.log(getQueryVariable("hash")); // G145252
NOTE: I know this is not the exact answer to your actual problem, but the question itself is presenting a bad practice scenario, thus my suggestion.
Credits for the getQueryVariable function goes to CSS Tricks: https://css-tricks.com/snippets/javascript/get-url-variables/?test=3&test2=5
Let's assume you're using jQuery.
Change all your links so that they have a common class name, lets say 'hashClick' e.g
My Link
To get the hash part when clicked, add a click event handler for those links
$('.hashClick').click( function(event) {
event.preventDefault();
var url = $(this).attr('href');
var hash = url.substring(url.indexOf('#')+1);
alert("You clicked " + hash);
// or at this point you can do an AJAX call
// or GET request to process.php with hash as one of the parameters
})
suppose this is the link
http://test.com/?go=any#G145252
to get the hash value
window.location.hash
which will return you #G145252
and
window.location.hash.substring(1) will return you "G145252"
I have a multi page form.
Page One has a few fields that get passed into the second form, via GET method, and it auto fills the first four fields of the second part of the form.
Page two has a few more questions, and when you submit it, it submits into our CRM(vanillaSoft), and leads to a thank you page.
My current issue:
I want to be able to take an affiliate link, such as:
http://something.com/step-one.html?AFFILIATE_ID=#affid#&SUB_ID=#s1#
I need to dynamically populate the AFFILIATE_ID parameter with a unique transaction ID, and the SUB_ID with a unique ID as well.
I currently have two fields on my first page with hidden fields, ex:
<input type="hidden" name="SUB_ID">
<input type="hidden" name="AFFILIATE_ID">
But that isn't working. I need this date to be sent into the CRM I use.
Any advice?
Thanks!!!
Your current setup will work if you set your form submit method to GET. You probably have it set to POST.
Setting your form method to GET will put those hidden fields in the URL, like you are expecting.
On the last form, set that one to POST (to POST to the server).
You can grab the Query string with JavaScript, like this:
var getParamValue = (function() {
var params;
var resetParams = function() {
var query = window.location.search;
var regex = /[?&;](.+?)=([^&;]+)/g;
var match;
params = {};
if (query) {
while (match = regex.exec(query)) {
params[match[1]] = decodeURIComponent(match[2]);
}
}
};
window.addEventListener
&& window.addEventListener('popstate', resetParams);
resetParams();
return function(param) {
return params.hasOwnProperty(param) ? params[param] : null;
}
})();
How can I get query string values in JavaScript?
You could also send both POST and GET methods. But POST can be done only on server side, where JavaScript is Client-side scripting language.
<form method="POST" action="form.php?a=1&b=2&c=3">
PHP -> Send both POST and GET in a form
How to read the post request parameters using javascript
I need to create a registration and a login page with javascript and localstorage and I am very confused with a few things.
Let's say all the info that needs to be saved is a string, and I want to have an array of these strings stored locally that can grow at any time and as long as it isn't cleared it keeps growing. I need to be able to parse through that array later and compare the strings with the string that will be inputted in the login page. How do I create an array of strings in local storage and access it? I tried the following: localstorage.token = JSON.stringify(token); but then every time there's a new token it re writes it. I read a few posts but I am still a bit confused.
Thank you.
Ok, even though it's still rough at the edges, here's some proof of concept:
HTML:
<form>
<input name='abc' value='' />
<input name='def' value='' />
<input name='ghi' value='' />
<button type="button">Save</button>
</form>
JS:
$(function() {
var $form = $('form'),
$saveBtn = $('button'),
myForm = {},
myFormJsoned = localStorage.getItem('myform');
if (myFormJsoned) {
try {
myForm = JSON.parse(myFormJsoned);
$.each(myForm, function(i, obj) {
$form[0][obj.name].value = obj.value;
});
}
catch(e) {
localStorage.removeItem('myform');
}
}
$saveBtn.click(function() {
localStorage.setItem('myform',
JSON.stringify($form.serializeArray()));
});
});
The point is, when this button is clicked, the form is serialized into an array with that helping jQuery method (of course, using serialize would be even more simple - if unserialize were available). Then it's JSONed and stored into a single field of localStorage.
When you load the page, the process is reversed: JSON is parsed into Array of Objects (the result of jQuery.serializeArray), this AoO is inserted into a form back again (using convenience of $.each).
What's the concept, you may ask? My point is that it is certainly possible to work with localStorage as it were a single-string container - like cookie. But then again, I'd consider using separate container for each of the fields:
localStorage.setItem('myform_abc', $form[0].abc.value);
localStorage.setItem('myform_def', $form[0].def.value);
localStorage.setItem('myform_ghi', $form[0].ghi.value);
Well, token is a string in your case, so if you stringify it, its value will change.
You don't need to, so just do :
localStorage.token = token;
You should use JSON.stringify only for object types:
var t = {a: 5, b: 'Tom'};
// set
localStorage.special = JSON.stringify(t);
// get
var u = JSON.parse(localStorage.special);
console.log(u.a); // 5
console.log(u.b); // 'Tom'
EDIT: About your registration/login process : http://jsfiddle.net/NAzZ5/
Ok, so in my rails app on one of the pages I needed to pass a Javascript variable so that it was available to rails. Now one runs server side and one runs client side so I know this is very difficult. I looked to the internet and found a solution that involved dynamically creating a form in a function included in my external javascript page.
Basically, a form with a hidden field was made using document.createElement statements and the hidden field was given the value of what I wanted to pass to rails and then form.submit() is called so that the form is submitted. the form was given a method of post and it was given a path to go to. So when submit it called the page redirects to another page with the hidden field now in the params hash and accessible by rails with params[:param].
This worked great for a while, until we started using session to keep track of a logged in user. After clicking the button to be redirected with that dynamic form the session gets cleared. The only thing I found online about sessions being cleared is when rails detects a CSRF it clears the session.
So could what I'm doing cause rails to detect a CSRF and thus clear my session? is there any other reason the session might be cleared that anybody knows of? Also, without ajax (because I'm just not up to screwing with that, it doesnt play nicely.) is there another good way im missing to pass a javascript variable (it has to be javascript, I'm using a javascript function to get the users current location) so that it is available to rails? (I'm thinking rather than javascripting the form, I might just make a hidden form right on my page, although this is a little less elegant because anybody looking at the source can see it and wonder why its there and screw with it)
if anybody is interested, below is the code for my dynamic form function.
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path); //page to go redirect to when form submitted
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
//after form is submitted params is available by params[:location]
hiddenField.setAttribute("name", 'location');
hiddenField.setAttribute("value", params )
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
}
In any form requests, and ajax the CSRF token must be passed through. You need to create a hidden field in the form with the name authenticity_token. Then you need to grab the value from the meta tag:
<meta content="some_token_value" name="csrf-token" />
Like so:
var token = "";
var tags = document.getElementsByTagName("meta");
for(var i = 0; i < tags.length; i++) {
if(tags[i].name == "csrf-param") {
token = tags[i].content;
}
}
Then simply drop that in the value of the hidden tag, much like you did for the location value.
you can add an erb line in your javascript file:
var csrf_token = '<%= form_authenticity_token %>';
then in your requests, add 'authenticity_token' : csrf_token in the post-data.
I have a search function that returns an arraylist of objects to my form. I am iterating through the list using JSTL's foreach tags.
<c:forEach items="${searchResults}" var="contact" varStatus="loop">
<div style="padding: 5px;">
${contact.firstName} ${contact.lastName}
<br>
${contact.primaryPhone}
<br>
//Is this the proper way to set up the url?
View Contact
</div>
<br>
</c:forEach>
When the user clicks the link inside each row, the row index is passed to the querystring and at this point I would like to show a div that contains additional information about the user.
I have a javascript function that I use to display the div and center it on the screen bla bla bla, but my question is how do I refresh the page with the index loaded into the querystring and then fire my javascript function?
I considered using:
<c:if test="${not empty param.id}">
//Check if id in querystring is available and if so, display popup
</c:if>
To check if there was an index available in the querystring, but I don't think there is a way to fire my function from within a JSTL tag.
Should I be doing something on the server side when I request back to the servlet rather than trying to handle this on the client side? I just figure its a waste to requery my database and set another request parameter, when I already have the information I need stored in a parameter than I am using to display my list anyways.
You can embed a script tag within the parameter check, and run whatever you want within it. For example, set some variable that you can test later on, when the page finished loading.
Or, if you embed the parameter check late enough in the page, just invoke your function.
<c:if test="${not empty param.id}">
<script>
runSomeFunction();
</script>
</c:if>
The solution I eventually came up with is to check for my id parameter in the querystring each time the page loads (with javascript)
function init(){
console.log("Contacts page loaded.");
//Loads popup if 'id' is present in the querystring.
if(getQuerystring('id', 'null') !== 'null') {
showCenteredDiv('popup');
}
};
The function I use to check the querystring is:
//Search querystring for a specific parameter. Second arg is the value to display if its not found.
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null) {
return default_;
} else {
return qs[1];
}
}