Tree menu expand and collapse using PHP - php

I have following array:
$firstlevel=array(“numbers”,”vowels”,”animals”,”birds”);
$numbers=array(“one”,”two”,”three”);
$vowels= array (“a”,”e”,”i”,,”o”,”u”);
$animals=array(“lion”,”tiger”,”dog”,”wolf”,”horse”,”Zebra”);
$birds=array(“parrot”,”sparrow”,”crow”);
I need tree menu like below:(ONLY BY USING PHP)
+ numbers
+ vowels
+ animals
+ birds
Reset button
When clicking it expands like following:
+ Fruits
- Vegetables
+ Drumstick
+ Lady’s finger
+ Animals
+ Birds
The same format should be retain once we click on the other first level item its
corresponding child nodes to be in expanded.

This is For pure css, js and html code. For php refer next section.
$(document).ready(function(){
$('.child').hide();
});
$( "a" ).click(function() {
Show(this);
});
function Show(obj)
{
var ObjId = obj.id;
var Obj = ObjId.split('-');
var id = Obj[0];
var symb = $('#'+id+'-symbol').html();
if(symb.trim() == "+")
{
$('#'+id).show(1000);
$('#'+id+'-symbol').html("- ");
}
else
{
$('#'+id).hide(1000);
$('#'+id+'-symbol').html("+ ");
}
}
ul {
list-style: none;
margin-left:10px;
}
ul>li{
margin-left:15px;
padding-top:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<a id='fruit-a' style='text-decoration:none; color:black;' href='#'>
<span id='fruit-symbol'>+ </span>
Fruit
</a>
<ul class='child' id='fruit'>
<li>* numbers</li>
<li>* vowels</li>
<li>* animals</li>
<li>* birds</li>
</ul>
</li>
</ul>
You can do it like this with php.
<html>
<head>
<style>
ul {
list-style: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.child').hide();
});
function Show(id)
{
var symb = $('#'+id+'-symbol').html();
if(symb.trim() == "+")
{
$('#'+id).show(1000);
$('#'+id+'-symbol').html("- ");
}
else
{
$('#'+id).hide(1000);
$('#'+id+'-symbol').html("+ ");
}
}
</script>
</head>
<body>
<?php
$firstlevel=array("numbers","vowels","animals","birds");
$numbers=array("one","two","three");
$vowels= array ("a","e","i","o","u");
$animals=array("lion","tiger","dog","wolf","horse","Zebra");
$birds=array("parrot","sparrow","crow");
$AllArray = ["firstlevel", "numbers", "vowels", "animals", "birds"];
echo "<ul>";
foreach($AllArray as $a)
{
echo "<li><a onclick=\"Show('".$a."')\" style='text-decoration:none; color:black;' href='#'><span id='".$a."-symbol'>+ </span>".$a."</a><ul class='child' id='".$a."'>";
foreach($$a as $id=>$val)
{
echo "<li>* ".$val."</li>";
}
echo "</ul></li>";
}
echo "</ul>";
?>
</body>
</html>
You can see result through this link https://www.tehplayground.com/5SHAWKeEcsm5O5Ww

use jquery with php u will get i did same thing try this......
include this first
<div class="menu_list" id="secondpane"> <!--Code for menu starts here-->
<p class="menu_head">Data Warehousing</p>
<div class="menu_body">
Teradata Online training
Informatica Online training
Cognos Online training
</div>
<p class="menu_head">SAP</p>
<div class="menu_body">
SAP BO
SAP ABAP
SAP BI/BW
SAP FICO
SAP HR
</div>
<p class="menu_head">ORACLE</p>
<div class="menu_body">
ORACLE DBA
ORACLE 11g
</div>
<p class="menu_head">SQL</p>
<div class="menu_body">
SQL DBA
</div>
<p class="menu_head">JAVA</p>
<div class="menu_body">
Core JAVA
Advanced JAVA
</div>
<p class="menu_head">SAS</p>
<div class="menu_body">
SAS BI
SAS CDM
</div>
<p class="menu_head">Testing Tools</p>
<div class="menu_body">
Manual Testing+QTP Training
ETL Testing
SELENIUM Training
</div>
<p class="menu_head">Android Training</p>
<div class="menu_body">
Android Course
</div>
<p class="menu_head">Sharepoint Training</p>
<p class="menu_head">.NET Training</p>
<div class="menu_body">
ASP .NET Training
C# Training
</div>
</div>
add these styles
#charset "utf-8";
/* CSS Document */
body {
margin: 10px auto;
font: 105%/140% Verdana,Arial, Helvetica, sans-serif;
}
.menu_list {
width:250px;
}
.menu_head {
padding: 5px 10px;
cursor: pointer;
position: relative;
margin:1px;
font-weight:bold;
background:#83C7DA url(left.png) center right no-repeat;
font-size:15px;
color:black;
border-radius:5px;
}
.menu_body {
display:none;
}
.menu_body a{
display:block;
color:#C00;
background-color:#EFEFEF;
padding-left:10px;
font-weight:bold;
text-decoration:none;
}
.menu_body a:hover{
color: #000000;
text-decoration:underline;
}
integrate jQuery.js library then only it will work.....
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
<!--//---------------------------------+
// Developed by Roshan Bhattarai
// Visit http://roshanbh.com.np for this script and more.
// This notice MUST stay intact for legal use
// --------------------------------->
$(document).ready(function()
{
//slides the element with class "menu_body" when mouse is over the paragraph
$("#secondpane p.menu_head").mouseover(function()
{
$(this).css({backgroundImage:"url(down.png)"}).next("div.menu_body").slideDown(500).siblings("div.menu_body").slideUp("slow");
$(this).siblings().css({backgroundImage:"url(left.png)"});
});
});
</script>

First of all, you need to create a table like this:
CREATE TABLE IF NOT EXISTS `menus` (
`cid` int(10) NOT NULL,
`name` varchar(20) NOT NULL,
`parent_cat` int(10) NOT NULL,
PRIMARY KEY (`cid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `menus` (`cid`, `name`, `parent_cat`) VALUES
(1, 'numbers', 0),
(2, 'vowels', 0),
(3, 'one', 7),
(4, 'two', 7),
(5, 'a', 2),
(6, 'e', 2),
(7, 'ones', 1),
(8, 'tens', 1),
(9, 'ten', 8),
(10, 'twenty', 8);
Download this plug-in
and here is my php code for creating expand and collapse menu:
<?php
$viewsql = "SELECT * FROM menus";
$viewsqlres=mysql_query($viewsql);
while ( $viewsqlrow = mysql_fetch_array($viewsqlres)) {
$viewarray[$viewsqlrow['cid']] = array('cid'=>$viewsqlrow['cid'],'name' => $viewsqlrow['name'],'parent_cat' => $viewsqlrow['parent_cat']);
}
function view_generate_menu($parent_cat_view) //recursive function that prints category as a nested html unorderd list
{
$has_childs_view = false;
////this prevents printing 'ul' if we don't have subcategory for this category
global $viewarray;
////use global array variable instead of a local variable to lower stack memory requierment
foreach($viewarray as $key => $value_view) {
if ($value_view['parent_cat'] == $parent_cat_view) {
//if this is the first child print '<ul>'
if ($has_childs_view === false) {
//don't print '<ul>' multiple times
$has_childs_view = true;
?>
<ul id="tree">
<?php } ?>
<li><?php echo $value_view['name']; ?>
<?php
view_generate_menu($key);
////call function again to generate nested list for subcategory belonging to this category
echo '</li>';
}
}
if ($has_childs_view === true) echo '</ul>';
}
view_generate_menu(0);
?>
some styling:
<style>
#tree li {
list-style: none outside none;}
</style>

Related

Bad redirect when translating with php using a button: <a href="?lang=en">

I have managed to translate an example web page using an array, the problem I have found is that when pressing the button (it is used to translate) it directs you to the index, and what I want is to translate the page where you are you find.
I leave you the code in addition to some image:
<div class = "menu">
<ul>
<li>
<? php echo $ lang ['home']?>
</li>
<li>
<? php echo $ lang ['about']?>
</li>
<? php
include ('menu.php');
?>
<li class = "right">
<? php echo $ lang ['Spanish']?>
</li>
<li class = "right">
<? php echo $ lang ['catalan']?>
</li>
<li class = "right">
<? php echo $ lang ['english']?>
</li>
</ul>
https://ibb.co/w62zkDM
I don't know how to do it any other way, I don't know if what I'm trying to do can be done, I have the translations in a single folder.
sorry for my english i'm using google translate.
I have also used:
but it redirects me to index anyway.
Sorry for my english i´m using google translate.
Your requirement is to translate the language of a page. Iam not sure how much the below solution using JS will helps.
<html>
<head>
<style>
.goog-te-banner-frame.skiptranslate {
display: none !important;
}
.goog-gt-tt{
display:none;
width:0px;
height:0px;
}
a{
cursor:pointer;
}
#button{
background:#3399ff;
padding:5px 10px;
box-shadow:0px 6px 16px -6px rgba(1,1,1,0.5);
border:0;
outline:none;
margin:0px 10px;
}
</style>
</head>
<body>
<a onclick="changeLanguageByButtonClick('de')" id='button'>German</a>
<a onclick="changeLanguageByButtonClick('es')" id='button'>Spanish</a>
<a onclick="changeLanguageByButtonClick('en')" id='button'>English</a>
<!--PAGELOADER-->
<div id="google_translate_element" style="display:none"></div>
<h1>Google Translator:Default Language English</h1>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<script>
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: "en"}, 'google_translate_element');
}
function changeLanguageByButtonClick(language) {
var selectField = document.querySelector("#google_translate_element select");
for(var i=0; i < selectField.children.length; i++){
var option = selectField.children[i];
// find desired langauge and change the former language of the hidden selection-field
if(option.value==language){
selectField.selectedIndex = i;
// trigger change event afterwards to make google-lib translate this side
selectField.dispatchEvent(new Event('change'));
break;
}
}
}
</script>
</body>
</html>

My External JavaScript files stopped working after successful ajax call to reload a div

I'm building a simple chat system using Ajax, jQuery, PHP, MySQLi.
On the chatting page, jquery post request is set to handle user sent messages.
Now the problem is, when I sends a message to a user, the message will be sent successfully, on trying to update the div (chat messages), some of my externally included js files in the index page will stop working. See jQuery code below:
$(function(){
$("#send-msgs").click(function(e){
/* Auto Detect A Link (START)*/
// Get the content
var output = $("#message").val();
var chat_id = $("#chat_id").val();
e.preventDefault();
//Start Post Request
$.ajax({
type: "POST",
url: "post_message.php",
data: "message_text="+output+"&chat_id="+chat_id,
cache: false,
beforeSend: function(){
//Show Events before sending request
$(".chat-main .active .details h6").html("<span class='text-primary'>You: </span><span class='text-secondary'>Sending...");
$(".chat-main .active .date-status h6#time_status").html("--:-- --");
$(".chat-main .active .date-status h6#msg_status").html("<span title='Sending...' class='fa fa-ellipsis-h'></span>");
$("#setemoj").attr({
"disabled" : "disabled",
});
$("#send-msg").attr({
"disabled" : "disabled",
});
},
//If everything looks right, continue
success: function(response){
$.ajax({
type: "POST",
url: "only_load_chat.php",
data: "phone_number=<?php echo #$phone_number1;?>&chat_id="+chat_id,
cache: false,
success: function(response){
// alert(response);
var current_time = $("#js_current_time").val();
var msg = $("#setemoj").val();
$(".chat-main .active .details h6").html("<span class='text-primary'><b>You:</b> </span><span class='text-secondary'>"+output+"</span>");
$(".chat-main .active .date-status h6#time_status").html(current_time);
$(".chat-main .active .date-status h6#msg_status").html("<span title='Seen'><span title='Sent' class='fa fa-check text-primary'></span></span>");
// $(".chat-main .active .details .date-status h6").html(js_current_time);
$("#fetch_chat").html(response);
document.getElementById("setemoj").removeAttribute("disabled");
document.getElementById("setemoj").value = "";
},
})
}
});
});
});
post_message.php file
if($_SERVER['REQUEST_METHOD'] == "POST"){
session_start();
require "./includes/db-config.php";
require "./includes/check_if_login.php";
require "./includes/SaNiTiZer.php";
require "./includes/function.php";
if(isset($_REQUEST['chat_id']) && isset($_REQUEST['message_text'])){
$user_msg = htmlspecialchars($_REQUEST['message_text']);
$chat_id1 = $_REQUEST['chat_id'];
$sql = mysqli_prepare($conn, "INSERT INTO direct_chats_msg(`message`, `user_id`, chat_id) VALUES(?,?,?)");
mysqli_stmt_bind_param($sql, 'sii', $user_msg, $user_id, $chat_id1);
mysqli_stmt_execute($sql);
echo "Done";
} else {
echo "Error in POST request";
}
} else {
echo "Error in POST request";
}
only_load_chat.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST"){
session_start();
require "./includes/db-config.php";
require "./includes/check_if_login.php";
require "./includes/SaNiTiZer.php";
require "./includes/settings.php";
require "./includes/function.php";
$phone_number1 = $_REQUEST['phone_number'];
$main_chat_id = $_REQUEST['chat_id'];
?>
<!--<script src="./assets/js/owl.carousel.js"></script>-->
<!--<script src="./assets/js/tippy-bundle.iife.min.js"></script>-->
<!--<script src="./assets/js/bootstrap.js"></script>-->
<!--<script src="./assets/js/switchery.js"></script>-->
<!-- <script src="./assets/js/easytimer.min.js"></script> -->
<!-- <script src="./assets/js/index.js"></script> -->
<!-- <script src="./assets/js/popper.min.js"></script> -->
<!-- <script src="./assets/js/feather-icon/feather.min.js"></script>-->
<!-- <script src="./assets/js/feather-icon/feather-icon.js"></script>-->
<!-- <script src="./assets/js/zoom-gallery.js"></script> -->
<!-- <script src="./assets/js/script.js"></script> -->
<ul class="chatappend">
<?php
$sql = mysqli_prepare($conn, "SELECT * from direct_chats_msg where chat_id=?");
mysqli_stmt_bind_param($sql, 'i', $main_chat_id);
mysqli_stmt_execute($sql);
$get_result = mysqli_stmt_get_result($sql);
if(mysqli_num_rows($get_result)>0){
while($row2 = mysqli_fetch_array($get_result)){
$sender = $row2['user_id'];
$sql2 = mysqli_prepare($conn, "SELECT id, userID, FirstName, LastName, OtherName, DisplayName, reg_date,
about_text, profile_pic, gender, countryCode, phone_number, `address`, `state`, country, website, is_online from accounts where id=?");
mysqli_stmt_bind_param($sql2, 'i', $sender);
mysqli_stmt_execute($sql2);
$get_result2 = mysqli_stmt_get_result($sql2);
$row4 = mysqli_fetch_array($get_result2);
$chat_msg_id = $row2['dcm_id'];
?>
<li style="margin:15px;" class="<?php if($row2['user_id']==$user_id){echo"replies";}else{echo"sent";}?>">
<div class="media">
<div class="profile mr-4"><img class="bg-img" src="./assets/images/avtar/new/<?php echo $row4['profile_pic'];?>" alt="<?php echo $row4['LastName']." ".$row4['FirstName'];?>" /></div>
<div class="media-body">
<div class="contact-name">
<!-- <h5><?php echo $row4['LastName']." ".$row4['FirstName'];?></h5> -->
<h6><?php echo date("h:i:s A", strtotime($row2['chat_time']));?></h6>
<ul class="msg-box">
<li class="msg-setting-main">
<div class="msg-dropdown-main">
<div class="msg-setting"><i class="fa fa-ellipsis-h"></i></div>
<div class="msg-dropdown" style="box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);margin-top:-15px;margin-left:-100px;">
<ul>
<li><i class="fa fa-share"></i>forward</li>
<li><i class="fa fa-clone"></i>copy</li>
<li><i class="fa fa-star-o"></i>rating</li>
<li><i class="ti-trash"></i>delete</li>
</ul>
</div>
</div>
<h5 class="msg-content" id="msg-content<?php echo $row2['dcm_id'];?>" style="<?php if($row2['user_id']==$user_id){echo"background-color:#1c9dea;color:#ffffff;padding:7px;";}else{echo"background-color:#e5edf5;color:#000;padding:7px;";}?>">
<?php echo htmlspecialchars_decode($row2['message']);?><br/>
</h5>
</li>
<div id="link_title<?php echo $chat_msg_id;?>"></div>
<!--</li>-->
<style>
.custom_emoji {
width: 20px;
height: 20px;
background-origin: content-box;
color: transparent;
text-align: center;
padding: 3px;
}
.msg-content a {
color: #FF9800;
text-decoration: none;
border-bottom: 1px dotted #000;
}
.msg-content a:hover { color: #ffffff; }
</style>
</li>
<!-- <script>
function newMesssage() {
var message = $('.message-input input').val();
if($.trim(message) == '') {
return false;
}
// var today = new Date(),
// h = checkTime(today.getHours()),
// m = checkTime(today.getMinutes()),
// s = checkTime(today.getSeconds());
// document.getElementById('cur_time').innerHTML = h + ":" + m + ":" + s;
var current_time = $("#js_current_time").val();
$('<li class="replies" style="margin:15px;">\
<div class="media"> \
<div class="profile mr-4 bg-size" style="background-image: \
url("./assets/images/avtar/new/<?php // echo $profile_pic;?>"); background-size: \
cover; background-position: center center;"></div>\<div class="media-body">\
<div class="contact-name"> <h5> </h5> <h6 id="cur_time">'+current_time+'</h6> \
<ul class="msg-box"> <li> <h5 style=background-color:#1c9dea;color:#ffffff;padding:7px;>\
' + message + '</h5> </li></ul> </div></div></div></li>').appendTo($('.messages .chatappend'));
$('.message-input input').val(null);
$('.chat-main .active .details h6').html('<span>You: </span>' + message);
$(".messages").animate({ scrollTop: $(document).height() }, "fast");
};
</script> -->
</ul>
</div>
</div>
</div>
</li>
<?php require "./includes/current_user_chat_profile(right_sidebar).php";?>
<?php
}
?>
</ul>
<?php
} else {?>
<!-- node.js -->
<?php require "./includes/current_user_chat_profile(right_sidebar).php";?>
<script src="./assets/js/owl.carousel.js"></script>
<script src="./assets/js/popper.min.js"></script>
<script src="./assets/js/tippy-bundle.iife.min.js"></script>
<script src="./assets/js/bootstrap.js"></script>
<script src="./assets/js/switchery.js"></script>
<script src="./assets/js/easytimer.min.js"></script>
<script src="./assets/js/index.js"></script>
<script src="./assets/js/feather-icon/feather.min.js"></script>
<script src="./assets/js/feather-icon/feather-icon.js"></script>
<script src="./assets/js/zoom-gallery.js"></script>
<script src="./assets/js/script.js"></script>
<?php
}
} else {
require "./includes/error.php";
}
// } else {
// require "./includes/error.php";
// }
?>
The externally included js files in the only_load_chat.php, when the comments are removed it would make the included js files in the index page not to work (But making the page load too slow), Even after viewing the codes via the developer mode (Ctrl+Shift+I Key), I will be seeing duplicates of the js files.
Please can someone help with me this:
I don't want the externally included js files in the index page disabled, because when disabled, that would make me to include the js files it in the only_load_chat.php, as this would make the website load very slow.
Thanks

How to access a model method with javascript

Please have a look at the below CakePHP code
Flip2.php (Model)
<?php
class Flip2 extends AppModel {
var $name = 'Flip2';
public $useTable = false;
//Increment the correct_answer field of the specific user
public function correctAnswer($userID=89, $word)
{
$setQuery = "UPDATE `users_words` SET `correctanswer` = `correctanswer`+1 WHERE `userid`=$userID && `wordid`='$word' ";
query($setQuery);
}
}
Flip2Controller.php (Controller)
<?php
class Flip2Controller extends AppController {
public function index()
{
}
}
?>
index.ctp (View)
<?php
//echo $this->Html->css(array('bootstrap', 'mark', 'style'));
echo $this->Html->script(array('timer','swfobject','bootstrap.min.js'));
?>
<style>
#hideall {
display: none;
opacity: 0.7;
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000;
border: 1px solid #cecece;
z-index: 1;
vertical-align:middle;
text-align:center;
}
.removeCardflip{
transition: rotateY(0deg);
-webkit-transition: rotateY(0deg);
transition-duration: 0s;
}
/* SECTIONS */
.section {
clear: both;
padding: 0 10px 0 10px;
margin: 0px;
}
</style>
<div id="hideall">
<?php //echo $this->Html->image('progress.gif', array('alt' => 'Wait', 'style' => 'text-align:center; padding-top:200px;'));?>
</div>
<!--<div class="wrapper" style="border: 1px solid red; width: 100%;">-->
<div class="section group" style="margin-top: 50px;">
<div class="col span_3_of_3">
<h3 style="margin:0px; font-size:22px;">Play word game: </h3>
</div>
</div>
<div class="">
<div>
<div>
<span class="remainWords"><?php //echo count($words);?></span> oxxxxxxxxxxxxxxxf <?php //echo $totalWords;?>
</div>
<div>
<?php
echo $this->Html->image("comic_edit.png",
array(
"alt" => "Pareto List",
"id" => "paretoList",
'url' => "javascript:;"
)
);
?>
</div>
</div>
</div>
<div class="container"><div class="row">
<?php
foreach($worddeck as $worcard)
{
?>
<div class="xy col-lg-3 col-md-4 col-sm-6 img-rounded" id="card1" style="width:250px; height:200px; background-color:grey; heiht:170px; margin: 10px 10px;">
<div id="enside1" >
<h1 data-pos="<?php //echo ; ?>" ><?php echo $worcard['unique_wordsforcards']['en_word']; $enSpell = $worcard['unique_wordsforcards']['en_word']; ?></h1>
</div>
<div id="ptside1" style="display:none;">
<?php echo $phonemer[$enSpell]; ?>
<p><?php echo $worcard['unique_wordsforcards']['hint']; ?></p>
</div>
<div id="cntrol1">
<button type="button" id="2" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
</div>
<?php
}
?>
</div></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript">
$(document).ready(function(){
$( ".btn-danger" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".btn-success" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".xy" ).click(function(){
$(this).find("#enside1").toggle();
$(this).find("#ptside1").toggle();
console.log(this);
});
});
</script>
Now, what I need to do is, this. When the user click on the Acertei button, I need to execute the function correctAnswer. I am very new to PHP and CakePHP so I am really confused about how to do this when a button is clicked. Any advice please?
You have
<div id="cntrol1">
<button type="button" id="2" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
You should use different IDs for each button.
You can call the correctAnswer function with ajax:
Change the button to something like
<button type="button" id="2" data-word="<?php $worcard['unique_wordsforcards']['en_word'] ?>" class="a btn btn-success mr5 btn-lg">Acertei</button>
And then add the following code in $(document).ready()
$(document).ready(function(){
$(".btn-success").click(function(){
var word = $(this).data('word');
$.post('/flip2/correct.json', { word: word })
.done(function(data) {
alert('Saved');
});
I am not sure how the user part works. You should probably have that in the session, and not sent to the function. I hardcoded user 89 and added a way for you to send the word.
Use an appropriate model method
The function correctAnswer in the model would better be written using updateAll:
public function correctAnswer($userId, $word) {
return $this->updateAll(
array('correctanswer' => 'correctanswer + 1'),
array(
'userid' => $userId,
'wordid' => $word
)
);
}
Written in this way the inputs ($userId and $word) will be escaped appropriately and not susceptible to sql injection.
Create a controller action
The doorway to the web for an application is a controller action, create a simple function, calling the model method, and write it to output json:
public function correct() {
$postData = $this->request->data;
$word = $this->request->data['word'];
$userId = $this->Auth->user('id');
$result = false;
if ($userId && $word) {
$result = $this->Flip2->correctAnswer($userId, $word);
}
$this->set('_serialize', array('result'));
$this->set('result', $result);
}
Note that
It'll only work via a post request.
The Auth component (the session) is used to get the current user id, it's not a user-defined input.
This function is defined such that it'll work as a json response.
There's no need to create a view file with the above code.
Be sure to setup your app to handle json requests:
After adding Router::parseExtensions('json'); to your routes file, CakePHP will automatically switch view classes when a request is done with the .json extension, or the Accept header is application/json.
Call the controller action
The required js would be of the form:
$(".btn-success").click(function(){
var word = ...;
$.post(
'/flip2/correct.json',
{word: word},
function (data) {
console.log(data);
// {result: bool}
}
);
});
Note that:
The url ends in .json which is a simple and robust way to provoke CakePHP to respond as json.
It is a post request.
The response will be of the form defined by _serializein the controller action.

Saving menu sorting position to backend

Introduction
I currently use the jQuery .sortable function and it works like a charm. However this is only client side and I would like to store the new sorting position to the backend (mySQL database).
I store the sorting order using numerical field (and retrieved using SQL ORDER BY).
Menu text Sorting ID
------------ ---------
Menu item #1 => 0
Menu item #2 => 1
Menu item #3 => 2
Menu item #4 => 3
Current HTML code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Sortable - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
#sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; }
#sortable li span { position: absolute; margin-left: -1.3em; }
</style>
<script>
$(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
});
</script>
</head>
<body>
<ul id="sortable">
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Menu item #1</li>
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Menu item #2</li>
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Menu item #3</li>
<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Menu item #4</li>
</ul>
</body>
</html>
Tinker.io link: http://tinker.io/b3f27
The question
Now, how would I store the new position into the database? Adding an ID to the sortable and posting it back to a php script which would lookup both sorting positions and switch them over is what I would do but I'm looking forward for your opinions.
This is basic idea is sending data using AJAX after update:
JS:
$("#sortable").sortable({
update : function () {
var items = $('#sortable').sortable('serialize');
$.get("sort.php?"+items);
}
});
HTML:
<ul id="sortable">
<li id="s_1" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Menu item #1</li>
<li id="s_2" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Menu item #2</li>
<li id="s_3" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Menu item #3</li>
<li id="s_4" class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Menu item #4</li>
</ul>
Here you need to set id to each LI, please see working demo
PHP:
<?php
var_dump($_GET);
?>
You can find more detailed answers here

drag multiple elements at the same time to the drop area

I'm new to jQueryUI and I'm not able to drag multiple <li> elements to the drop area. However I managed to drag one and drop it on the drop area. Please can anyone help me with this.
JavaScript
$(function() {
$trash= $( "#trash" );
$("a", ".polaroids").draggable({
zIndex: 999,
revert: "invalid" ,
helper: function(){
$copy = $(this).clone();
return $copy;},
appendTo: 'body',
scroll: false
});
$("a", ".polaroids").selectable();
$trash.droppable({
accept: ".polaroids a",
activeClass: "custom-state-active",
drop: function( event, ui ) {
$(this).append(ui.draggable);
}
});
});
Here is the <div> in which the <li> elements are dragged but one by one
<div class="st_view_container">
<div class="st_view">
<?php
foreach($gpID as $k => $v) {
?>
<div id="stv_content_<?php echo $v;?>" class="st_tab_view st_first_tab_view">
<ul class="polaroids" id ="polaroids">
<?php
$sql2=mysql_query("select * from user_group WHERE group_id='$v' AND user_id=3");
$i=1;
while($row=mysql_fetch_array($sql2)) {
$memid=$row['member_id'];
$sql1=mysql_query("select * from users_profile WHERE uid='$memid'");
while($row1=mysql_fetch_array($sql1)) {
$ufname=$row1['fname'];
$ulname=$row1['lname'];
$upic=$row1['profile_pic'];
?>
<li>
<a href="#" title="<?php echo $ufname; ?>">
<img src="../<?php echo $upic; ?>" rel="<?php echo $row1['uid']?>" width="65px" height="65px" />
</a>
</li>
<?php
if($i%6==0) {;}
$i++;
}
?>
</ul>
</div>
<?php } ?>
</div> <!-- /.st_view -->
</div> <!-- /.st_view_container -->
and here is the <div> in which i want the multiple elements to be dropped, but not one by one.
<div id="trash" style="width:200px; height:200px; border:1px solid;">
<h4 class="ui-widget-header"><span class="ui-icon ui-icon-trash">Trash</span> Trash</h4>
</div>
Here is a demo based on some research…
Is it possible to link two jquery.ui draggables together?
grouping draggable objects with jquery-ui draggable
Can't drop jquery ui helper on droppable
How to reimplement jQuery's default helper in a custom helper
and me playing with the jQueryUI droppable photo manager demo which is what you are using as a template.
Functionality includes single click and drag (as is the default behaviour) or use Ctrl+left click to select multiple items and then drag. The drag helper function is used to select all the items with class="selected" and the drop function is customised to extract the img elements from the container the drag helper added them to. The other function simple enables the Ctrl+click behaviour.
The following code is duplicated below from the demo but does require jQuery, jQueryUI and one of the jQueryUI themes.
HTML
<ul id="draggable">
<li><img src="nature-q-c-50-50-1.jpg" alt="" /></li>
<li><img src="nature-q-c-50-50-2.jpg" alt="" /></li>
<li><img src="nature-q-c-50-50-3.jpg" alt="" /></li>
<li><img src="nature-q-c-50-50-4.jpg" alt="" /></li>
<li><img src="nature-q-c-50-50-5.jpg" alt="" /></li>
<li><img src="nature-q-c-50-50-6.jpg" alt="" /></li>
</ul>
<div id="trash">
<h4 class="ui-widget-header">Trash<span class="ui-icon ui-icon-trash"></span></h4>
</div>
CSS
body {
font-family:"Trebuchet MS";
}
#draggable {
margin:0;
padding:10px;
width:300px;
list-style-type:none;
background-color:#000;
}
li {
display:inline;
}
img {
border:5px solid white;
}
.image-group img {
margin-right:5px;
}
#trash {
margin-top:10px;
width:200px;
height:200px;
border:1px dotted #000;
}
.selected {
border-color:#aed0ea
}
#trash h4 {
margin:0;
padding:0 5px;
}
.ui-icon {
display:inline-block;
}
JavaScript
$('#draggable li').draggable({
revertDuration:100,
helper:function() {
var selected = $('#draggable img.selected');
if (selected.length === 0) {
selected = $('img', $(this)).addClass('selected');
}
console.log('selected', selected);
var container = $('<div class="image-group"/>');
container.append(selected.clone());
console.log('container', container);
return container;
},
cursorAt:{ left:25,top:25 }
});
$('#trash').droppable({
drop: function(event, ui) {
var newItems = $(ui.helper).find('img').clone(false)
.removeClass('selected');
$(this).append(newItems);
console.log('ui.draggable', ui.draggable);
$('#draggable img.selected').parent().remove();
}
});
$('#draggable li').click(function(event) {
if (event.ctrlKey) {
$('img', $(this)).toggleClass('selected');
}
});

Categories