Inserting values of JS-created input textboxes into a database - php

I am using jQuery to create as many input textboxes as the user needs like so:
<script type="text/javascript">
$(document).ready(function() {
$('#names').on({
blur: function() {
var name = $("<p><input class='input' type='text' /></p>")
var nullFields = 0;
$(this).closest('div#names').find('input.input').each(function(){
if($(this).val() == ""){
nullFields++;
}
});
console.log(nullFields);
if(nullFields <= 1){
$('#names').append(name.fadeIn(500));
}
}
}, 'input');
});
</script>
Inserting a static textbox into a database isn't a problem using $_POST['blah'] andmysql_query("INSERT INTO ..."), but how do I insert the values of the dynamically created textboxes? I know I'll have to give the textboxes different names as they're created and I presume the MySQL query will be by way of some sort of loop.
EDIT
The website in question is here, specifically at step 4. As mentioned above, step 3 was quite straightforward.

This is an example to get you started, not the complete solution.
You create an array for the names then have the php insert each array item
var currentArrayNum = 1;
$('#someClickable').click(function(){
$('#td').append('<input name="arrayName['+currentArrayNum+']" value="" />');
currentArrayNum += 1;
});
php:
foreach ($_POST as $key){
if (is_array($key)){
foreach ($key as $key2 => $value){
//$key2 will equal arrayName[currentArrayNum]
//$value will equal the user input for the text field
do some stuff
}

You can create arrays out of name, simply try this:
<input type="text" name="post_input[input_1]" value="">
<input type="text" name="post_input[input_2]" value="">
After Submit, you would get an Array out of $_POST["post_input"] with the keys input_1 and input_2 and their assigned values. Then you just loop them as a normal array, for example
$aTextFields = $_POST["post_input"];
foreach( $aTextFields as $sValue ) {
...
}

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

Check which dynamic buttons (input type button) the user has click on server side php

First of all I want to thanks all of you guys for helping every day , answering questions. You have save me a lot of time and I have learn a lot.
I have let's say this buttons on a form.
<button type="button" value="Adventurous" name="adv" id="adv">Adventurous</button>
<button type="button" value="Discovery" name="disc" id="disc">Discovery</button>
<button type="button" calue="Easy-going" name="easy" id="easy">Easy-going</button>
When the user clicks on a button to specify how he feels in our example I have the follow code on jquery to change the state of the button as checked and change the class (to be shown with different colors etc)
$(".tailor_field .tailor_mood_btn button").click(function() {
var checked = $(this).attr('checked');
$the_image = $(this).find("img");
if(checked){
$(this).removeClass("mood_on");
$(this).attr('checked', false);
$the_image.attr("src", templateDir+"/images/btn_on.png");
}
else{
$(this).addClass("mood_on");
$(this).attr('checked', true);
$the_image.attr("src", templateDir+"/images/btn_off.png");
}
});
So when the user press submit I want to check on server side (php) which buttons the user clicked ?
Second I would like to insert the buttons dynamically. Ie to have a string on my DB, explode it to an array and loop each element to create the buttons etc. How I will know what to check if I don't know how many buttons will be and their names from the beginning ? Maybe with sessions (I would like to avoid it if there is another solution)?
Thanks a lot!
I would do it this way:
var checkedButtons = $(".tailor_field .tailor_mood_btn button[checked=true]");
$("form").submit(function() {
var data = [];
checkedButtons.each(function(index, element) {
var name = element.attr('name');
var value = element.val();
data[name] = value;
});
$.post('file.php', data);
});
The data variable is an array with keys as the names of clicked buttons, an values of values of those buttons. Later an ajax request is made to the file that needs this data (file.php) where the data array is available in the superglobal $_POST (ex. $_POST['adv'] = "Adventurous")
I think the best answer is to just use a list of checkboxes. It is what they were made for.
If you want to use the special buttons though, here is one way using the hidden filed as the input, rather than the actual button. I don't know if the element "button" has a checked attibute.
I just used a simple little javascript to change the values of the input, you can adapt your current function. Just notice that I gave the clickable buttons a new id, appending "_button" to the name from your database.
<?php
$string = "Adventerous,Discovery,Easy-Going"; /* this is from your database */
$delimiter = ",";
$button_values = explode($delimiter, $string);
?>
<html>
<body>
<script type="text/javascript" >
function checkbutton(id) {
var val = document.getElementById(id).value;
if (val == 0)
val = 1;
else
val = 0;
document.getElementById(id).value = val;
alert("Clicked: " + id);
}
</script>
<form action="form-catch.php" method="post">
<?php
foreach($button_values as $value) {
echo '<button type="button"
onClick="checkbutton(\''.$value.'\')">'.$value .'</button>
<input type="hidden" name="'.$value.'" id="'. $value .'" value="0" ><br>';
}
?>
<input type="submit" value="submit">
</form>
</body></html>
Then on the server, the form will send the button names from the string and the 0 or 1 if that button was checked.
<?php
/* quick form checker to show what was clicked in the other form */
foreach($_POST as $key => $val)
echo "<br> $key : $val";
?>
Even if you do not use the exact code, I hope the concept will get you in the right direction.
1) Send the data as a form input.
2) Loop through whatever was sent over and check for set values.

How to check multiple checkboxes checked using jquery?

i am new to the jquery, it is quite interesting, but i am having a little problem,
i am populating multiple checkboxes from database using foreach loop like this,
<? foreach($cities as $city) { ?>
<input type="checkbox" name="city[]" value="<?=$city->id?>" id="city[]" />
<? } ?>
i want to restrict user to check atleast one checkbox, i know how to do this with only one checkbox, but got confused with this kind of array in jquery, any help will be greatly appreciated!
Many thanks in advance!
To find how many checkboxes are checked, you can use something like:
var checkedNum = $('input[name="city[]"]:checked').length;
if (!checkedNum) {
// User didn't check any checkboxes
}
Since you're providing the same name attribute to all the checkboxes (from your PHP loop), you can use the selector input[name="city[]"] to target and find them all. But to find out how many specifically are checked, you can add the :checked selector. An alternative to this is using $('input[name="city[]"]').filter(":checked").
Finally, !checkedNum will only pass if checkedNum is 0, since 0 is falsey. Any other number is truthy, and wouldn't satisfy the condition !checkedNum.
References:
jQuery attribute equals selector: http://api.jquery.com/attribute-equals-selector/
:checked selector: http://api.jquery.com/checked-selector/
jQuery .length property: http://api.jquery.com/length/
If you want at least one checkbox checked, you can use this
var somethingChecked = false;
$("input[type=checkbox]").each(function() {
if(this).is(':checked')) {
somethingChecked = true;
}
});
if(!somethingChecked) {
alert("You haven't checked anything yet");
}
What this does is initialize a variable to false. Then the script loops through all inputs of type checkbox. If the item is checked, set the variable to true. Finally, check if the variable is still false. If it is, then show an error.
This code work well for me,here i convert array to string with ~
<input type="checkbox" value="created" name="today_check"><strong>Created</strong>
<input type="checkbox" value="modified" name="today_check><strong>Modified</strong>
<a class="get_tody_btn">Submit</a>
<script type="text/javascript">
$('.get_tody_btn').click(function(){
var vals = "";
$.each($("input[name='today_check']:checked"), function(){
vals += "~"+$(this).val();
});
if (vals){
vals = vals.substring(1);
}else{
alert('Please choose atleast one value.');
}
});
</script>
Assuming you have #my_form as the ID of your form, you could do
$("#my_form input[type=checkbox]:checked"). // ... do something
to select and do something with the checked checkboxes. You can also do
$("#my_form input[type=checkbox]").each(function(idx, elem) {
var is_checked = $(this).prop("checked");
// Do something with is_checked
});
to iterate through all the checkboxes and check whether they are checked or not.
First of all id of the checkboxes should be unique.
Do like this
<?
$checkBoxCount = 0;
foreach($cities as $city) { ?>
<input type="checkbox" name="city[]" value="<?=$city->id?>" id="chkbox-<?=$checkBoxCount?>" />
<? } ?>
Now in jQuery check like this to get all the checkboxes thats checked.
var checkCount = $("input[name='city[]']:checked").length;
if(checkCount == 0)
{
alert("Atleast one checkbox should be checked.");
}

Ajax Form submit receiving in PHP

I am experiencing some issues with a form I am making. I have the code to post a form to my PHP script that is meant to handle the data with this code:
<script type="text/javascript">
$(document).ready(function()
{
$("#submit").click(function()
{
var q1 = $("#q1").val();
var q2 = $("#q2").val();
var answers = "page=1&q1="+q1+"&q2="+q2;
$.ajax({
type:'POST',
url:'add.php',
data:answers,
success:function(response)
{
$("#answers").html(response);
}
});
});
});
</script>
This form is then received in my PHP script like this:
$page = $_POST['page'];
$q1 = $_POST['q1'];
$q2 = $_POST['q2'];
echo "Page: " .$page . "<br/>Question 1: " . $q1 . "<br/>Question 2: " . $q2;
The issue of it all is that I want this form to be able to handle X amount of inputs and also handle input I do not know the name of. Like I can get 5 textboxes, or 2 textboxes + a string of radiobuttons and so on. Is there a way to collect ALL $_POST data and then explode it or something similar so I can get it ready for the database? I wish to recover all question id's(values) and all answer values(could be a string or an int representing a radiobutton id).
You can iterate through all POST and GET request parameters by simply treating POST and GET as an array. For an example:
print_r($_POST);
Alternatively:
foreach ($_POST as $key => $value) {
echo $key." = ".$value."<br>";
}
If you want to handle a variating amount of input fields, you can define an incrementing naming convention and use loops to gather them all to an array.
with print_r($_POST); you can look at all values.
or something like this:
foreach ( $_POST AS $key => $value) {
echo $key." => ".$value."<br>";
}
First: Let jQuery build your data string, your current method requires you to know each field in advance and can't handle data with special characters in it.
url:'add.php',
data: $('#myForm').serialize(),
success:function(response)
Second: Name your fields using the PHP multiple fields with the same name convention:
<input type="radio" name="answer[1]" value="foo">
<input type="radio" name="answer[1]" value="bar">
You can then access them as:
$_POST['answer'][]
It is an array, so you can get the '1' and the 'foo' or the 'bar' in a loop.

Categories