Get form field names with javascript or php? - php

Is there a way to return a list / array of all the field names that are contained within a form? I.e if i made a form with 10 fields ('name', 'email' etc...) on submit i can determine what the element names are?

JavaScript
The raw JS way to do that is:
const inputs = document['<your form name>'].getElementsByTagName("input");
for (const input in inputs) {
if (inputs[input] && inputs[input].name) {
console.log(inputs[input].name);
}
}
PHP
Yes. They are all in the superglobals $_GET (for all of the GET variables), $_POST (if your form has method="POST"), and $_REQUEST ($_REQUEST is, by default Environment, Get, Post, Cookie, and Server (in that order) you can read more here).
If you want to just get the names, then you can use array_keys on any of the above.

In JavaScript we can get the name attribute of each form element like this:
$('form').on('submit', function () {
var names = [];
$.each($(this).find('input, textarea'), function () {
names.push(this.name);
});
});
This gathers the name attribute of each input or textarea element in the form and puts them in an array, names.
Note that .on() is new as of jQuery 1.7 and in this case is the same as using .bind(): http://api.jquery.com/on
In PHP you can loop through each of the $_GET or $_POST variables:
<?php
$names = array();
if (isset($_POST) && !empty($_POST)) {
foreach ($_POST as $key => $val) {
//$key is the name you wanted, and $val is the value of that input
$names[] = $key;
}
}
?>
And again, the $names variable is an array of all the names of form elements.
Update
If you want to create an associative array of names : values in JS you can do this:
$('form').on('submit', function () {
var names = {};
$.each($(this).find('input, textarea'), function () {
names[this.name] = this.value;
});
});
Now you can access the names variable like this:
alert(names.email);//this will alert the value of the input who's name is `email`

jQuery serialize:
http://api.jquery.com/serialize/
$('form').submit(function() {
alert($(this).serialize());
return false;
});

the $_POST array contains all the field that have been submitted if the form's method was post. If the method was get then $_GET has the form fields (as well as any other get params that happen to be in the URL)

With JQuery you can know it by selecting the input elements and using attr('name');
With PHP :
you can traverse $_GET, $_POST with foreach
You can also get the list of keys by using array_keys($_POST);

:input selector will find form elements in client
http://api.jquery.com/input-selector/
demo http://jsfiddle.net/JBsbL/
$('form').submit(function() {
var inputList = [];
$(this).find(':input').each(function() {
inputList.push(this.name);
})
alert(inputList.join(', '))
return false;
})​

Yes, they are the keys of your $_POST e.g:
$_POST['name'] = 'whatever name was in the form';
You can do a print_r($_POST) to see all keys.
(or $_GET depending on your forms submit method)

These solutions fully solve your problem, but they wroted as use jQuery. jQuery is not a populer library nowadays. We can solve with pure JavaScript more easily.
[...document.querySelectorAll("form input, form textarea, form select")].map(el => el.name)

Related

Simulate html form POST using ajax/jquery

I want to read all the post variables and their content from a form and post them using jquery's "$.post()".
First of all, this won't do the job:
$.post("myServer.com/test2.php", $('#myform').serialize())
because it would only send one variable which I'd have to parse on the php side.
Here is how I'd start:
function doIndirectPost() {
variableWithTheFormPOSTData = {};
$("#IdOfMyForm :input").each(function() {
variableWithTheFormPOSTData[$(this).attr("name")] = $(this).attr("value");
}
document.getElementById("IdOfMyForm").submit();
$.post("myServer.com/test2.php", variableWithTheFormPOSTData);
}
and then I'd like to use $.post() to post the data seperated in multiple variables (just like a normal form submit would do it...
I read somewhere, that you could do that like this:
$.post('myserver.com/test2.php.php',{
var1: content1,
var2: content2
}
But I want it to be dynamic. This part:
var1: content1,
var2: content2
should autmatically contain all variable names and values of the form.
In the end I'd like to be able to get all POST variables like this:
foreach ($_POST as $key => $value)
{
echo $key . "= " . $value;
}
Serialize doesn't send only one variable, it sends name value pairs of all input elements in the form. So
$("#IdOfMyForm").on("submit", function () {
$.post("myServer.com/test2.php", $("#IdOfMyForm").serialize(),
function(dataFromServer){
//server sent a response now do whatever you want to do after form has been submitted
//or submit form regular way $("#IdOfMyForm").submit();
}
);
return false;
});
Should work. Just remember to set name attribute of every input/select element in form.
Have you tried it using JQuery's Ajax instead?
Like this answer here:
jQuery Ajax POST example with PHP

Passing array elements in javascript as parameters for an AJAX POST request

I've taken some input values from the user and I want to post these values as arguments in my AJAX request so I can add an entry to a database in PHP:
My function in JS is:
function reqAdd()
{
var tablename = $("table").options[$("table").selectedIndex].value
var fields = new Array();
var inputs = $$("input.postfields");
new Ajax.Request(
"process.php?type=add&table="+tablename,
{
method: "post",
parameters:
onSuccess: functionName,
onFailure: ajaxFailure
}
);
}
The variable inputs contains all the input fields I need so I just need to extract their values but how can I place them into the parameters section if they have no key? they are just values.
Use Form.serializeElements() which takes an array of elements, $$("input.postfields") and turns it into a querystring or object ready for POSTing.
So
var inputs = $$("input.postfields");
inputs = Form.serializeElements(inputs); //add this line
And
parameters: inputs,
Personally I like passing objects to my Ajax requests, and skipping the submit inputs so I would pass an options object to serializeElements()
inputs = Form.serializeElements(inputs,{hash:true,submit:false});
http://api.prototypejs.org/dom/Form/serializeElements/

$_POST another attribute than value

Is it possible to get some other attribute's value than attribute named value with $_POST
example: <option value="FusRo" name="Dah"></option>
Normally when i use $_POST['Dah'] The php grabs FusRo (the value).
But I want to grab another attribute's value than attribute named value. I hope you understand.
If I cant use $_POST to grab some other value, is it some other comand i can use?
Another example:
If i use
<option value="FusRo" name="Dah"></option>
Can I get the "Dah" with $_POST instead of "Fusro" ?
You can put your other value in a hidden field:
<input type="hidden" name="DahHidden" value="somethingelse" />
Then get it from $_POST with:
$_POST['DahHidden']
If this value has to dynamically change based on what's in the <select>, then you'll need JavaScript.
If you want to grab the keys from $_POST (i.e. the name attributes from your form fields), you can iterate over $_POST like this:
foreach( $_POST as $key => $value)
echo $key . ' => ' . $value; // Will print Dah => value (eventually)
Note that iterating over $_POST will likely produce more output than just that one form element (unless 'Dah' is the only thing you submitted in your form.
The only way is to use JavaScript to modify the posted data, or even simpler use jQuery
then it would look like something like this :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.js"></script>
</head>
<body>
<form name="skyrim" id="skyrim">
<input type="text" value="FusRo" name="Dah" data-name="dhovakin" data-race="kajit" />
<form>
<script>
$('#skyrim').submit(function( e ){
data = {};
url = 'http://sandbox.local/testpost.php';
e.preventDefault();
$('input, textarea', this).each(function(){
var pcs = $( this ).data();
var ename = $( this ).attr('name');
if(undefined == data[ ename ] ){
data[ ename ] = {};
data[ ename ]['_'] = $(this).val();
}
$.each(pcs, function(k, v){
data[ ename ][k] = v;
});
});
$.ajax({
url : url
,data : data
,type : "POST"
}).done(function(){
});
});
</script>
</body>
</html>
The above code will add all the attributes starting with data- to the post .
the result of the above is :
Dah[_] FusRo // default value
Dah[name] dhovakin // data-name
Dah[race] kajit // data-race
$_POST only gives you the names of the field, and their corresponding value, nothing more.
No, you cannot post anything else then the "value" of an inputfield.
You could hack your way into it by using javascript. Something like
document.getElementById('FORM').onsubmit = function() {
document.getElementById('FIELD').value = document.getElementById('FIELD').customAttribute
}
However, if javascript is disabled, your form will submit the wrong values. Not a really solid solution.
Sounds to me more like you will have to redefine your values, I can't really imagine why you would like to alter this behavior.

How to send Javascript/jQuery array over URL paramter to PHP?

Here's my script, this works fine... send_array_to_other_page.html
$(function(){
//DECLARE ARRAY
var arr = new Array();
var i = 0;
$('#form').submit(function(e){
e.preventDefault();
var value = $('#box').val();
var index = arr.length;
var list = '';
//ADD VALUE TO ARRAY
arr[index] = value;
//OUTPUT VALUES IN ARRAY
for (var index in arr){
list+=index+': '+arr[index]+'<br/>';
$('#arrLength').html(arr.length);
}
//DISPLAY ARRAY
$('#display').html(list);
$('#form').get(0).reset(); //RESET FORM
});
$('#submit').click(function(){
window.location = 'send_array_to_other_page_2.php?list='+arr;
});
});
This doesn't. It outputs Array content lost. Id also like to point out the the url of this page is send_array_to_other_page_2.php. Its missing the ?list=
<?php
$arr = $_GET['list'];
echo 'The contents of the array are still... <br/>';
if(isset($arr)){
print_r($arr);
} else {
echo 'Array content lost';
}
?>
$(function(){
//DECLARE ARRAY
arr = new Array();
var i = 0;
$('#form').submit(function(e){
e.preventDefault();
var value = $('#box').val();
var index = arr.length;
var list = '';
//ADD VALUE TO ARRAY
arr[index] = value;
//OUTPUT VALUES IN ARRAY
for (var index in arr){
list+=index+': '+arr[index]+'<br/>';
$('#arrLength').html(arr.length);
}
//DISPLAY ARRAY
$('#display').html(list);
$('#form').get(0).reset(); //RESET FORM
});
$('#submit').click(function(){
window.location = 'send_array_to_other_page_2.php?list='+arr;
});
});
Try without the var arr to make it global, I don't believe the sub functions are parsing it.
Don't sent 'long' data over a URL. Most browsers have a length limit and it's very easy to exceed that and end up with corrupted data. For 'big' data, use a POST, which is not limited.
To send the array itself, just do an AJAX request and let jquery encode the array into JSON. You then handle it in PHP with json_decode() and you'll end up with a native PHP array.
Edit: Updated the JavaScript on jsfiddle based on your comment. On "submit", the array is saved at the "#form" element using the .data() method. On "click" of the "#submit" button, that data is retrieved and the url is build up.
The click event does fire before the submit event (at least in my Firefox 7), so your array is empty when concatenated to the URL string.
I put together some JavaScript on jsfiddle that might help. You do not really need to bind to the click event of the submit-button, just do the "redirect" in the submit handler function. You are building your string list there anyways. So there would no confusion what fires first, the click or the form submit event.
As for the serialization of your array, I used jQuery's .each() function but there is nothing wrong doing it by hand (if done correctly).
I could also imagine that the form is actually posted and this is why you do not see the "?list" search part of the URL.
If you don't need a complete redirect, why don't you send the data using jQuery.get()?

jQuery get values from selected checkboxes

First problem is that I do not know how to get the values of SPECIFC checkboxes when they are checked.
I need a function that will get the value of the selected checkboxes by checkbox ID or Name.
This is the code I have so far:
$("#doStatus").click(function(){
var Tuitting = $('textarea#tuitting').val();
var F = $('input#Fb').val(); //checkboxes with ID Fb
var T = $('input#Tw').val(); //checkboxes with ID Tw
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", { tuitting: Tuitting, f: F, t: T });
window.setTimeout('location.reload()', 1000);
return false;
});
Now the second problem is that both var F and var T may contain MORE than one values in an array..
Obviously when I use the ajax get functions the multiple values for both var F and var T are not
passed at all. What is the problem..?
How do I pass multiple values in an array that will be then runed by the foreach on the doStatusBox.php page?
Please help me.
$("#doStatus").click(function() {
var Tuitting = $('textarea#tuitting').val();
var F = $('input[name="fb"] :selected').val();
//You can give the name of checkbox and get the values of selected checkbox
return false;
});
I'm answering based on an assumption: you need checked checkboxes to pass them via GET method to your doStatusBox.php script.
However, why would you go trough the trouble of finding which checkbox is checked if you can simply use the serialize() method and let jQuery do the job for you?
$("#doStatus").click(function()
{
var serialized = $("#someFormHere").serialize()
// or, if you have your form elements within a div or another element
var serialized = $("#elementID :input").serialize();
$.get("<?echo $site['url'];?>modules/yobilab/tuitting_core/classes/doStatusBox.php", serialized);
window.setTimeout('location.reload()', 1000);
return false;
});
However, is "#doStatus" a submit button submitting the form or something else? If it submits the form, bind the submit event to the form, not click event to the button submitting it.

Categories