Angular - storing checkbox values, and displaying them - php

Suppose that, you have 27 checkboxes, let's call them 'categories'. These checkboxes are in one section, you can select them multiple, and save.
The eseence is: if you save the form, the categories will be added to your profile, in MySQL.
My question is:
How I should name the models,
How I should store de values after sending the form
I had a solution for this, I saved the nth of the categories, then clicked them back at loading, but that's not the best.
Here is the code:
$scope.getSelectedCats = function() //Returning array: [1,4,5,6]
{
$return_array = [];
$i = 0;
if($scope.whoareu.develop){ $return_array[$i] = 1; $i++;}
if($scope.whoareu.design){ $return_array[$i] = 2; $i++;}
if($scope.whoareu.produce){ $return_array[$i] = 3; $i++;}
if($scope.whoareu.repair){ $return_array[$i] = 4; $i++;}
[...]
return $return_array;
}
HTML
<p>
<input ng-model="whoareu.develop" type="checkbox" value=1 id="WAY8" name="whoareu" />
<label for="WAY8">Develop</label>
</p>
<p>
<input ng-model="whoareu.design" type="checkbox" value=2 id="WAY9" name="whoareu" />
<label for="WAY9">Design</label>
</p>
<p>
<input ng-model="whoareu.produce" type="checkbox" value=3 id="WAY10" name="whoareu" />
<label for="WAY10">Produce</label>
</p>
<p>
<input ng-model="whoareu.repair" type="checkbox" value=4 id="WAY11" name="whoareu" />
<label for="WAY11">Repair</label>
</p>
[...]
And last, a very ugly solution for loading checks:
<?php
//$dbData = Data row from mysql, in object, by Wordpress
echo "setTimeout(function(){";
foreach(explode(',', $dbData->interested_in) as $val)
{
//echo "$('input:checkbox[name=whatareu]').filter('[value=$val]').click();";
echo "$('input:checkbox[name=whatareu]').eq($val-1).click();";
}
echo "}, 1000);";
?>

I don't know if I understand your problem well, see my snippet. If you want, you could create some mapping function setDefaultState(basedOn) which set checked in model checkboxs.
If the problem is that data is lost after you leave the controller, you should use some singleton storage like Angular's factories, and storage the checked categories there.
angular.module('app', [])
.controller('FrameController', ['$injector',
function($injector) {
var vm = this;
vm.checkboxs = [{
id: 'WAY8',
label: 'Develop',
checked: true
}, {
id: 'WAY9',
label: 'Design'
}]
angular.extend(vm, {
save: save
})
function save() {
// API call
console.log('checked: ', vm.checkboxs.filter(function(c) {
return c.checked
}).map(function(c) {
return {
id: c.id
}
}));
}
}
]);
setTimeout(function() {
angular.bootstrap(document.getElementById('body'), ['app']);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="body">
<div ng-controller="FrameController as vm">
<ul>
<li ng-repeat="checkbox in vm.checkboxs">
<input ng-model="checkbox.checked" type="checkbox" id="{{checkbox.id}}" name="whoareu" />
<label for="{{checkbox.id}}">{{checkbox.label}}</label>
</li>
</ul>
<button ng-click="vm.save()">
Save
</button>
</div>
</div>

Related

How to retain multiple checkbox even page refreshes reset after form submit

i have a form of multiple checkboxes. but i want to retain the checkbox checked but reset it after form submit. here is my code.
<?php
if(isset($_POST['query'])){
$searched = $_POST['query'];
$conn = mysqli_connect('localhost','root','','orderqueing') or die (mysqli_error());
$query = "SELECT * FROM product_tbl WHERE itemName LIKE '%$searched%'";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo '<label style="float:left" class="option_item">
<input type="checkbox" id="mycheckbox" class="checkbox" name="prodid[]" value="'.$row['itemName'].'">
<div class="option_inner facebook">
<div class="tickmark"></div>
<div class="icon">'.$row['itemName'].'<input type="hidden" name="prodname[]" value="'.$row['itemName'].'"></div>
<div class="icon">'.$row['itemPrice'].' PHP<input type="hidden" name="price[]" value="'.$row['itemPrice'].'"></div>
<div class="icon"><input type="number" name="multiple[]" style="padding:5px;width:60px;" value="1" ></div>
</div>
</label>';
}
} else {
$conn = mysqli_connect('localhost','root','','orderqueing') or die (mysqli_error());
$query = "SELECT * FROM product_tbl";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result)){
echo '<label style="float:left" class="option_item">
<input type="checkbox" id="mycheckbox" class="checkbox" name="prodid[]" value="'.$row['itemName'].'">
<div class="option_inner facebook">
<div class="tickmark"></div>
<div class="icon">'.$row['itemName'].'<input type="hidden" name="prodname[]" value="'.$row['itemName'].'"></div>
<div class="icon">'.$row['itemPrice'].' PHP<input type="hidden" name="price[]" value="'.$row['itemPrice'].'"></div>
<div class="icon"><input type="number" name="multiple[]" style="padding:5px;width:60px;" value="1" ></div>
</div>
</label>';
}
}
?>
this is my UI :
enter image description here
because the checked checkboxes resets when i search an item.
i want to retain it checked before the form submits.
i could not think of a solution to this problem. thanks for the help
You can consider recording the checkbox you selected in the cookie when submitting or at the end of the keyup function; then get the cookie in window.onload or your code and give the corresponding checkbox a selected state
I'm not quite sure if you are requesting this data via ajax.This is untested code, but provides an idea; you may need to modify or even use
I thought of the following workaround:
window.onload=function(){
//Called after initialization or search. Check the checkbox
function reloadCheckBox(){
let allProdCheck = document.querySelectorAll("input[name=prodid[]]");
allProdCheck.forEach(element => {
let cooki = getCookie("prod_"+element.value);
if(cooki!=''&&Boolean(cooki)==true){ //if exists (previously selected)
element.checked = true;
}else{
element.checked = false;
}
});
}
}
//Record in cookie when selected
function prodCheck(ele){
setCookie("prod_"+ele.value,ele.checked);
}
function setCookie(cname,cvalue='',exdays=1){
var d = new Date();
//d.setTime(d.getTime()+(exdays*24*60*60*1000));
//var expires = "expires="+d.toGMTString();
//document.cookie = cname+"="+cvalue+"; "+expires;
document.cookie = cname+"="+cvalue;
}
function getCookie(cname){
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name)==0) { return c.substring(name.length,c.length); }
}
return "";
}
Then add event onclick="prodCheck(this)" to this statement <input type="checkbox" id="mycheckbox" class="checkbox" name="prodid[]" value="'.$row[' itemName'].'" >
<input type="checkbox" id="mycheckbox" class="checkbox" name="prodid[]" value="'.$row['itemName'].'" onclick="prodCheck(this)" >
you saied cant figure it out on how to use it in multiple checkboxes?http://jsfiddle.net/Lwxoeyyp/1/
<input type="button" id="ReserveerButton1" value="save" onclick="save()"/>
<input type="button" id="Wisbutton1" value="delete" onclick="wis()"/>
<input type="checkbox" id="checkbox1zaal1" onchange="checkChange(this)">1e film van de dag</input>
<input type="checkbox" id="checkbox1zaal2" onchange="checkChange(this)">1e film van de dag</input>
<input type="checkbox" id="checkbox1zaal3" onchange="checkChange(this)">1e film van de dag</input>
function load(){
let checks = JSON.parse(localStorage.getItem('checkbox'));
if(checks!={}){
for(let key in checks){
    document.getElementById(key).checked = checks[key];
   }
}
}
/*one checkbox is checked or unchecked
If you want to use the save method you wrote, you can pass the corresponding single checkbox object as the parameter
*/
function checkChange(ele){
let oldCheck = JSON.parse(localStorage.getItem('checkbox'));
if(oldCheck==null||oldCheck=={}){
oldCheck={};
}
oldCheck[ele.id] = ele.checked;
localStorage.setItem('checkbox', JSON.stringify(oldCheck));
}
load();

PHP: Easiest and cleanest way to modify multidimensional array?

I have a dynamic multi-dimensional array that can be of any dimension here is a sample:
$array_serial = 'a:2:{i:0;a:2:{s:2:"id";a:4:{s:3:"url";s:27:"products.php?la=electronics";s:6:"otitle";s:11:"Electronics";s:6:"utitle";s:11:"Electronics";s:4:"ttip";s:11:"Electronics";}s:8:"children";a:2:{i:0;a:2:{s:2:"id";a:4:{s:3:"url";s:51:"products.php?la=electronics&lb=Computer-Peripherals";s:6:"otitle";s:20:"Computer Peripherals";s:6:"utitle";s:20:"Computer Peripherals";s:4:"ttip";s:34:"Electronics : Computer Peripherals";}s:8:"children";a:1:{i:0;a:2:{s:2:"id";a:4:{s:3:"url";s:63:"products.php?la=electronics&lb=Computer-Peripherals&lc=Printers";s:6:"otitle";s:8:"Printers";s:6:"utitle";s:8:"Printers";s:4:"ttip";s:45:"Electronics : Computer Peripherals : Printers";}s:8:"children";a:1:{i:0;a:1:{s:2:"id";a:4:{s:3:"url";s:90:"products.php?la=electronics&lb=Computer-Peripherals&lc=Printers&ld=Single-Function-Printer";s:6:"otitle";s:23:"Single Function Printer";s:6:"utitle";s:23:"Single Function Printer";s:4:"ttip";s:71:"Electronics : Computer Peripherals : Printers : Single Function Printer";}}}}}}i:1;a:1:{s:2:"id";a:4:{s:3:"url";s:38:"products.php?la=electronics&lb=Mobiles";s:6:"otitle";s:7:"Mobiles";s:6:"utitle";s:7:"Mobiles";s:4:"ttip";s:21:"Electronics : Mobiles";}}}}i:1;a:2:{s:2:"id";a:4:{s:3:"url";s:31:"products.php?la=homenfurnitures";s:6:"otitle";s:19:"Home And Furnitures";s:6:"utitle";s:19:"Home And Furnitures";s:4:"ttip";s:19:"Home And Furnitures";}s:8:"children";a:2:{i:0;a:1:{s:2:"id";a:4:{s:3:"url";s:9:"about.php";s:6:"otitle";s:8:"About Us";s:6:"utitle";s:8:"About Us";s:4:"ttip";s:8:"About US";}}i:1;a:2:{s:2:"id";a:4:{s:3:"url";s:40:"products.php?la=homenfurnitures&lb=Other";s:6:"otitle";s:5:"Other";s:6:"utitle";s:5:"Other";s:4:"ttip";s:27:"Home And Furnitures : Other";}s:8:"children";a:1:{i:0;a:2:{s:2:"id";a:4:{s:3:"url";s:51:"products.php?la=homenfurnitures&lb=Lights-AnD-Lamps";s:6:"otitle";s:14:"Lights & Lamps";s:6:"utitle";s:14:"Lights & Lamps";s:4:"ttip";s:36:"Home And Furnitures : Lights & Lamps";}s:8:"children";a:2:{i:0;a:1:{s:2:"id";a:4:{s:3:"url";s:12:"contacts.php";s:6:"otitle";s:10:"Contact Us";s:6:"utitle";s:10:"Contact Us";s:4:"ttip";s:10:"Contact US";}}i:1;a:2:{s:2:"id";a:4:{s:3:"url";s:58:"products.php?la=homenfurnitures&lb=Dinnerware-AnD-Crockery";s:6:"otitle";s:21:"Dinnerware & Crockery";s:6:"utitle";s:21:"Dinnerware & Crockery";s:4:"ttip";s:43:"Home And Furnitures : Dinnerware & Crockery";}s:8:"children";a:1:{i:0;a:1:{s:2:"id";a:4:{s:3:"url";s:78:"products.php?la=homenfurnitures&lb=Dinnerware-AnD-Crockery&lc=Cups-AnD-Saucers";s:6:"otitle";s:14:"Cups & Saucers";s:6:"utitle";s:14:"Cups & Saucers";s:4:"ttip";s:60:"Home And Furnitures : Dinnerware & Crockery : Cups & Saucers";}}}}}}}}}}}';
All index "otitle" of this array will be displayed in form in an input type text, and the user can modify this Title according to their desire. How can I achieve this in a clean way?
And this is just part of the array, the actual array can be much bigger.
Here is my code to view "otitle" in a input type
function get_menu_list($selected_menus)
{
if($selected_menus != null){
foreach($selected_menus as $menu_level_1)
{
$title = implode("///",$menu_level_1['id']);
echo '
<li class="dd-item">
<div class="dd-handle">
<input type="text" name="otitle[]" value="'.$menu_level_1['id']['otitle'].'" />
</div>
';
if(isset($menu_level_1['children']))
{
echo '<ol class="dd-list">';
foreach($menu_level_1['children'] as $menu_level_2)
{
$title_level_2 = implode("///",$menu_level_2['id']);
echo '
<li class="dd-item">
<div class="dd-handle">
<input type="text" name="otitle[]" value="'.$menu_level_2['id']['otitle'].'" />
</div>
';
if(isset($menu_level_2['children']))
{
echo '<ol class="dd-list">';
foreach($menu_level_2['children'] as $menu_level_3)
{
$title_level_3 = implode("///",$menu_level_3['id']);
echo '
<li class="dd-item">
<div class="dd-handle">
<input type="text" name="otitle[]" value="'.$menu_level_3['id']['otitle'].'" />
</div>
';
if(isset($menu_level_3['children']))
{
echo '<ol class="dd-list">';
foreach($menu_level_3['children'] as $menu_level_4)
{
$title_level_4 = implode("///",$menu_level_4['id']);
echo '
<li class="dd-item">
<div class="dd-handle">
<input type="text" name="otitle[]" value="'.$menu_level_4['id']['otitle'].'" />
</div>
';
if(isset($menu_level_4['children']))
{
echo '<ol class="dd-list">';
foreach($menu_level_4['children'] as $menu_level_5)
{
$title_level_5 = implode("///",$menu_level_5['id']);
echo '
<li class="dd-item">
<div class="dd-handle">
<input type="text" name="otitle[]" value="'.$menu_level_5['id']['otitle'].'" />
</div>
</li>
';
}
echo "</ol>";
}
echo '</li>';
}
echo "</ol>";
}
echo '</li>';
}
echo "</ol>";
}
echo '</li>';
}
echo '</ol>';
}
echo '</li>';
}
}//end if
else
return null;
}
$array_unserial = unserialize($array_serial);
echo get_menu_list($array_unserial);
I did not used the Recursion method but since I have already written the function with using foreach loop. And here is the code of how I accomplished this task using this same function.
if (isset($_REQUEST['u_arr'])) {
$array_serial = serialize($_REQUEST['u_arr']);
}
else {
//Here is my code to view "utitle" in a input type
$array_serial = $array_serial; /*You can get $array_serial from the question of this post*/
}
function get_menu_list($selected_menus)
{
if($selected_menus != null){
foreach($selected_menus as $id1=>$menu_level_1)
{
$title = implode("///",$menu_level_1['id']);
echo '
<li class="dd-item">
<div class="dd-handle">
<input type="hidden" name="u_arr['.$id1.'][id][url]" value="'.$menu_level_1['id']['url'].'" />
<input type="hidden" name="u_arr['.$id1.'][id][otitle]" value="'.$menu_level_1['id']['otitle'].'" />
<input type="text" name="u_arr['.$id1.'][id][utitle]" value="'.$menu_level_1['id']['utitle'].'" />
<input type="hidden" name="u_arr['.$id1.'][id][ttip]" value="'.$menu_level_1['id']['ttip'].'" />
</div>
';
if(isset($menu_level_1['children']))
{
echo '<ol class="dd-list">';
foreach($menu_level_1['children'] as $id2=>$menu_level_2)
{
$title_level_2 = implode("///",$menu_level_2['id']);
echo '
<li class="dd-item">
<div class="dd-handle">
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][id][url]" value="'.$menu_level_2['id']['url'].'" />
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][id][otitle]" value="'.$menu_level_2['id']['otitle'].'" />
<input type="text" name="u_arr['.$id1.'][children]['.$id2.'][id][utitle]" value="'.$menu_level_2['id']['utitle'].'" />
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][id][ttip]" value="'.$menu_level_2['id']['ttip'].'" />
</div>
';
if(isset($menu_level_2['children']))
{
echo '<ol class="dd-list">';
foreach($menu_level_2['children'] as $id3=>$menu_level_3)
{
$title_level_3 = implode("///",$menu_level_3['id']);
echo '
<li class="dd-item">
<div class="dd-handle">
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][id][url]" value="'.$menu_level_3['id']['url'].'" />
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][id][otitle]" value="'.$menu_level_3['id']['otitle'].'" />
<input type="text" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][id][utitle]" value="'.$menu_level_3['id']['utitle'].'" />
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][id][ttip]" value="'.$menu_level_3['id']['ttip'].'" />
</div>
';
if(isset($menu_level_3['children']))
{
echo '<ol class="dd-list">';
foreach($menu_level_3['children'] as $id4=>$menu_level_4)
{
$title_level_4 = implode("///",$menu_level_4['id']);
echo '
<li class="dd-item">
<div class="dd-handle">
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][children]['.$id4.'][id][url]" value="'.$menu_level_4['id']['url'].'" />
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][children]['.$id4.'][id][otitle]" value="'.$menu_level_4['id']['otitle'].'" />
<input type="text" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][children]['.$id4.'][id][utitle]" value="'.$menu_level_4['id']['utitle'].'" />
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][children]['.$id4.'][id][ttip]" value="'.$menu_level_4['id']['ttip'].'" />
</div>
';
if(isset($menu_level_4['children']))
{
echo '<ol class="dd-list">';
foreach($menu_level_4['children'] as $id5=>$menu_level_5)
{
$title_level_5 = implode("///",$menu_level_5['id']);
echo '
<li class="dd-item">
<div class="dd-handle">
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][children]['.$id4.'][children]['.$id5.'][id][url]" value="'.$menu_level_5['id']['url'].'" />
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][children]['.$id4.'][children]['.$id5.'][id][otitle]" value="'.$menu_level_5['id']['otitle'].'" />
<input type="text" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][children]['.$id4.'][children]['.$id5.'][id][utitle]" value="'.$menu_level_5['id']['utitle'].'" />
<input type="hidden" name="u_arr['.$id1.'][children]['.$id2.'][children]['.$id3.'][children]['.$id4.'][children]['.$id5.'][id][ttip]" value="'.$menu_level_5['id']['ttip'].'" />
</div>
</li>
';
}
echo "</ol>";
}
echo '</li>';
}
echo "</ol>";
}
echo '</li>';
}
echo "</ol>";
}
echo '</li>';
}
echo '</ol>';
}
echo '</li>';
}
}//end if
else
return null;
}
$array_unserial = unserialize($array_serial);
?>
<form method="post" action="">
<?php get_menu_list($array_unserial) ?>
<button type="submit">Submit</button>
</form>
Basic Idea
The idea you are looking for is called Recursion. Recursion works by a named function calling itself until some variety of conditionals are met. For example, the mathematical operator ! (read: "Factorial") is one of the simplest ways to get an idea of how recursion works. A factorial is defined by starting with your given number, say 5, and multiplying by every integer from that number until you reach 1. So 5! is calculated like so: 5*4*3*2*1. In code that may look something like:
function factorial($n){
if($n<=1) return 1;
//If the number being passed is one or lower, no need to call this function again, just return 1.
return $n*factorial($n-1);
//If we got to here, the $n is not 1 or less, so we multiply $n times the answer of factorial($n-1), which will repeat until $n-1 becomes 1.
}
I found this Quora question where I thought both answers helped to explain in different ways the idea of recursion.
Answer
Now, for your question. I've commented everything I can think of, so please let me know if you don't understand anything.
<style>
div.menu-item > div.menu-item {
margin-left:1rem;
}
</style>
<?php
function get_menu_list($selected_menus,$offset_i=false)
{
foreach($selected_menus as $i=>$menu):
//the : is an alternate syntax in PHP for {}, now instead of trying to find a matching }, PHP will look for the keyword "endforeach;"
$id_string = ($offset_i===false) ? $i : $offset_i.'-'.$i;
//If the $offset_i is false, then we are calling this function directly and these are main-level elements.
//If it is not false, this function is being called from itself.
?>
<div class="menu-item">
<label for="text-<?php echo $id_string;?>"><?php echo $menu['id']['otitle'];?></label><input type="text" id="text-<?php echo $id_string?>" value="<?php print($menu['id']['utitle']);?>" />
<?php
//The code above just outputs any information you want into a 'menu-item' div. you can change literally every thing here to your liking. This was fastest for me.
/*
The code below
1. Checks if the $menu array as a key named 'children', and if that is true
2. Checks that the count (or sizeof) the array is greater than 0.
3. If it does, call get_menu_list on the children array, supplying the $id_string we created up top so that we don't have overlapping
ID names in our HTML.
*/
if(array_key_exists('children', $menu) && count($menu['children'])>0){
get_menu_list($menu['children'],$id_string);
}
?></div><?php
//Ends the HTML div we started up top.
endforeach;
//Self explanatory.
}
$array_serial = 'a:2:{i:0;a:2:{s:2:"id";a:4:{s:3:"url";s:27:"products.php?la=electronics";s:6:"otitle";s:11:"Electronics";s:6:"utitle";s:11:"Electronics";s:4:"ttip";s:11:"Electronics";}s:8:"children";a:2:{i:0;a:2:{s:2:"id";a:4:{s:3:"url";s:51:"products.php?la=electronics&lb=Computer-Peripherals";s:6:"otitle";s:20:"Computer Peripherals";s:6:"utitle";s:20:"Computer Peripherals";s:4:"ttip";s:34:"Electronics : Computer Peripherals";}s:8:"children";a:1:{i:0;a:2:{s:2:"id";a:4:{s:3:"url";s:63:"products.php?la=electronics&lb=Computer-Peripherals&lc=Printers";s:6:"otitle";s:8:"Printers";s:6:"utitle";s:8:"Printers";s:4:"ttip";s:45:"Electronics : Computer Peripherals : Printers";}s:8:"children";a:1:{i:0;a:1:{s:2:"id";a:4:{s:3:"url";s:90:"products.php?la=electronics&lb=Computer-Peripherals&lc=Printers&ld=Single-Function-Printer";s:6:"otitle";s:23:"Single Function Printer";s:6:"utitle";s:23:"Single Function Printer";s:4:"ttip";s:71:"Electronics : Computer Peripherals : Printers : Single Function Printer";}}}}}}i:1;a:1:{s:2:"id";a:4:{s:3:"url";s:38:"products.php?la=electronics&lb=Mobiles";s:6:"otitle";s:7:"Mobiles";s:6:"utitle";s:7:"Mobiles";s:4:"ttip";s:21:"Electronics : Mobiles";}}}}i:1;a:2:{s:2:"id";a:4:{s:3:"url";s:31:"products.php?la=homenfurnitures";s:6:"otitle";s:19:"Home And Furnitures";s:6:"utitle";s:19:"Home And Furnitures";s:4:"ttip";s:19:"Home And Furnitures";}s:8:"children";a:2:{i:0;a:1:{s:2:"id";a:4:{s:3:"url";s:9:"about.php";s:6:"otitle";s:8:"About Us";s:6:"utitle";s:8:"About Us";s:4:"ttip";s:8:"About US";}}i:1;a:2:{s:2:"id";a:4:{s:3:"url";s:40:"products.php?la=homenfurnitures&lb=Other";s:6:"otitle";s:5:"Other";s:6:"utitle";s:5:"Other";s:4:"ttip";s:27:"Home And Furnitures : Other";}s:8:"children";a:1:{i:0;a:2:{s:2:"id";a:4:{s:3:"url";s:51:"products.php?la=homenfurnitures&lb=Lights-AnD-Lamps";s:6:"otitle";s:14:"Lights & Lamps";s:6:"utitle";s:14:"Lights & Lamps";s:4:"ttip";s:36:"Home And Furnitures : Lights & Lamps";}s:8:"children";a:2:{i:0;a:1:{s:2:"id";a:4:{s:3:"url";s:12:"contacts.php";s:6:"otitle";s:10:"Contact Us";s:6:"utitle";s:10:"Contact Us";s:4:"ttip";s:10:"Contact US";}}i:1;a:2:{s:2:"id";a:4:{s:3:"url";s:58:"products.php?la=homenfurnitures&lb=Dinnerware-AnD-Crockery";s:6:"otitle";s:21:"Dinnerware & Crockery";s:6:"utitle";s:21:"Dinnerware & Crockery";s:4:"ttip";s:43:"Home And Furnitures : Dinnerware & Crockery";}s:8:"children";a:1:{i:0;a:1:{s:2:"id";a:4:{s:3:"url";s:78:"products.php?la=homenfurnitures&lb=Dinnerware-AnD-Crockery&lc=Cups-AnD-Saucers";s:6:"otitle";s:14:"Cups & Saucers";s:6:"utitle";s:14:"Cups & Saucers";s:4:"ttip";s:60:"Home And Furnitures : Dinnerware & Crockery : Cups & Saucers";}}}}}}}}}}}';
$array_unserial = unserialize($array_serial);
get_menu_list($array_unserial);
?>
On a related note about your data in your serialized
Try to avoid using serialized strings as much as you possibly can. A very simple solution is one I already wrote out to you in the comments, but by creating a table categories with just a few fields you can get the same set of data without having to use array serialization / deserialization. It definitely is a question outside of the topic of this particular question, but I'd feel like I wasn't being very helpful if I didn't at least mention it to you.

Update checkbox and textarea value in mysql db using Jquery

I have textarea and three checkboxs in my mysql db by default textarea value as null and checkboxs values as zero(0).
when i enter some text in textarea i'm updating text value in my mysql db but i gotta stuck in checkbox things can some one suggest how to update checkbox checked value in mysql db
say for example if checkbox is checked/clicked i should be able to update my mysql db with value '1' if not the value will be '0'
https://jsfiddle.net/07wmpjqf/1/
db structure
ID TEXT ABC XYZ LMN
1 NULL 0 0 0
Thanks!
html
<div>
<textarea class="lb_text" rows="6" cols="50" placeholder="Add text here..."></textarea>
</div>
<div>
<label>
<input type='checkbox'>ABC
</label>
</div>
<div>
<label>
<input type='checkbox'>XYZ
</label>
</div>
<div>
<label>
<input type='checkbox'>LMN
</label>
</div>
<div>
<input type="submit" class="lb_save" value="submit">
</div>
php
if(isset($_POST['lb_text']))
{
$live_blog = mysqli_real_escape_string($_POST['lb_text']);
$sql = "update demo set text='".$live_blog."'";
$result = mysqli_query($con, $sql);
}
}
jquery
$(function(){
$(".lb_save").click(function(){
var lb_text = $('.lb_text').val();
if(lb_text == '')
{
alert("Enter Some Text...");
$('.lb_text').focus();
}
else
{
$.ajax({
type: "POST",
url: "index.php",
data:{
lb_text:lb_text,
},
success:function(response){
alert('successfully updated');
}
});
}
return false;
});
});
add id to your check box and capture th value in jquery.
<div>
<label>
<input type='checkbox' id="abc">ABC
</label>
</div>
<div>
<label>
<input type='checkbox' id="xyz">XYZ
</label>
</div>
<div>
<label>
<input type='checkbox' id="lmn">LMN
</label>
</div>
and change your ajax data like this,
data: {
lb_text: lb_text,
abc: $("#abc").is(':checked') ? 1 : 0,
xyz: $("#xyz").is(':checked') ? 1 : 0,
lmn: $("#lmn").is(':checked') ? 1 : 0,
},
and your query like this,
$live_blog = mysqli_real_escape_string($_POST['lb_text']);
$abc = $_POST['abc']
$xyz = $_POST['xyz']
$lmn = $_POST['lmn']
$sql = "update demo set text='".$live_blog."',ABC='".$abc."',XYZ='".$xyz."',LMN='".$lmn."'";

jquery not sending button choice to php

I have a search function that will accept a search string and send it to a php file for parsing a database column. I'd also like users to choose which aspect of the website they'd like to search (comics, artwork, or both). Comic and Artwork or stored in two separate tables.
This is a function that will accept an input search string from the html below and send it to a php file.
<script type="text/javascript">
function search(searchString) {
//var site = $("#site").val();
$.get("./scripts/search.php", {_input : searchString},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
And this is javascript to accept a choice to search "comics", "artwork" or "all".
function searchChoice(choice) {
alert("Choice: " + choice);
$.get("./scripts/search.php", {_choice : choice}
);
}
</script>
HTML:
<!--Search filtering for comics, artwork, or both-->
<span class="search"><b>Search for: </b> </span>
<div class="btn-group" data-toggle="buttons-radio">
<span class="search">
<button type="button" class="btn" id="comics" onclick="searchChoice(this.id)">Comics</button>
<button type="button" class="btn" id="artwork" onclick="searchChoice(this.id)">Artwork</button>
<button type="button" class="btn" id="all" onclick="searchChoice(this.id)">All</button>
</span>
</div>
<br/>
<br/>
<!--Search functionality-->
<span class="search">
<input type="text" onkeyup="search(this.value)" name="input" value="" />
</span>
<br />
<span id="output"><span class="sidebarimages"> </span></span>
PHP excerpt:
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : "all");
You can see the javascript correctly alerting out "Choice: comics" when comics button is selected, but the php side, echo "</br>Choice: " . $siteChoice;, is echo'ing out "all", which is incorrect.
Any ideas would be greatly appreciated!
As mentioned #E_p, that is the problem ... another option is to create a variable and store the data there ... try this: you don't need change the html
var mySearchString = 0;
var myChoice = 'all';
function search(searchString) {
mySearchString = searchString;
GetSearch();
}
function searchChoice(choice) {
myChoice = choice;
GetSearch();
}
function GetSearch(){
$.get("./scripts/search.php", {_input : mySearchString, _choice : myChoice},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
You do not keep state for _choice.
When search is called it does not pass it to a server.
You need to change buttons to option and in search function pass both. to a server at the same time
Replace the buttons with radio buttons and use form.Serialize()
<form id="searchform">
<input type="radio" name="_choice" value="comics" />Comics<br/>
<input type="radio" name="_choice" value="artwork" />Artwork<br/>
<input type="radio" name="_choice" value="all" />All<br/>
<input type="text" onkeyup="search()" name="_input" value="" />
</form>
Javascript
function search() {
//var site = $("#site").val();
$.get("./scripts/search.php", $('#searchform').serialize(),
function(returned_data) {
$("#output").html(returned_data);
}
);
}
The .serialize() function converts form input to JSON so you don't have to type manually, No more parameter, and no two functions, just one to do them all

How to make a div appear from a php variable using jquery

I am populating a list of checkboxes from a foreach loop, and giving each an ID. I have added a set of divs below that would appear, depending on which checkbox is created. I was thinking I could load the id variable into a jQuery if statement, and then use a .toggle to show or hide the corresponding div.
<?php
//Call Programs
$getPrograms = Doctrine::getTable('Program')->createQuery()->where('subsection=?', 'mfa')->orWhere('subsection=?', 'mps')->orWhere('subsection=?', 'mat')->orWhere('subsection=?', 'ma')->orderBy('title ASC')->execute(); ?>
<div class="form_row">
<label>
<span><sup class="required_form_item">*</sup>Select Program</span>
</label>
<div class="buttonColumn" style="margin-left:170px;">
//loop the records in with checkboxes
<?php foreach ($getPrograms as $prog): ?>
<?php
$subsection = $prog->getSubsection();
$subsection = strtoupper($subsection);
$trimProg = trim($prog->getTitle(), ' ');
$removeChars = array(" ", "&");
$trimProg = str_replace( $removeChars, '', $trimProg );
$trimProg = preg_replace('/\s\s+/', '_', $trimProg);
?>
//custin id matches record title
<input type="checkbox" name="program" class="isChecked" id="<?php echo $trimProg; ?>" value="<?php echo $subsection . " " . $prog->getTitle() ?>" /><?php echo $subsection . " " . $prog->getTitle() ?><br />
<?php endforeach ?>
</div>
</div>
The following divs would be set to display:none until the matching checkbox is checked.
<div class="form_row sessionTime" id="Program1" style="display:none;">
Please choose an session time:
<input type="checkbox" name="schedule" value="5:00 pm" />5:00 pm<br />
</div>
<div class="form_row sessionTime" id="program2" style="display:none;">
Please choose an session time:
<input type="checkbox" name="schedule" value="10:00 pm" />10:00 pm<br />
</div>
...
And this is what I thought would work...but alas...it doesn't
$('.isChecked').click( function() {
if ( $(this).is(':checked') ) {
$thisID = $(this).attr("id");
$('.'+ $thisID).show();
}
else {
$('.'+ $thisID).hide();
}
}
);
You should be using "Program1" as class name instead of id like this
<div class="form_row sessionTime Program1" style="display:none;">
Please choose an session time:
<input type="checkbox" name="schedule" value="5:00 pm" />5:00 pm<br />
</div>
And your jQuery code should work, which you can simplify as follows:
$('.isChecked').click( function() {
if ( $(this).is(':checked') ) {
$('.'+ this.id).show();
}
else {
$('.'+ this.id).hide();
}
});
I tested this code # home and it works as you might want
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(
function()
{
$('.isChecked').click(
function()
{
if ( $(this).is(':checked') )
{
$(this).show();
}
else
{
$(this).hide();
}
}
);
}
);
</script>
</head>
<body>
<form>
<input type="checkbox" name="program" class="isChecked"/>
<input type="checkbox" name="program" class="isChecked"/>
<input type="checkbox" name="program" class="isChecked"/>
<input type="checkbox" name="program" class="isChecked"/>
</form>
</body>
I think the problem in your code can come from the $(document).ready() handler that waits for the entire DOM to be loaded before binding action listener to it.
What's more, your jquery code wasn't working for me. My version seems to work, but once checked box hidden, the user cannot handle them anymore.
Otherwise, I think doing some Doctrine requests in your template is a very bad idea.
Good bye !

Categories