I have created a form in HTML/CSS on my website.
Now, my idea is to give out links that would contain some string (basically like an affiliate link) and would like that string to be entered in a hidden form field to be submitted, or somehow else, have that string in the submitted data.
is there an easy way to do this?
There are two ways of approaching this, both of which use a GET variable in the link you distribute.
First off, let's assume that--for example's purpose--your special string is abc123. You would then distribute a link that follows the form http://example.com/my/form/?affiliate=abc123.
Assuming that, here are two solutions, one in PHP and another in Javascript.
PHP Solution
This one is fairly easy, as long as you're just setting a hidden field.
<input type='hidden' name='affiliate' value='<?= htmlspecialchars($_GET['affiliate'], ENT_QUOTES, 'UTF-8'); ?>' />
Update: Added htmlspecialchars() call to escape any input, to prevent security issues with users setting the GET variable manually.
Javascript Solution
HTML
<input type='hidden' id='affiliate-input' name='affiliate' />
Javascript
This solution relies on jQuery. If you want a pure JS solution, let me know.
var $_GET = {};
// When the page loads, set the input value
$(document).ready(function(){
setupGetVariables();
var affiliateId = $_GET["affiliate"];
$("#affiliate-input").val(affiliateId);
});
function setupGetVariables()
{
if(document.location.toString().indexOf('?') !== -1) {
var query = document.location
.toString()
// get the query string
.replace(/^.*?\?/, '')
// and remove any existing hash string (thanks, #vrijdenker)
.replace(/#.*$/, '')
.split('&');
for(var i=0, l=query.length; i<l; i++) {
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
}
The setupGetVariables() method was helped by this answer.
Related
for example
in
input name:1111,ss:1111,... => {name:1111,ss:1111,...}
A method of turning characters into objects
I can't find a good way to do it
So, you need this method or what?
if need method, it's simple: just get value of textarea, wrap text into quotes, add braces and call on it JSON.parse()
var textarea = document.getElementById("id-of-textarea");
var value = textarea.value;
var wrapped = "{"+value.replace(/(\w+)/g, '"$1"') + "}";
var result = JSON.parse(wrapped);
But, you should expect any values that user can input, so it's not good idea to use textarea for input some data.
As per the structure of you input I would suggest you to use different textfields to capture data rather than having it into a single textarea. Like this, you will be able to iterate over those and fetch their value and store them in form of an object or a map
Your HTML:
<input id="name" value="1111"/>
<input id="ss" value="2222"/>
...
Your script (JQuery/Javascript):
var data = {};
$('input').each(function () {
data[$(this).attr("id")] = $(this).val();
});
So basically, I have a lot of form fields (About 50 or so). Doing an AJAX request is going to be astronomically big, and it will most likely just make my code look ugly and unreadable. Is there anyway to gather all form data from a page and do an AJAX request?
If you had the names of the object for each input box like:
<input type="text" data-ajax="MyAjaxObjectName1" />
You could recurse through all of the inputs in this way:
var ajaxObject = {};
$('#myContainer input[type=text]').each(function() {
var inputObject = $(this).data('MyAjaxObjectName1')
ajaxObject[inputObject] = $(this).val()
}
That is the simplest way I can think of to recurse through every field that you have. Although, you'd have to update the HTML to include those attributes
The jQuery 'serialize' method:
Description: Encode a set of form elements as a string for submission.
See https://api.jquery.com/serialize/
I suggest to use $.serializeArray() on the form element.
It returns an array with each name and value of form inputs.
Docu & examples: https://api.jquery.com/serializeArray/
<input type="checkbox" name="Package1" value="packagename">
<input type="checkbox" name="Package2" value="packagename">
<input type="checkbox" name="Package3" value="packagename">
How to make any two checkboxes required for the user to submit the form. The user should not be able to submit the form unless he has checked atleast two checkboxes?
How to achieve that?
Rename checkboxes to name=package[] and values 1, 2, 3.
Then in PHP you'll have o condition (if you send form with GET method, just change POST to GET):
if (isset($_POST['package']) && count($_POST['package']) >= 2) {/* continue */}
If you want to validate it in browser (JS), than:
<script>
var i = 0;
$('[type="checkbox"]').each(function() {
if ($(this).is(':checked')) {
i++;
}
});
if (i <= 1) {
return false; // disable sending form when you've checked 1 checkbox in maximum
}
</script>
Add a class that refers only these checkboxes and then count how many are checked.
A quick and dirty way to validate the checkboxes using JavaScript:
JavaScript
checkCheckboxes = function() {
var numberOfCheckedCheckboxes = 0;
var checkbox1 = document.getElementsByName("Package1")[0];
var checkbox2 = document.getElementsByName("Package2")[0];
var checkbox3 = document.getElementsByName("Package3")[0];
if (checkbox1.checked)
{
numberOfCheckedCheckboxes++;
}
if (checkbox2.checked)
{
numberOfCheckedCheckboxes++;
}
if (checkbox3.checked)
{
numberOfCheckedCheckboxes++;
}
alert(numberOfCheckedCheckboxes >= 2);
}
DEMO: JSFiddle
This code isn't the cleanest block of code, however it does get the job done, and will return true if there are at least 2 checkboxes checked, and will return false otherwise. To make it cleaner, you can change the name value of each checkbox to the same name, such as "packages", and then use document.getElementByName("packages"), then use a for-each loop to loop through each element and check its checked state (I would provide a demo in JSFiddle or JSBin, however it seems that Google Chrome is blocking the script in that case). Using the for-each implementation would allow you to use the same amount of code, regardless of the number of checkboxes.
In HTML, you cannot.
You can impose restrictions in client-side JavaScript or in server-side processing of form data, or both. As usual, client-side restrictions are inherently unreliable and should be regarded as convenience to the user, not a reliable method of doing anything. Server-side processing depends on the server-side technology used.
I'm working on a website where I need to pass variables between actions. The variables are actually input fields. Here is some example markup.
<table>
<tr>
<td><input type="checkbox" name="major/1" value="1" checked /></td>
</tr>
<tr>
<td><input type="radio" name="major/2" value="1" checked /></td>
<td><input type="radio" name="major/2" value="2" /></td>
</tr>
</table>
Next Page
I basically want the values of those passed through a pagination system so it can be all used by the end. How could I accomplish this? Preferably without the use of a form surrounding the entire page.
The only way to pass input form elements from one page to another is through a form post. You can certainly pass data via session or similar, but that's not passing them in form elements.
I don't understand you reluctance to use a form. hidden fields are form elements. They're used in forms. That's their purpose. You want to use form elements but not use a form? That's pretty pointless.
EDIT:
I think your problem is that you don't truly understand the way a browser and server work. They only communicate via get and post commands. Therefore, the only way to send an input to the server is via a post, and a post must contain a form. That's how a browser sends it's data.
There's a lot of things you could do via javascript, but all of those things would be a lot messier than just doing your post.
I could see two possible methods. First, use hidden input fields inside the postback form. This will ensure variables from the current iteration get saved to the model on postback:
#Html.HiddenFor(model=>model.Field1)
The second would be to save whatever you need to TempData on the controller side and retrieve it on the next postback:
TempData["tempkey"] = MyModel;
I think that whether the best solution is one of these (or something else) depends on what your model and controller logic looks like.
The easiest way to accomplish this without using a form would be to use jQuery or javascript to grab the values and append them as url variables, assuming that is an acceptable approach. The other way would be to capture the values, send them ahead of time via ajax, and have your backend store them as session variables prior to following the link First, give the link a class name to listen to...
$('.navigation').on('click', '.pagelink', function(e){
e.preventDefault();
// url variables method
var theUrl = ($(this).attr('href')) + '?';
var ajaxUrl = $(this).attr('href');
// needed for ajax method
var theVals = new Object();
$.each('table input', function() {
// needed for ajax method
var theName = $(this).attr('name');
theVals[theName] = $(this).val();
// url variables method
theUrl = theUrl + theName + '=' + $(this).val() + '&';
});
// url variables method
theUrl = theUrl.substr(0, theUrl.length - 2);// removes ending ampersand
window.location = theUrl;
// the ajax session method
$.ajax({
url : [MVC path to store session variables - ex: /ajax/setsession/],
type : 'POST',
data : theVals,
success : function(data) {
if(data) {
// do something with data, like display success message
window.location = ajaxUrl;
}
}
});
Here is the situation: I have 2 pages.
What I want is to have a number of text links(<a href="">) on page 1 all directing to page 2, but I want each link to send a different value.
On page 2 I want to show that value like this:
Hello you clicked {value}
Another point to take into account is that I can't use any php in this situation, just html.
Can you use any scripting? Something like Javascript. If you can, then pass the values along in the query string (just add a "?ValueName=Value") to the end of your links. Then on the target page retrieve the query string value. The following site shows how to parse it out: Parsing the Query String.
Here's the Javascript code you would need:
var qs = new Querystring();
var v1 = qs.get("ValueName")
From there you should be able to work with the passed value.
Javascript can get it. Say, you're trying to get the querystring value from this url: http://foo.com/default.html?foo=bar
var tabvalue = getQueryVariable("foo");
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];
}
}
}
** Not 100% certain if my JS code here is correct, as I didn't test it.
You might be able to accomplish this using HTML Anchors.
http://www.w3schools.com/HTML/html_links.asp
Append your data to the HREF tag of your links ad use javascript on second page to parse the URL and display wathever you want
http://java-programming.suite101.com/article.cfm/how_to_get_url_parts_in_javascript
It's not clean, but it should work.
Use document.location.search and split()
http://www.example.com/example.html?argument=value
var queryString = document.location.search();
var parts = queryString.split('=');
document.write(parts[0]); // The argument name
document.write(parts[1]); // The value
Hope it helps
Well this is pretty basic with javascript, but if you want more of this and more advanced stuff you should really look into php for instance. Using php it's easy to get variables from one page to another, here's an example:
the url:
localhost/index.php?myvar=Hello World
You can then access myvar in index.php using this bit of code:
$myvar =$_GET['myvar'];
Ok thanks for all your replies, i'll take a look if i can find a way to use the scripts.
It's really annoying since i have to work around a CMS, because in the CMS, all pages are created with a Wysiwyg editor which tend to filter out unrecognized tags/scripts.
Edit: Ok it seems that the damn wysiwyg editor only recognizes html tags... (as expected)
Using php
<?
$passthis = "See you on the other side";
echo '<form action="whereyouwantittogo.php" target="_blank" method="post">'.
'<input type="text" name="passthis1" value="'.
$passthis .' " /> '.
'<button type="Submit" value="Submit" >Submit</button>'.
'</form>';
?>
The script for the page you would like to pass the info to:
<?
$thispassed = $_POST['passthis1'];
echo '<textarea>'. $thispassed .'</textarea>';
echo $thispassed;
?>
Use this two codes on seperate pages with the latter at whereyouwantittogo.php and you should be in business.