How to pass a javascript variable to PHP - php

Im creating a dynamic form with a button called "Add more rows" when this is clicked a JavaScript function creates a new row of textboxes with the appropriate id.
The problem is, how do I pass a counter variable from my JavaScript function to my next php page so it nows how many rows of textboxes to receive $_POST.
Ive got my JavaScript function however I'm missing data from the rows it creates itself.
any ideas?
Thanks
This is my js function
window.onload=function()
{
inp=document.getElementsByTagName('input');
for(c=0;c<inp.length;c++)
{
if(inp[c].value=='add')
{
inp[c].onclick=function()
{
n=15;
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='time'+n;
document.getElementById('txtara').appendChild(x)
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='event'+n;
document.getElementById('txtara').appendChild(x)
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='supplies'+n;
document.getElementById('txtara').appendChild(x)
var sel = document.createElement('select');
y = document.createElement('option');
y.value = 'Yes';
y.name = 'success' + n;
y.innerHTML = y.value;
x = document.createElement('option');
x.value = 'No';
x.name = 'success' + n;
x.innerHTML = x.value;
sel.appendChild(y);
sel.appendChild(x);
document.getElementById('txtara').appendChild(sel);
document.getElementById('txtara').appendChild(sel);
document.getElementById('txtara').appendChild(sel);
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name='comment'+n;
document.getElementById('txtara').appendChild(x)
document.getElementById ('txtara').innerHTML += '<br>';
n++;
}
}
}
//-->
}

You should add an <input type="hidden" name="num_rows" value="0"> to your form and update its value to be the row count when the form is submitted.

Assuming you want the number for easing the way you fetch the data on the server side.
There is a very simple way of doing this.
Let's say you have many input's of the same logical data type you want to handle, like:
<input type="text" name="names" value=""> And you create more of it dynamically.
Of course, you want them individual names to fetch the data, so you do like:
<input type="text" name="names[]" value=""> OR if you have more input for one entity, to make it consistent: <input type="text" name="names[1]" value=""><input type="text" name="eye_colours[1]" value=""> , so you can add a number in the brackets.
What do you do on the PHP side?
if( isset($_POST['names']))
foreach($_POST['names'] as $key => $val){ ... }
PHP parses it as an array, hurray! :)

You can add a name attribute to your form elements. As your form contains multiples elements (and you don't know how much elements), this name attribute must be in the form "my_name[]". The [] chars indicates a collection of elements. So your HTML code could look like this:
<form method="POST" action="mypage.php">
<input type="text" name="whatever[]" value="first" />
<input type="text" name="whatever[]" value="second" />
<input type="text" name="whatever[]" value="third" />
<input type="submit" />
</form>
Then, when the form will be submitted, you can get the values using the PHP variable $_POST['whatever']. This variable is an array and contains all the values of the "whatever" inputs like this:
$myValues = $_POST['whatever'];
// $myValues = array( 0 => "first", 1 => "second", 2 => "third" );
Then, if you want to do some actions with each rows, do a for each loop. If you want to know how many lines were submitted, you can simply do a count.

Since javascript is a client-side language, this is not possible :(
but, you can use AJAX to send a local javascript var to the server by GET, or POST

You can use PHP to output javascript code. If you have a value you can output it directly in javascript, or if you have a more complex value, you can encode it using json_encode.

You don't need to. POST will carry the number of rows for you without a problem. Simply do count($_POST) to get the number of values posted. Or, if you use my suggested version below, use count($_POST['time']) to get the number of time values.
var types = ['time', 'event', 'supplies'];
function createInput( i, n )
{
var base = isNaN( i )? i: types[ i ];
x=document.createElement('input');
x.setAttribute('rows',1);
x.setAttribute('cols',20);
x.name= base + "[" + n + "]"; // this will make $_POST[<base>] an array with n as the index.
document.getElementById('txtara').appendChild(x)
}
window.onload=function()
{
inp=document.getElementsByTagName('input');
for(c=0;c<inp.length;c++)
{
if(inp[c].value=='add')
{
var n = 15; // move n out here. Otherwise n will always = 15.
inp[c].onclick=function()
{
for( var i = 0; i < types.length; i++ )
{
// passing both variables in will avoid any possible collisions.
createInput( i, n );
}
var sel = document.createElement('select');
sel.name = 'success[' + n + ']';
y = document.createElement('option');
// option has no name attribute (http://www.w3schools.com/tags/tag_option.asp)
y.value = 'Yes';
y.innerHTML = y.value;
x = document.createElement('option');
x.value = 'No';
x.innerHTML = x.value;
sel.appendChild(y);
sel.appendChild(x);
// you had this three times... why?
document.getElementById('txtara').appendChild(sel);
createInput( 'comment', n );
document.getElementById ('txtara').innerHTML += '<br>';
n++;
}
}
}
}

Related

Why all the inputs are checked after post in JQUERY?

I have radio inputs, if I click on an input, then after post, all the other inputs go to "checked", I don't understand why, here is my code:
foreach ($tab_stickers_stored as $key => $value) {
<input class="form-check-input switch_sticker" type="checkbox" id="switch_sticker_<?=$key?>" name="switch_sticker" value="<?= $key ?>"
<?php if (isset($_POST['switch_sticker'])){echo 'checked="checked"';}?>>
}
$(".switch_sticker").on('change', function() {
var index = $(this).val();
$("input[name='switch_sticker']:checked").each(function(){
if ($("#switch_sticker_" + index).is(':checked')) {
var temp = document.getElementById('largeur_sticker_' + index).value;
document.getElementById('largeur_sticker_' + index).value = document.getElementById('longueur_sticker_' + index).value;
document.getElementById('longueur_sticker_' + index).value = temp;
} else {
var temp = document.getElementById('longueur_sticker_' + index).value;
document.getElementById('longueur_sticker_' + index).value = document.getElementById('largeur_sticker_' + index).value;;
document.getElementById('largeur_sticker_' + index).value = temp;
}
index = "";
});
});
Thank you
Your inputs have different id attributes, but they all have the same name. It is the name that determines what gets submitted, as you have already discovered without realising it when you wrote this line:
<?php if (isset($_POST['switch_sticker'])){echo 'checked="checked"';}?>
That if statement has nothing in it which varies around the loop; it looks at the same value $_POST['switch_sticker'] every time.
The JavaScript code, meanwhile, is essentially irrelevant to the question, because it only changes the value of various elements. Those will show up as the value of the $_POST['switch_sticker'] variable, but because there's only one variable and lots of values, it will just end up with the last one in the list.
The solution is to give each of your checkboxes their own name, like you give them their own value: name="switch_sticker_<?=$key?>". Then look for that name in the PHP: <?php if (isset($_POST['switch_sticker_' . $key])){echo 'checked="checked"';}?>.
You can also use names in the form something[something_else], e.g. name="switch_sticker[<?=$key?>]" and <?php if (isset($_POST['switch_sticker'][$key])){echo 'checked="checked"';}?>. That will cause PHP to create an array when they're submitted, which is a bit nicer to work with - you can write things like foreach ( $_POST['switch_sticker'] as $submittedKey => $submittedValue ) { ... }.

How to see if checkboxes with the same name are checked and then retrieve the values in php

I have a list of songs. I'm trying to determine whether or not a song on the list has been checked or not. If so I need to know the value of the checkbox.
my html looks like this... the value $song_id is pulled from the list in the database.
<input type='checkbox' name='song[]' value='$song_id' />
There could be 10 songs... there could 100.
I need to know which ones have been checked and how to get the value.
On click save item ID of item to array; (js)
On click search was such ID already checked; (in array)
ADDED
You should use jQuery (or raw javascript) to do logic you want. jQuery is http://jquery.com/ using it you can do you want on front-end. Do this on back-end is bad idea.
Once you submit the form the $_POST['song'] variable will contain an array of all the $song_id's that were selected.
You can do something like this:
<input type='checkbox' name='song[]' class='songItem' value='$song_id' />
<input type='hidden' id='selectSongsHidden' />
In JavaScript,
var selectedSongValues = [];
var selectedSongsString = ""; // for comma-separated values
function GetSelectedSongs()
{
var songs = $('.songItem');
var selectedSongs = [];
for(var i=0; i<songs.length; i++)
{
var checked = $(songs[i]).is(':checked');
if(checked)
{
selectedSongs.push(songs[i]);
}
}
for(var j=0; j<selectedSongs.length; j++)
{
selectedSongValues.push($(selectedSongs[j]).val());
selectedSongsString += $(selectedSongs[j]).val() + ",";
}
$('#selectSongsHidden').val(selectedSongsString);
}
When you press submit, in the onclick event you can call this function and set the value to a hidden field.
You can see this in a working http://jsfiddle.net/A3e3y
foreach ( $_POST['song'] AS $song_id ) {
// do smth with $song_id ...
}

How to find which input field is modified?

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 ...
}

Change text input values dynamically

My question might be quite easy for you guys, but it's hard for me...
I have a text field and I want to change its value between once <label id="some_id"> is clicked. Until what I've described now, I can do it myself with jQuery, but here comes the complex part (for me, obviously):
I have two values I want for that text field, and once that <label> is clicked, it switches to the value that isn't shown, but once we click it again, it goes back to the original text the text field contained.
I have to keep my jQuery/JS internal because I get the desired values from the database and I don't want to make my .js files .php.
This is what I got:
<label for="html" onclick="$('#html').val('<?php echo $image->convert('html_b', $image_data['image_link']); ?>')">HTML:</label>
<input type="text" id="html" value="<?php echo $image->convert('html_a', $image_data['image_link']); ?>" readonly />
It does the first part I need, changing the value of the field to the new value, but once that button gets clicked again, I want the original text.
Thank you.
You can compare its current value to the available possibilities.
<label id="toggle" for="stuff">I'm a label</label>
<input type="text" val="" name="stuff" id="stuff">​
var possibilities = ["foo", "bar"];
$('#toggle').click(function(){
var old_val = $("#stuff").val(), new_val;
if (old_val == possibilities[0])
new_val = possibilities[1];
else
new_val = possibilities[0];
$("#stuff").val(new_val);
});​
demo
First, don't use inline JavaScript.
You can use a combination of .toggle() and data-* attributes for this. For example, using a data-toggle attribute for the value you want to toggle with.
<label for="html" data-toggle="This is a placeholder">HTML:</label>
<input type="text" id="html" value="This is my real value" readonly>​
$("label[for][data-toggle]").each(function() {
var $this = $(this);
var $for = $("#" + $this.attr("for"));
var originalValue;
$this.toggle(function() {
originalValue = $for.val();
$for.val($this.data("toggle"));
}, function() {
$for.val(originalValue);
});
});​
See it here.
UPDATE #1
I added usage of for attribute of <label>.
UPDATE #2
If you don't want to use .toggle() due to the deprecation notice.
$("label[for][data-toggle]").each(function() {
/* cache */
var $this = $(this);
var $for = $("#" + $this.attr("for"));
var originalValue = $for.val();
/* state variable */
var which = 0;
$this.click(function() {
$for.val(which ? originalValue : $this.data("toggle"));
which = 1 - which;
});
});​
See the non-.toggle() alternative here.
For doing this, on the first button click you need to store the current value of input in some variable and then on 2nd click you can assign that variable to input value. If you donot want to have js file, you can simply use <script></script> tags to write the jquery.
`<label id="label" onclick="replaceText('newvalue')">Click Mee</label>
<input id="html" type="text" value="some value">
<script>
var currentValue="";
function replaceText(newval){
currentValue= $("#html").val();
if(currentValue!=newval)
$("#html").val(newval);
$("#label").attr("onclick","replaceText('"+currentValue+"')");// Here we assigned the other value to label onclick function so that it will keep on toggling the content.
}
</script>`
DEMO HERE
You can store the values into JavaScript variables and use jQuery click method instead of onclick attribute.
var def = "<?php echo $image->convert('html_a', $image_data['image_link']); ?>",
up = "<?php echo $image->convert('html_b', $image_data['image_link']); ?>";
$('label[for=html]').click(function() {
$('#html').val(function(i, currentValue) {
return currentValue === def ? up : def;
});
});

Load array from inputs to PHP with jQuery .load()?

Ok, I've been looking and looking for about 2 weeks now and I've yet to find exactly what I need to figure out, so now is the time to ask the experts!
I'm working on an advertising management system and one of the parts of the request form is to select start and end dates for an ad. The user is given an option of adding more dates.
So, there are two inputs that are there initally...
<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">
Then, under that is an option to dynamically add more inputs.
When the user adds more inputs, it just copies those initial inputs, so we end up with more instances. For example:
<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">
<input type="text" name="startDate[]" id="startDateInput">
<input type="text" name="enddate[]" id="endDateInput">
Is there a way to send the results of these inputs as an array using .load()?
I have it sending and displaying the info for one set of inputs with the code below...
var startDate = $("#startDateInput").val();
var endDate = $("#endDateInput").val();
$("#adBooking").show().load('../scripts/checkSpots.php', { startDate: startDate, endDate: endDate});
I guess I just don't 100% understand how to do this. I've been racking my brain for the past two weeks but I can't find anything totally relevant to what I'm doing.
But, what I need to do is make an array of data out of all the startDate and endDate inputs and then throw it through the .load() and into the checkSpots.php page and have it display the information for each set of start/end dates.
Is there a different way of doing this? Maybe a more efficient way? Or, if anyone can shed a bit of light on this broken jQuery noob, I'd greatly apprecaite it! :D
demo: http://jsbin.com/etihaw/3
$(function() {
$("#add-date").click(function(e) {
var i = $('.end-date').length + 1;
$('<p class="dates">' +
'<input class="start-date" name="startDate[' + i + ']" id="startDate' + i + '" />' +
'<input class="end-date" name="endDate[' + i + ']" id="endDate' + i + '" />' +
'</p>').insertAfter('.dates:last');
e.preventDefault();
});
$('#my-form').submit(function() {
var post_data = $(this).serialize();
//$("#adBooking").show().load('../scripts/checkSpots.php', post_data);
alert(post_data);
return false;
});
PHP
<?php
foreach($_POST['startDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 07/12/2011
}
foreach($_POST['endDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 09/12/2011
}
?>
First things first, ID's need to be unique, so when a new date pair is added, append a qualifier on the end of the id:
<input type="text" name="startDate[]" id="startDateInput1">
<input type="text" name="enddate[]" id="endDateInput1">
<input type="text" name="startDate[]" id="startDateInput2">
<input type="text" name="enddate[]" id="endDateInput2">
Or better yet, use a class:
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
Then you can apply some jQuery voodoo whenever you'd like (button click, submit, etc):
$('#myButton').click(function(){
// Our ajax post data. For example, $_POST['startDates'][2] would
// give you the 3rd start date in your php file.
var data = {
startDates: new Array(),
endDates: new Array()
};
// Loop through each date pair, extract its value, and add it to our post data
$('.startDateInput').each(function(){
data.startDates.push(this.val());
});
$('.endDateInput').each(function(){
data.endDates.push(this.val());
});
// Load it!
$('#result').load('doSomething.php', data);
});
Note: Above code is not tested, just an example of one possible solution.
Hope that helps. Oh, and obligatory Family Guy reference.
There is a major flaw in your logic: Any id attribute must be unique in the document. As you use several id's more than once, it will not work or give unexpected results at best.
First, you shouldn't use the same id on multiple elements within a single html page. That's going to cause all sorts of unpredictable behavior. Use class instead so:
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
<input type="text" name="startDate[]" class="startDateInput">
<input type="text" name="enddate[]" class="endDateInput">
Then you need to query for all the input elements using jquery loop through each element and assign its value to the appropriate array.
var myEndDateArray = [], myStartDateArray = [];
$(".endDateInput").each(function() {
myEndDateArray.push($(this).val())
});
$(".startDateInput").each(function() {
myStartDateArray.push($(this).val())
});
Finally, you must post the array data to your page in a compatible post format.
$("#adBooking").show().load('../scripts/checkSpots.php', { 'startdate[]': myStartDateArray, 'enddate[]': myEndDateArray});
I bumped int this problem lately, and I found aSeptik solution is very useful.
But there is a mistake in it. From jQuery documentation:
Request Method
The POST method is used if data is provided as an object; otherwise,
GET is assumed.
Since the result of the .serialze() function is string the .load() methode will use GET.
JS code (same):
$(function() {
$("#add-date").click(function(e) {
var i = $('.end-date').length + 1;
$('<p class="dates">' +
'<input class="start-date" name="startDate[' + i + ']" id="startDate' + i + '" />' +
'<input class="end-date" name="endDate[' + i + ']" id="endDate' + i + '" />' +
'</p>').insertAfter('.dates:last');
e.preventDefault();
});
$('#my-form').submit(function() {
var post_data = $(this).serialize();
//$("#adBooking").show().load('../scripts/checkSpots.php', post_data);
alert(post_data);
return false;
});
PHP script with _GET:
<?php
foreach($_GET['startDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 07/12/2011
}
foreach($_GET['endDate'] as $key => $val ) {
echo $key; // 1
echo $val; // 09/12/2011
}
?>

Categories