Add post variable to form with jQuery - javascript

I have the below code which adds the value of the parameter to my form by default. This works well but if you set the form to post then it no longer works. What is the best approach to setting this value?
var request = {};
var pairs = location.search.substring(1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
request[pair[0]] = pair[1];
}
var getfirstname = document.getElementById('firstname');
var firstname = request['firstname'];
getfirstname.setAttribute('value', firstname);
<form method="get" action="search">
<input type="text" name="firstname" id="firstname" />
<input type="submit" alt="Go" value="Go" border="0" />
</form>
www.example.com?firstname=john
<form method="get" action="search">
<input type="text" name="firstname" id="firstname" value="John" />
<input type="submit" alt="Go" value="Go" border="0" />
</form>

The answers you've gotten so far probably don't address your issue correctly. If you are setting the value of an input from a form that is submitted with the method set to "GET" then the parameters are available in the querystring and accessible by the browser - that's why this works:
var pairs = location.search.substring(1).split('&');
But when you change the method to "POST", the posted data is no longer available to the browser (client-side). You need to retrieve the posted data on the server-side. If you are using PHP you would do something like this (very very simplified version):
<?php
$firstname = (isset($_POST['firstname'])) ? $_POST['firstname']:'NA';
?>
<form method="get" action="search">
<input type="text" name="firstname" id="firstname" value="<?php echo $firstname; ?>" />
<input type="submit" alt="Go" value="Go" border="0" />
</form>
Hope that helps. If you can explain a little more about what you are trying to do I could add something to address an ajax via jQuery option.

If you want to set the value of a field set the value property not the value attribute
getfirstname.value = firstname;

Instead of setting the value attribute, set the actual value:
getfirstname.val(firstname);

Related

How to set a variable js with input (form) tag html / PhP

I want to know if i can set a variable when the player finish the him form.
E.g:
<form>
First name:<br>
<input type="text" name="firstname" value="Pedro">
<br>
Last name:<br>
<input type="text" name="lastname" value="Pinto">
<br><br>
<input type="submit" value="Submit">
</form>
And when he submit, execute a function on JS, what saves the firstname and lastname to a variable.
And i want know in PhP, if it's possible too thanks.
JS solution:
In this solution, the data is processed client side. Be careful though if you are saving any of this to your server since users can use their browser to manipulate the data in unintended ways.
HTML:
<form>
First name:<br>
<input type="text" id="firstname" value="Pedro">
<br>
Last name:<br>
<input type="text" id="lastname" value="Pinto">
<br><br>
<input type="submit" value="Submit" onclick="myFunction()">
</form>
JS:
function myFunction() {
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
}
PHP solution:
In this solution, the data is processed server side. Here, you will clear out any JS variables because this causes a new page to load when you do this. So, generally, do not do this if you need to continue working on page after saving your variables. Also, note that the HTML forms use "name" instead of "id" when passing a post.
HTML:
<form action="MYPAGE.php" method="post">
First name:<br>
<input type="text" name="firstname" value="Pedro">
<br>
Last name:<br>
<input type="text" name="lastname" value="Pinto">
<br><br>
<input type="submit" value="Submit">
</form>
PHP:
<?php
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
?>
AJAX Solution: The third way to do it which is sort of a hybrid is to use AJAX. In this solution you use JavaScript to collect the variables, then you POST the data to another .php file without navigating away. This way you don't clear out any of your JavaScript variables, and you can write the data to the server. Then whatever content is generated by your targeted PHP page can be loaded into the page you are already on by inserting it into the element you target with your result.
NOTE: This sample code uses jQuery.
HTML:
<form>
First name:<br>
<input type="text" id="firstname" value="Pedro">
<br>
Last name:<br>
<input type="text" id="lastname" value="Pinto">
<br><br>
<input type="submit" value="Submit" onclick="myFunction()">
</form>
<div id="MYTARGETELEMENT"></div>
JS:
function myFunction() {
var firstname = document.getElementById('firstname').value;
var lastname = document.getElementById('lastname').value;
$.ajax({
type:"POST",
url: "MYPAGE.php",
data: {
firstname:firstname,
lastname:lastname
},
success: function(result){
$("#MYTARGETELEMENT").html(result);
}
});
}
PHP:
<?php
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
echo("Post Received By Server");
?>
var username = $("input[name=firstname]").val();
var lastname = $("input[name=lastname]").val();
This is how you get the value of both input field with Jquery. The first part gets your input by it's name, .val() gets the value from that input.
How to get it in PHP:
Add a name to the submit button:
<input type="submit" name="submit" value="Submit">
Then use this code:
<?php
if(isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
}
?>

Dynamic URL from user input to search

What I am trying to accomplish: When a user inputs dates, number of adults ect it would dynamically add the info via javascript to the URL within the url variables. This is what I have so far: ( I am a Noob but trying to make it work )
<script type="text/javascript">
$(function () {
$('#submit').click(function() {
$('#button').click(function(e) {
var checkInDate = document.getElementById('checkInDate').value;
var checkInMonthYear = document.getElementById('checkInMonthYear').value;
var checkOutDate = document.getElementById('checkOutDate').value;
var checkOutMonthYear = document.getElementById('checkOutMonthYear').value;
var numberOfAdults = document.getElementById('numberOfAdults').value;
var rateCode = document.getElementById('rateCode').value
window.location.replace("http://www.Link.com/redirect?path=hd&brandCode=cv&localeCode=en&regionCode=1&hotelCode=DISCV&checkInDate=27&checkInMonthYear=002016&checkOutDate=28&checkOutMonthYear=002016&numberOfAdults=2&rateCode=11223");
window.location = url;
});
});
Ok, so first things first: You probably don't need to do this at all. If you create a form and add a name attribute to each input, then the submission automatically creates the URL for you. Fixed value fields can be set to type="hidden".
For this to work you need to use the "GET" method.
<form action="http://www.Link.com/redirect" method="GET">
<input type="hidden" name="path" value="hd"><br>
<input type="hidden" name="brandCode" value="cv"><br>
<input type="hidden" name="localeCode" value="en"><br>
<input type="hidden" name="regionCode" value="1"><br>
<input type="hidden" name="hotelCode" value="DISCV"><br>
<input type="text" name="checkInDate"><br>
<input type="text" name="checkInMonthYear"><br>
<input type="text" name="checkOutDate"><br>
<input type="text" name="checkOutMonthYear"><br>
<input type="text" name="numberOfAdults"><br>
<input type="text" name="rateCode"><br>
<input type="submit">
</form>
Clicking "Submit" changes the URL to the desired one.
If this does not suit your needs, you can replace parameters in the URL by following the advice in this SO answer: Answer Link
This is much better than trying to re-implement URL manipulation on your own.

Is there a modification of this that can make the form value appear?

So, here's the form
<form action="/missions/basic/3/index.php" method="post">
<input type="hidden" name="file" value="password.php" />
<input type="password" name="password" /><br /><br />
<input type="submit" value="submit" />
<input type=button value="Get Value" onclick="printIt()" /></form>
I have these methods here to try to get the value to appear.
function printIt(){
for (i = 0; i < document.getElementsByName('password').length; i++) {
var x = window.alert(document.getElementsByName('password')[i].value());
window.alert(x);
}
}
I want to know what I can change in those last two methods to get the value to appear.
The function document.getElementsByTagName() returns an array, not one element, so changing your code to window.alert(document.getElementsByName('password')[0].value); should get the first item's value. The first item will most likely be the element in your form you're looking for.

Pass an input box value through to a var in the js doc to be used

Is it possible to pass the value of an input from a form into a var to be used in a function.
for example:
<input type="text" id="userID" name="userID" placeholder="Enter user ID" style="width:200px;" />
<input type="submit" value="search" />
So the userID would be passed into :
var userId = null;
I am looking to use this as a way for a user to input their userID in to the flickr api call.
$.getJSON('http://api.flickr.com/services/rest/?method=flickr.photos.search&getSizes&api_key=feb7e93d9a90e9a734787bea9be81440&user_id='+userID+'&has_geo=1&extras=geo&format=json&jsoncallback=?', mapImages);
I had a look around and came across
var userId = document.getElementById("userID").value;
This does not seem to be working though.
I have tried:
<form type="post" onsubmit="loadImages(); return false;">
<input type="text" id="userID" name="userID" placeholder="Load user images" />
<input type="submit" value="Get Flickr images!" />
</form>
Using the function:
function loadImages()
{
var userId = document.getElementById("userID").value;
}
Is this along the right track or totally off?
getElementById is case-sensitive.
In your HTML you use "userID" and in your JavaScript "userId".

How to set the value of a form element using Javascript?

I have a simple form like this one:
<form ENCTYPE="multipart/form-data" action="upload.php" method="POST">
<p>UPLOAD FILE: <input type="file" name="file1"> <br /></p>
<input type="submit" value="Upload">
<input type="hidden" name="email" id="email" value="">
</form>
I have to set the value of the hidden field to an email like "email#email.com".
I can obtain this value from adding a querystring parameter by external iframe like:
<iframe name="email#email.com" src="index.html?email=email#email.com">
Ok. But how can I set value="" to value="email#email.com"?
I know have to use javascript, but I dunno how to deal with the var.
document.getElementById('Id').value='new value';
answer to comment:
try this:
<input type="" name="email" id="email">
<iframe id="frm" name="email#email.com" src="index.html?email=email#email.com">
</iframe>
<script>
document.getElementById('email').value = document.getElementById('frm').name;
</script>
then you can change adopt it. change type to hidden and etc.
If your script is executed from the document inside the iframe, you can do this :
var getUrlParameter = function(name, defaultValue) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( document.location.href );
if( results == null ) return defaultValue;
else return decodeURIComponent(results[1]);
};
document.getElementById('email').value=getUrlParameter('email');
As you've labeled this question as jQuery You can use $('#Id').val('new value'); But don't forget to add jQuery Library.

Categories