php database, jquery dynamic content load - php

I would like to achieve such an effect, except that when you click on the picture (link) jquery script sends a GET to the same file from the fact that with another ID. I mean the dynamic reload the page without refreshing the addition of a nice effect in the attached link.
my code :
<script>
$('a.menu').click(function(){
$('.content').html('');
})
</script>
<div class="content" id="page_effect" style="padding:0px; display:none;">
<div class="separator" style="margin: -17px auto;"></div>
<span class="choose-product"> Wybierz Produkt</span>
<p>
<?php
$kat=$_GET['kat'];
$co_ile_strona=9;
//----------------
$dopisz="";
if (is_numeric($kat)) {
$dopisz=" WHERE kat_id='".$kat."'";
$wyk=mysql_query("SELECT * FROM kategorie WHERE kat='".$kat."'");
while($ww=mysql_fetch_array($wyk)) {
$dopisz.=" OR kat_id='".$ww['id']."'";
}
}
$sile=false;
$wyk=mysql_query("SELECT * FROM produkty ".$dopisz."");
if ($ile=mysql_num_rows($wyk)) {
if (!$sile) {
$nazwa = mysql_fetch_assoc(mysql_query("SELECT * FROM kategorie WHERE id='".$_GET['kat']."'"));
if(strlen($nazwa['nazwa']) > 0)
$nazwa = $nazwa['nazwa'];
?>
<div style="text-align: center; width: 80%;margin: 0 auto;margin-top: 39px;">
<a href="produkt.html"><div class="product-box">
<img src="images/picasso0.png" alt="Product"/>
<span class="product-title"><?=$nazwa?></span>
</div>
</a>
<?
$sile=true;
}
if (!$_GET['strona']) $strona=1; else $strona=$_GET['strona'];
$start=($strona*$co_ile_strona)-$co_ile_strona;
mysql_data_seek($wyk,$start);
$licz=0;
while(($ww=mysql_fetch_object($wyk)) && $licz<$co_ile_strona) { $licz++;
?>
<a href="<?=strtolower(seo($ww->nazwa))?>-<?=$ww->id?>p.html"><div class="product-box">
<img src="produkty/front/<?=$ww->front?>" alt="<?=$ww->nazwa?>"/>
<div class="name2"><span><?=$ww->nazwa?> </span></div>
</div>
</a>
<?
}
} else echo "<span style='color: #ff0000; font-size: 12pt; font-weight: bold;'>Przepraszamy, ale nie znaleziono produktów pasujących do tego zapytania</span>";
?>
</div>
<div class="menu-bottom" style="text-align:center;">
<span style="position: relative;top: 25px;display: inline-flex;margin-bottom: 20px;">Wybierz serię:
<ul>
<?php
$zapas=$_GET['kat'];
$wyk=mysql_query("SELECT * FROM kategorie WHERE kat='0' and wid='1' ORDER BY poz ASC");
while($ww=mysql_fetch_object($wyk)) {
?> <!--<?/*=$ww->nazwa?>-<?=$ww->id*/?>k.html*/-->
<li> <? if($_GET['kat']==$ww->id) echo "<span style='color: #000;'>".$ww->nazwa.""; else echo $ww->nazwa?></li>
<? } ?>
</ul>
</span>
</div>
<!-- end .content --></div>
link : Click here

As mentioned in the comment, you should send an AJAX request to the page that is responsible for handling the database tasks. You can use get() or post() function which is a shorthand of AJAX function as stated in jQuery documentation.
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
I've prepared a simple jsFiddle demonstrating how the task can be achieved (please note the event.preventDefault() call):
$(document).ready(function(){
$("button").click(function(e){
var URL = '';
$.get(URL,function(data){
console.log("Status: " + status);
e.preventDefault();
});
});
});
Hope that helps.

Related

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

Ajax only retuen one value, but i need it to retun all the value that falls under one condition [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Ajax return only one product under range filter condition (products under price 68000) but actually database column price has more then one value under this range.
Here Database return result
public function Range(){
$conn=$this->makeConnection();
$query="select * from persons order by price desc";
$result = mysqli_query($this->conn,$query);
if(mysqli_num_rows($result) > 0){
return $result;
}else{
echo "No results";
}
}
Here i get the result in Html file
<?php
include("model/DALitem.php");
$obj=new DALitem();
$result=$obj->ViewData();
$range=$obj->Range();
?>
</div>
<div align="center">
<input type="range" min="0" max="100000" step="1000" value="1000" name="min_price" id="min_price">
<span id="price_range"></span>
</div>
<br><br>
<div class="row" id="product_loading">
<?php
while ($row = mysqli_fetch_array($range)) {
?>
<div class="col-3">
<img <?php echo "src=\"assets/uploadedImages/".$row['file']."\""?> class="img img-fluid" style="height: 300px; width: 200px; background-color: teal">
<h3><?php echo $row['name'] ?></h3>
<h4>Price - <?php echo $row['price'] ?></h4>
</div>
<?php
}
?>
</div>
Here is JQuery Script
$(document).ready(function() {
$('#min_price').change(function() {
var price = $(this).val();
$('#price_range').text('Product under price Rs. '+ price);
$.ajax({
url: 'load_product.php',
type: 'POST',
data: {price: price},
success:function(data){
$('#product_loading').html(data);
console.log(data);
}
});
});
});
Here is load_product file to which Ajax interact
<?php
include("model/config.php");
if (isset($_POST['price'])) {
$output='';
$query="select * from persons where price <=".$_POST['price']."";
$result=mysqli_query($conn,$query);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
$output='
<div class="col-3">
<img src="assets/uploadedImages/'.$row['file'].'" class="img img-fluid" style="height: 300px; width: 200px; background-color: teal">
<h3>'.$row['name'].'</h3>
<h4>Price - '.$row['price'].'</h4>
</div>
';
}
} else {
$output='No Product Found';
}
echo $output;
}
?>
results under this code are
I'd suggest you change your code a little bit instead of loading the whole .php file go for a JSON approach
So in your DB return
return json_encode($result);
In your jQuery you can use $.each function that jQuery offers
$.getJSON("url_with_json_here", function(data){
$.each(data, function (index, value) {
console.log(value);
});
});
source: JQuery Parsing JSON array
Doc : http://api.jquery.com/jquery.each/
So once your set up your $.each you can use jQuery's .append() function
Doc: http://api.jquery.com/append/
So in the end your jQuery code should look a bit like this
$(document).ready(function() {
$('#min_price').change(function() {
$("#product_loading .col-md-3").remove();
$.getJSON("url_with_json_here", function(data){
$.each(data, function (index, value) {
$("#product_loading").append(`
<div class="col-md-3">
`+ value +`
</div>
`);
});
});
});
});
Please check the changes, it should work now.
$output='';
$query="select * from persons where price <=".$_POST['price']."";
$result=mysqli_query($conn,$query);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result)) {
$output .='
<div class="col-3">
<img src="assets/uploadedImages/'.$row['file'].'" class="img img-fluid" style="height: 300px; width: 200px; background-color: teal">
<h3>'.$row['name'].'</h3>
<h4>Price - '.$row['price'].'</h4>
</div>
';
}
} else {
$output='No Product Found';
}
echo $output;} ?>

PHP / AJAX not getting return

I am using AJAX to receive data from my database on to my main PHP page.
I have a piece of code that worked, but on with PHP.
When I have just tried to put it in to AJAX (receiving format), the code that I return is not being shown.
I know my AJAX method works as I'm using it to get some other database values.
It's just the Get online users individually won't work.
When I load the page, the code shows what's inside my div id - Loading Info... and then goes blank, so I know it's trying to update it but it's not getting it correctly.
Picture showing that nothing is displayed
My PHP request code is :
//Get online users individually and echo if they're online or not in a div class
$user_grab = mysqli_query($con, "SELECT * FROM users");
while($users_ = mysqli_fetch_array($user_grab)) {
$last_online = strtotime($users_['lastonline']);
if(time() - $last_online < 30) {
$client_is_online = '
<div class="chat-list-item -available" style="background: rgba(255,255,255,0.1); padding: 5px;">
<img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
<div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
<div class="chat-list-excerpt">Online</div>
</div>
';
} else {
$client_is_online = '
<div class="chat-list-item -offline" style="background: rgba(255,255,255,0.1); padding: 5px;">
<img class="chat-list-avatar" src="'.$users_['profile_picture'].'" style="width: 40px; height: 40px; padding: 7px; border-radius: 20px;" /><i class="fa fa-circle chat-list-status"> </i>
<div class="chat-list-user">'.$users_['username'].' (<font size="2">'.get_users_level_all($users_['userLevel']).'</font>)</div>
<div class="chat-list-excerpt">Offline</div>
</div>
';
}
}
//I then echo it back to my home PHP page so it can read the values
//Ignore my other code definitions below as I know they work
//$client_is_online is the only one which doesn't
echo $totalUsers.",".$totalOnline.",".$freemode.",".$bypasses.",".$client_is_online;
My AJAX recieve code is :
<script>
function fetchOnline() {
$.ajax({
url: "includes/get_dash_settings.php",
context: document.body,
success: function(value){
var data = value.split(",");
$('#totalUsers').html(data[0]);
$('#totalOnline').html(data[1]);
$('#freeModeStatus').html(data[2]);
$('#bypassesStatus').html(data[3]);
$('#isOnline').html(data[4]);
},
complete:function(){
setTimeout(fetchOnline,5000);
}
})
}
$(document).ready(function() { setInterval(fetchOnline,5000); });
</script>
I then try storing the returned data in-side my div id :
<div class="sidebar-tab-content" id="staff">
<div class="chat-list sidebar-content-section" id="isOnline">
Loading Info...
</div>
</div>
Return the json data like this
1st : your overwriting the variable . you need to concatenate all user like this
$client_is_online=""; //declare empty string before while loop start
//while loop start here
$client_is_online .= 'html here';
// while end here
2nd : Return the json data like this
$response = array ('totalUsers'=> $totalUsers, 'totalOnline'=> $totalOnline,'freemode'=>$freemode,'bypasses'=>$bypasses,'client_is_online'=>$client_is_online);
header('Content-Type: application/json');
echo json_encode($response);
3rd : Don't forgot to add dataType in ajax
dataType: "json",
4rd : success function should be changed like this
ajax :
success: function(value){
var data = JSON.parse(value);
$('#totalUsers').html(data['totalUsers']);
$('#totalOnline').html(data['totalOnline']);
$('#freeModeStatus').html(data['freemode']);
$('#bypassesStatus').html(data['bypasses']);
$('#isOnline').html(data['client_is_online']);
},

div expand and collapse is not working in my php code

In my php page i have these following code:-
<?php
include ('dbConnect/dbConnect.php');
$query = "Select * from RitualType";
$queryResult = mysqli_query($dbcon, $query);
?>
<!-- <div class="panel-grid-cell" id="pgc-110-6-1" >--><br/>
<div class="row-fluid" style="">
<div class="col-md-4" id="" style="position: fixed; left: 50pt; width:254px;height:50px; top: 87px; z-index: 99999999;" >
<div class="textwidget" ><?php $i = 0;
while ($row = mysqli_fetch_array($queryResult)) {
?><div id="SpanHoma">
<span class="" style="color: red;font-size: 14px;"><strong><?php echo $row['Name'] ?></strong></span>
<div class="textwidget" id="RitualsGroup" style="display:none;">
<?php
$query1 = "Select * from Rituals where RitualTypeId=" . $row['Id'];
$queryResult1 = mysqli_query($dbcon, $query1);
?>
<?php while ($row1 = mysqli_fetch_array($queryResult1)) { ?>
<div class="Homas" > <?php echo "<a style='color: #000000;' href='#" . $row1['Id'] . "'>" ?>
<i class="fa fa-hand-o-right"></i> <span class="what-we-offer" style="color: #000000;">
<?php echo $row1['Name'] ?> </span><?php echo '</a>'; ?><br />
</div><?php $i++;
} ?>
</div></div><?php } ?>
</div>
</div>
</div>
Where RitualType is Heading and Rituals are the contents.
I need to make the div expand and collapsible. Right Now the page is like this
A
B
C
D
E
When i click A then the contents of A is getting displayed like
A
a
b
c
B
C
D
E
But when i click B the div is not getting expanded. It only Works for A. I want the particular div to open when i click the Main Heading.
Javascript Code to toggleis shown below
$(function () {
$("#SpanHoma").on("click", function () {
$("#RitualsGroup").toggle();
});
$('.RitualsGroup').hide();
});
You need to try like this (convert id to class in html and change javascript code like below):-
$(function () {
$(".SpanHoma").on("click", function () {
$(this).find(".RitualsGroup").toggle(); // this will check which one is clicked currently
});
});
$(function () {
$(".SpanHoma").on("click", function () {
$(this).find(".RitualsGroup").toggle(); // this will check which one is clicked currently
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class= "SpanHoma">
<span>A</span>
<div class= "RitualsGroup" style = "display:none;">
<li>c</li>
<li>d</li>
<li>e</li>
</div>
</div>
<div class= "SpanHoma">
<span>B</span>
<div class= "RitualsGroup" style = "display:none;">
<li>f</li>
<li>g</li>
<li>h</li>
</div>
</div>
Its because of you are giving same id for multiple div. try this:
change this:
<div id="SpanHoma">
to
<div class="SpanHoma">
and
<div class="textwidget" id="RitualsGroup" style="display:none;">
to
<div class="textwidget RitualsGroup" style="display:none;">
in jquery:
$(function () {
$(".SpanHoma").on("click", function () {
$(this).find(".RitualsGroup").toggle();
});
});

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.

Categories