How to access a model method with javascript - php

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.

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

Fetch the ID to post in ajax

I need some help with my code as I have got a problem with defined the variable to post them in Ajax. I am working on PHP as I am fetching the data from mysql database to input the information in PHP, so I would like to post the ID in ajax.
I have defined the variable $autoid outside of the while loop, but I am unable to defined them when I am using jquery because it will show empty data when I try to post them in Ajax.
When I try this:
var ID = $(this).data('deleteid');
$.ajax({
type: 'POST',
url: "sendtest.php",
data: {ID : "deleteid"
},
success: function(resultData) {
alert(resultData)
}
Here is the full code:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
else
{
$link = mysqli_connect('localhost', 'mydbusername', 'mydbpassword', 'mydbpassword');
$param_username = $_SESSION['username'];
$autocampaign = $_SESSION["auto_campaign"];
$autor_sql = "SELECT id, subject, day_cycle, enabled, delaysend FROM auto WHERE campaign ='$autocampaign' AND username ='$param_username'";
$autoid = '';
$results = mysqli_query($link, $auto_sql);
if (mysqli_num_rows($results) > 0)
{
while ($row = mysqli_fetch_array($results))
{
$autoid = $row["id"];
$autosubject = $row["subject"];
$autodaycycle = $row["day_cycle"];
$autoenabled = $row["enabled"];
$autodelay = $row["delaysend"];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
.calendar-content {
float: left;
width: 100%;
min-height: 112px;
border: 1px solid #ccc;
position: relative;
margin-top: -1px;
}
</style>
<div class="calendar-content">
<div style="margin-left: 40px;margin-top: 20px; height: 40px;">
<span id="autosubject" style="font-size: 25px;color: #0c7ac0;float: left;">Subject: <?php echo $autosubject ?> </span><br>
<div style="margin-left: 35px; margin-top: 15px; height: 40px;">
<form action="" method="post">
<span style="font-size: 15px; color: #ccd5d9; float: left; margin-top: -1px"><a name="autoid" id="autoid" href="#contactModal" role="button" data-toggle="modal">Send a test</a> | <a name="deleteid" id="deleteid" href="/auto/delete_auto.php?id=<?php echo $autoid; ?>"> Delete </a> | Copy to Draft | Settings</span>
</form>
</div>
</div><br>
<!-- email Modal -->
<div id="contactModal" class="modal fade" style="margin-top: 12%;" tabindex="-1" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" style="height: 250px;">
<div class="modal-header" style="margin-bottom: 10px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="modal-title">Send A Test Email</h3>
</div>
<div class="modal-body" style="height: 65%;">
<form action="" method="post">
<label class="label-control" value="">Send test message to email address:</label>
<select name="emails" id="emails" value="" style="width: 400px; margin-top: 10px; margin-bottom: 18px; margin-left: 60px;">
<option selected="selected" value='title'>Title</option>";
</select><br>
<button name="send_email" id="send_email" type="submit" class="btn btn-primary" style="margin-left: 36%;" data-auto-id="<?php echo $autoid; ?>">Send Test</button>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
$('#send_email').click(function(e) {
$(this)
.html("<span><i class='fa fa-spinner fa-spin'></i> Sending...</span>")
.prop("disabled", true);
var ID = $(this).data('deleteid');
$.ajax({
type: 'POST',
url: "sendtest.php",
data: {ID : "deleteid"
},
success: function(resultData) {
alert(resultData)
$('#contactModal').modal('hide');
$("#send_email")
.html("Send Test")
.prop("disabled", false);
}
});
});
});
</script>
<?php
}
?>
Here is the sendtest.php:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
else if(isset($_POST))
{
$id = $_POST[$autoid];
echo "hello your id is...";
echo $id;
}
?>
What I want to achieve is when I click on a send a test hyperlink, a modal will display and when I click on a button after I select on a dropdown listbox, I want to fetch the ID from the Delete hyperlink so I can post them in ajax. The reasons I want to post the ID in ajax is because I want to stay on the same page while I want to fetch the information from the mysql database.
Can you please show me an example how I can fetch the ID from the Delete hyperlink to post them in ajax?
Thank you for understanding what I am trying to do.
There are several issues in your code:
1st: data: {ID : "deleteid"}, should be data: {ID : ID }, (you want to send the var, not the string "deleteid")
2nd: var ID = $(this).data('deleteid'); should be var ID = $(this).data('auto-id');, because the data-attribute is data-auto-id="...
3rd: $id = $_POST[$autoid]; will throw an error (undefined variable) & a notice (undefined index). Should be $id = $_POST['ID'], because you call the param "ID" here: data: {ID : varname},
4th: you are missing a ; here: alert(resultData)
Here's the corrected ajax-part:
var ID = $(this).data('auto-id');
$.ajax({
type: 'POST',
url: "sendtest.php",
data: {ID : ID },
success: function(resultData) {
alert(resultData);
$('#contactModal').modal('hide');
$("#send_email")
.html("Send Test")
.prop("disabled", false);
}
});

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']);
},

How to validate an input to see if it matches a record in the database

I am trying to create an input that queries the database and returns whether or not a result exists in the database. I have it partially working, but my box is glowing green whenever I only type in one letter. It would be better if it stayed red until it actually found a exact match and then turned green. Edit: I just realized there is also something wrong with my query. It is correctly querying the database now. The original issue is my main problem.
$(document).ready(function(){
$("#load").keyup(function (e){
e.preventDefault();
;
searchRequest = $.ajax({
url: 'check_load_no.php',
data: $('#load').serialize(),
type: 'POST',
success: function (data) {
$(".verify").css('box-shadow', '0px 0px 9px 2px #84f850');
$(".error").css('display', 'none');
$(".success").css('display', 'block');
},
error: function (data) {
$(".verify").css('box-shadow', '0px 0px 9px 2px #ad0037');
$(".success").css('display', 'none');
$(".error").css('display', 'block');
}
});
});
});
Below is my php
<?php include('../model/conn.php'); ?>
<?php include('../model/conn2.php') ?>
<?php
$sql = "SELECT cmt_2 FROM oeordhdr_sql WHERE cmt_2 = '{$_POST['load']}'";
$query = (odbc_exec($conn,$sql));
$row = (odbc_fetch_row($query));
if($row['cmt_2']){
echo 'yeah';
}
HTML
<h1>Please add the info based on your load number</h1>
<form action="" method="post">
<div class="card" >
<input class="verify" id="load" type="text" name="load" placeholder="Load Number" required/>
<span class="error" style="display: none;"><i class="fa fa-exclamation-triangle fa-lg" aria-hidden="true"> </i>I'm not finding anything</span>
<span class="success" style="display: none;"> <i class="fa fa-check-cube fa-lg" aria-hidden="true"> </i> Congratulations, that record exists!</span><br>
<button class="update_button" type="submit" name="add" value="update">Update</button></div></form>
Your error handler will not be called even if "yeah" is not echoed out by PHP script, as the server response would still be HTTP 200. For this reason, your success handler will always trigger (unless of course there is an actual problem with your server/application).
If you want to trigger the error handler, you would have to have the server send a 400 or 500 series HTTP response code (likely 404 in this case) for the case when no match is found.
Alternately, you could just put all your logic in the success handler and not change your server-side code at all. You would just have to test for the value of "yeah" being present or not.
You should also consider adding/removing CSS classes on your DOM elements rather than specifically specifying the CSS in your function. This would allow you to later change the CSS if needed, without having to alter this function.
success: function (data) {
if(data==="yeah")
{
$(".verify").css('box-shadow', '0px 0px 9px 2px #84f850');
$(".error").css('display', 'none');
$(".success").css('display', 'block');
}
else
{
$(".verify").css('box-shadow', '0px 0px 9px 2px #ad0037');
$(".success").css('display', 'none');
$(".error").css('display', 'block');
}
}
check if response is what you need and only then add .success class
Decided to output the error/success message using php instead of changing css
$("#load").keyup(function (e){
e.preventDefault();
searchRequest = $.ajax({
url: 'check_load_no.php',
data: $('#load').serialize(),
type: 'POST',
success: function (data) {
console.log(data);
if(data==="yeah")
{
$(".validate").html(data);
}
else
{
$(".validate").html(data);
}
}
});
});
My php
$sql = "SELECT cmt_2 FROM oeordhdr_sql WHERE cmt_2 LIKE '{$_POST['load']}'";
$query = odbc_exec($conn,$sql);
$row = (odbc_fetch_row($query));
if($row){
echo '<span class="success" style="display: block;"> <i class="fa fa-check-cube fa-lg" aria-hidden="true"> </i> Congratulations, that record exists!</span>';
}else{
echo'<span class="error" style="display: block;"><i class="fa fa-exclamation-triangle fa-lg" aria-hidden="true"> </i>I\'m not finding anything</span>';
}
My HTML
<h1>Please add the info based on your load number</h1>
<form action="" method="post">
<div class="card" >
<input class="verify" id="load" type="text" name="load" placeholder="Load Number" required/>
<div class="validate"></div><br>
<button class="update_button" type="submit" name="add" value="update">Update</button></div></form>

php database, jquery dynamic content load

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.

Categories