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.
Related
I have couple of input field and values in them. This is projected to the user.
The user can modify these values and submit them.
When submitted, I need to check which input field is modified.
I can compare the previous fields and current fields and check. But I am trying to find more optimized way to do this.
I can use javascript, php, jquery and html tricks
<input id="input1" value="someValue" type="text">
<input id="input2" value="someValue" type="text">
Script:
$('input').on('change',function(){
var id = $(this).attr('id');
alert("input field is modified : ID = " + id);
});
You can create 2 different input, 1 hidden with a class like originalVal and 1 visible for every input.
Then on submit you do something like that :
$('input').each(function(){
var currentVal = $(this).val();
var originalVal = $(this).closest('.originalVal').val()
if(currentVal != originalVal){
//This input has changed
}
})
Since no code was given, you could compare what was in the input compared to what is now in it.
HTML Input:
<input type="text" id="testInput" value="DB Value"/>
jQuery
var modifiedInputs = [];
var oldVal = "";
$("#testInput").focus(function() {
oldVal = this.value;
}).blur(function() {
console.log("Old value: " + oldVal + ". New value: " + this.value);
//If different value, add to array:
if (this.value != oldVal) {
modifiedInputs.push(this.id);
}
});
Fiddle: http://jsfiddle.net/tymeJV/tfmVk/1/
Edit: Took it a step further, on modification of an input, if the changed value is different from the original, it pushes the elements ID to the array.
I would say your best bet would be to get the initial values from the input fields, and then compare them later on. Then, just do a comparison once the submit button is clicked. For instance, put this somewhere in your $(document).ready() that way it will retrieve the initial value.
var oldValue=[];
$('input').each(function(){
oldValue.push($(this).val());
});
Then you can compare later on when you hit the submit.
you could compare with default value like this
for(var i in formObj)
if('value' in formObj[i] && formObj[i].value!=formObj[i].defaultValue){
//do what ever here ...
}
I need to pass an array to a php page with AJAX. This array of input elements gets sent to the other page:
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith" size="117" >
This is how I prepare it for sending:
var txtCoursesNamewith = $.serialize($('#txtCoursesNamewith').val());
But I get this error when running the script:
TypeError: $.serialize is not a function
How can I send an array with AJAX?
I am facing same problem and, i am just using code like this.
but first of all please insert one hidden field and set textbox id like this:
<input type="hidden" name="txt_count" id="txt_count" value="3" />
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith1" size="117" >
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith2" size="117" >
<input type="text" name="txtCoursesNamewith[]" id="txtCoursesNamewith3" size="117" >
<script type="text/javascript">
var txt_count= $('#txt_count').val();
for (i=1; i<=txt_count; i++){
queryString += "&txtCoursesNamewith%5B%5D=" + $('#txtCoursesNamewith'+i).val();
}
</script>
finally we can pass queryString variable to ajax, and you can print array.
<?php
echo "<pre>";
print_r($_GET); // or print_r($_POST);
?>
var textBoxes;
$('input[name="txtCoursesNamewith[]"]').each(function() {
textBoxes+=$(this).val()+"|||";
});
Now the textBoxes have all the values of text field with ||| separated and pass to php script and use explode() function to split each input value . may it helps u
You don't need to use .val() because .serialize() works on a the field itself, not on the value. (because it needs to get the name and the value from the field)
You can also call serialize() directly on a jQuery object, rather than using the jquery object as a parameter. Do it like this:
var txtCoursesNamewith = $('#txtCoursesNamewith').serialize();
Hope that helps.
Because $.serialize($('#txtCoursesNamewith').val()) is a string and not a jQuery object, it doesn't have the serialize function.
If you want to serialize the input (with its value), use $('#txtCoursesNamewith').serialize();
$.ajax({
type: 'POST',
url: your url,
data: $('#'+form_id).serialize(),
success: function(data) {
$('#debug').html(data);
}
});
Then in php
<?php
print_r($_POST);
?>
$(document).keyup(function(e){
var idd = $(".hidd").val();// Here i can't get the correct value of "class hidd" and always get value 1
var sss = ".comment_tarea" + idd;
$tArea = $(sss);
alert(sss);
if ($tArea.is(":focus") && e.keyCode == 13) {
var t = $tArea.val();
}
});
$id1=0;
while(...){
$id1++;
<form >
<? $t =$id1; $comment_tarea = "comment_tarea".$t;
echo("comment");
echo($comment_tarea);
?>
<textarea class="<? echo $comment_tarea; ?>" name="tarea"></textarea>
<input type="hidden" class="hidd" value="<?php echo htmlspecialchars($id1); ?>" />
</form>
}
In the Jquery function, there is always value 1 in variable idd of class "hidd" for all textarea that means all class of $comment_tarea such as "comment_trea1", "comment_trea2", "comment_trea3", "comment_trea4",.......ans so on.
Here the textarea input value is change by $id1 which is unique.
How can get the correct idd value means get idd=1 for "comment_trea1",get idd=2 for "comment_trea2", get idd=3 for "comment_trea3" and so on...
pls help .
.val() returns only the value of the first matched element.
What you need to do is call .val() on every matched element:
$(".hidd").each(function() {
alert($(this).val());
});
You are using val() with the selector and it will return value of element at zero index always. To get the value of element at one index if exists you can use $(".hidd").eq(1).val();
You better bind the keyup with your text area instead of binding with document. AS you are generating forms in loop and each loop iteration generates textarea with hidden field. You can relate the hidden field with the form enclosing textarea.
$("textarea[name=tarea]").keyup(function(e){
var idd = $(this).closest('form').find('.hidd').val();
//your code
}
I have an admin page where I add and delete table rows on the fly.
The page comes loaded with the existent data in the database (mostly consisting in a sku_code and 5 different prices) but when I add rows on the fly, and fill them with the corresponding skus and prices, I want to save them as well in the database.
The problem is that what I do on the client-side with Javascript (add table rows on the fly) with innerHTML = '<input type="text"> is not accesible via $_POST variables of the main <form>
So basically i add via Javascript 's so i can fill them and save them as well in the database. But the $_POST values are empty.
Javascript code works fine. I have no clue where should i start debugging.
here's some Javascript code i'm using
function insert_record(){
var my_table = document.getElementById('my_table')
var tr = my_table.insertRow(my_table.rows.length-1)
//id-ul curent, numar toate row-urile - 1 (care este butonul OK)
var c_id = my_table.rows.length-2
tr.id = 'row_' + c_id + ''
var tr_td_1 = tr.insertCell(0)
tr_td_1.className = 'text2'
tr_td_1.align = 'center'
tr_td_1.innerHTML = 'SKU'
var tr_td_2 = tr.insertCell(1)
tr_td_2.className = 'text3'
tr_td_2.width = '63'
tr_td_2.innerHTML = '<input name="sku_' + c_id + '" type="text" id="sku_' + c_id + '" size="33" value="">'
....this addes a inside the table just before the last which contains the submit button, after which there's the
You need to assign a label to element. Then you can grab it in next page.
Instead of innerHTML = <input type="text"> try to use
<script>
function addElement(tag_type, target, parameters) {
//Create element
var newElement = document.createElement(tag_type);
//Add parameters
if (typeof parameters != 'undefined') {
for (parameter_name in parameters) {
newElement.setAttribute(parameter_name, parameters[parameter_name]);
}
}
//Append element to target
document.getElementById(target).appendChild(newElement);
}
</script>
You can call this function below either click of even or manually addElement('INPUT','targetTag',{id:'my_input_tag', name:'my_input_tag', type:'text', size:'5'});
you should give the name attribute. if you are worried about the unlimited numbers of fields just go for the array of the input variables,
like this
<input type="text" name="field1[]">
Now you can access them in post like this:
$_POST['field1'] //this is an array of fields
EDIT:
First thing is that you should use some library like jquery which eases the work.
I suggest you make sure your all your fields are inside the form and that you have named all of them instead of trying ajax or functions like #shail suggested.
In my opinion they are not solving the problem, just avoiding it.
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)