Fetch the ID to post in ajax - php

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);
}
});

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

YouTube API Looping Issue

I am having a looping issue with my YouTube API script. The code below shows my code. The issue that I am having is that after I get a response back from the server through jquery ajax, I alert the YouTube ID of a selected specific video. For some reason, it alerts it three times. I tried modifying the code adding the ajax call outside of the loop, but it doesn't seem to work. Any help would be greatly appreciated.
Below is the app.js
function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}
$(function() {
$("form").on("submit", function(e) {
e.preventDefault();
// prepare the request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
headers: {referer: "//localhost/"},
q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
maxResults: 3 // Set this to the number you want to display on the page.
});
// execute the request
request.execute(function(response) {
var results = response.result;
$("#results").html("");
$.each(results.items, function(index, item) {
$.get("tpl/item.html", function(data) {
$("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}]));
$('.selection').on('click', function () {
let url = "update_db.php";
let song_name2 = item.snippet.title;
let youtube_id = item.id.videoId;
$.ajax({
dataType: "JSON",
url: url,
type: "GET",
data: {song_name2: song_name2, youtube_id: youtube_id},
success: function (data) {
alert("YouTube ID: " + youtube_id );
//ALERTS 3 TIMES. HOW TO FIX IT???
/*if(data.msg === "success"){
console.log(data.result);
alert(data.result);
} else {
console.log(data.result);
alert(data.result);
}*/
}
});
});
});
}); // for each loop
resetVideoHeight();
});
});
$(window).on("resize", resetVideoHeight);
});
function resetVideoHeight() {
$(".video").css("height", $("#results").width() * 9/16);
}
function youtube_api() {
gapi.client.setApiKey("PUBLIC KEY");
gapi.client.load("youtube", "v3", function() {
// yt api is ready
});
}
Below is the item.html
<div class="item">
<h2>Title: <strong><span style="color: red">{{title}}</span></strong></h2>
<h2><span class="selection">I will like to perform this selection</span></h2>
<iframe class="video w100" width="640" height="360" src="https://www.youtube.com/embed/{{videoid}}" frameborder="0" allowfullscreen></iframe>
</div>`enter code here`
Below is the index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Search your YouTube video</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Awesome videos!" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="row con">
<div class="col-md-6 col-md-offset-4">
<div style="width: 47%; height: 50px; margin-left: 22px; display: none" id="success" class="alert-success text-center"><div style="padding-top: 15px; padding-right: 15px;"></div></div>
<div style="width: 47%; height: 50px; margin-left: 22px; display: none" id="error" class="alert-danger text-center"><div style="padding-top: 15px; padding-right: 15px;"></div></div>
<form>
<p><input type="text" id="search" placeholder="Search YouTube video" autocomplete="off" class="form-control" required /></p>
<p>
<button type="submit" id="youtube_video_search" class="form-control btn btn-primary w100">
<span class="glyphicon glyphicon-search"></span> Search
</button>
</p>
</form>
</div>
</div>
<div class="row">
<div class=" col-md-6 col-md-offset-3">
<div id="results"></div>
</div>
</div>
<!-- scripts -->
<script src="./jquery-3.3.1.js"></script>
<script src="js/app.js"></script>
<script src="https://apis.google.com/js/client.js?onload=youtube_api"></script>
</body>
</html>
For some reason, it alerts it three times.
You are binding click on .selection on every loop and when the loop is done, you have 3 elements with .selection, that means you bind the click on all 3 of them.
You should bind it on id or some custom tag like data-selection-id=UNIQUE_ID
item.html
Change <span class="selection"> to <span class="selection" data-selection-id="{{videoid}}">
app.js
Change $('.selection').on('click', function () { to $('.selection[data-selection-id="+ item.id.videoId +"]').on('click', function () {
Not exactly sure your case, But for a workaround you can handle this with any boolean flag.
$('.selection').on('click', function () {
var isExecuted = false;
let url = "update_db.php";
let song_name2 = item.snippet.title;
let youtube_id = item.id.videoId;
$.ajax({
dataType: "JSON",
url: url,
type: "GET",
data: {song_name2: song_name2, youtube_id: youtube_id},
success: function (data) {
if(!isExecuted)
{
isExecuted = true;
alert("YouTube ID: " + youtube_id );
//ALERTS 3 TIMES. HOW TO FIX IT???
}
}
});
});

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.

change username settings dynamically php

I want to change username name dynamically when user change the settings. Without refresh it should change the name. Any help would be appreciated.
settings code file:
if($User_Name != $row['USERNAME'])
{
$insert = "UPDATE USER_LOGIN SET PASSWORD = '".$New_Password."', USERNAME = '".$User_Name."' WHERE USERNAME = '".$_COOKIE['username']."'";
$result = oci_parse($con, $insert);
// Executes a statement.
$check = oci_execute($result);
if($check)
{
echo "Saved";
// Commit the changes to the table.
oci_commit($con);
}
else
{
// Rollback changes to table.
oci_rollback($con);
}
}
Admin Panel:
<div class="user">
<img src="../../img/Users/Users/Admin.jpg" align="left"/>
<a class="name">
<?php
session_start();
if(isset($_COOKIE['username']))
{
echo $_COOKIE['username'];
}
else
{
echo $_SESSION['username'];
}
?>
<span class="sm">Administrator</span>
</a>
</div>
My ajax function is like this:
<!-- Ajax function is used to post the data to databse and show result in the table without refresh -->
<script>
var frm = $('.wrefresh');
frm.submit(function (ev)
{
ev.preventDefault();
var postdata = $(this).serialize();
var path = $(this).attr("action");
var mehtodtype = $(this).attr("method").toUpperCase();
// Clear fields data. (password).
$('form :input[type=password]').attr('value','');
// Remove selected pictures field.
$('#Picture').attr('src', '../../img/User No-Frame.png');
$.ajax
({
type: mehtodtype,
url: path,
data: postdata,
success: function(data)
{
if(data === "Please Fill Entries.")
{
$('#fullname').css("border-color", "rgb(219, 46, 46)");
$('#old').css("border-color", "rgb(219, 46, 46)");
$('#new').css("border-color", "rgb(219, 46, 46)");
$('#confirm').css("border-color", "rgb(219, 46, 46)");
$('#showmediv').show();
}
}
});
});
</script>
Html:
<form class="wrefresh" action="../Code Files/User.php" method="post">
<div id="photo_settings2" style="margin-left:74px;">
<img id="Picture" src="../../img/User No-Frame.png"/>
</div>
<br><br><br><br>
<div id='Upload_Panel' style="margin-left: 32px;">
<input name='file' type='file' id='file_browse' onchange="readURL(this,'Picture')" style="cursor: pointer;"/>
</div>
<div id="delete" style="margin-top: -40px; margin-left: 198px; cursor: pointer">
<img src="../../img/Delete_Panel.png">
</div>
<div style="margin-left:144px; margin-top:-15px"></div>
<br><br>
<div class="row-form" style="margin-top:10px">
<div class="span4">Username:</div>
<div class="span8"><input id="fullname" style="border: 1px solid #918C8C" type="text" class="cNav" name="uname" value=""/></div>
</div>
<div class="row-form">
<div class="span4">Old Password:</div>
<div class="span8"><input id="old" style="border: 1px solid #918C8C" type="password" class="cNav" name="opass" value=""/></div>
</div>
<div class="row-form">
<div class="span4">New Password:</div>
<div class="span8"><input id="new" style="border: 1px solid #918C8C" type="password" class="cNav" name="npass" value=""/></div>
</div>
<div class="row-form">
<div class="span4">Confirm:</div>
<div class="span8"><input id="confirm" style="border: 1px solid #918C8C" type="password" class="cNav" name="cpass" value=""/></div>
</div>
<br>
<div class="row-fluid" style="margin-left:112px; margin-top:-05px">
<div class="span9">
<button type="submit" class="btn btn-success" style="height:28px">Save</button>
<span id="showmediv" class="label label-important" style="display: none; margin-left: 14px; margin-top:-35px">Please Enter Fields</span>
</div>
</div>
</form>
You need to change the username which you are showing inside
<a class="name">
in ajax success callback like this:
I am not sure it will work or not.
$.ajax
({
type: mehtodtype,
url: path,
data: postdata,
success: function(data)
{
if(data === "Please Fill Entries.")
{
$('#fullname').css("border-color", "rgb(219, 46, 46)");
$('#old').css("border-color", "rgb(219, 46, 46)");
$('#new').css("border-color", "rgb(219, 46, 46)");
$('#confirm').css("border-color", "rgb(219, 46, 46)");
$('#showmediv').show();
//get new name
var userName = $("#fullname").val();
// show new username
$(".name").html(userName);
}
}
});
Onemore thing:
when you are sending ajax call you need to set new username in SESSION .
I hope you are trying to post the form without refreshing as I didnt understood what you were trying to achieve
What you need to do is use ajax to submit your form . Try this plugin and add the following code
http://jquery.malsup.com/form/#ajaxSubmit
download the plugin
and in the form add this
<form onsubmit="javascript:login();return false;">
function action(){
$('#form').ajaxSubmit({
target:'#output_login',
url:'./php/page.php'
});
return false;
}

Not able to load mysql query data in JEasyUI Grid

I am new to PHP and JEasy UI.
I am actually running the demo application of JEasy UI Grid.
Whereas I am not getting the data from Php file to Grid.
Any Idea or suggestion please...!!
Below is My Code:
index.php
<html>
<head>
<meta charset="UTF-8">
<title>Basic CRUD Application - jQuery EasyUI CRUD Demo</title>
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="http://www.jeasyui.com/easyui/demo/demo.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript" src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
</head>
<body>
<div class="demo-info" style="margin-bottom:10px">
<div class="demo-tip icon-tip"> </div>
</div>
<table id="dg" title="My Users" class="easyui-datagrid" style="width:700px;height:250px"
url="http://www.jeasyui.com/tutorial/app/crud/get_users.php"
toolbar="#toolbar" pagination="true"
rownumbers="true" fitColumns="true" singleSelect="true">
<thead>
<tr>
<th field="firstname" width="50">First Name</th>
<th field="lastname" width="50">Last Name</th>
<th field="phone" width="50">Phone</th>
<th field="email" width="50">Email</th>
</tr>
</thead>
</table>
<div id="toolbar">
New User
Edit User
Remove User
</div>
<div id="dlg" class="easyui-dialog" style="width:400px;height:280px;padding:10px 20px"
closed="true" buttons="#dlg-buttons">
<div class="ftitle">User Information</div>
<form id="fm" method="post" novalidate>
<div class="fitem">
<label>First Name:</label>
<input name="firstname" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>Last Name:</label>
<input name="lastname" class="easyui-validatebox" required="true">
</div>
<div class="fitem">
<label>Phone:</label>
<input name="phone">
</div>
<div class="fitem">
<label>Email:</label>
<input name="email" class="easyui-validatebox" validType="email">
</div>
</form>
</div>
<div id="dlg-buttons">
Save
Cancel
</div>
<script type="text/javascript">
var url;
function newUser(){
$('#dlg').dialog('open').dialog('setTitle','New User');
$('#fm').form('clear');
url = 'save_user.php';
}
function editUser(){
var row = $('#dg').datagrid('getSelected');
if (row){
$('#dlg').dialog('open').dialog('setTitle','Edit User');
$('#fm').form('load',row);
url = 'update_user.php?id='+row.id;
}
}
function saveUser(){
$('#fm').form('submit',{
url: url,
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
var result = eval('('+result+')');
if (result.errorMsg){
$.messager.show({
title: 'Error',
msg: result.errorMsg
});
} else {
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
}
}
});
}
function destroyUser(){
var row = $('#dg').datagrid('getSelected');
if (row){
$.messager.confirm('Confirm','Are you sure you want to destroy this user?',function(r){
if (r){
$.post('destroy_user.php',{id:row.id},function(result){
if (result.success){
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({ // show error message
title: 'Error',
msg: result.errorMsg
});
}
},'json');
}
});
}
}
</script>
<style type="text/css">
#fm{
margin:0;
padding:10px 30px;
}
.ftitle{
font-size:14px;
font-weight:bold;
padding:5px 0;
margin-bottom:10px;
border-bottom:1px solid #ccc;
}
.fitem{
margin-bottom:5px;
}
.fitem label{
display:inline-block;
width:80px;
}
</style>
</body>
</html>
PHP Code URL
http://www.jeasyui.com/tutorial/app/crud/get_users.php
to get the data from datagrid you need to code like this
public function get_user(){
/*Default request pager params from jeasyUI*/
$offset = isset($_POST['page']) ? intval($_POST['page']) : 1;
$limit = isset($_POST['rows']) ? intval($_POST['rows']) : 10;
$search = isset($_POST['search']) ? $_POST['itemid'] : '';
$offset = ($offset-1)*$limit;
//change this line to yours
$data = $this->user_model->get_user($offset,$limit,$search);
$i = 0;
$rows = array();
foreach ($data ['data'] as $r) {
$rows[$i]['first_name'] = $r->first_name;
$rows[$i]['last_name'] = $r->last_name;
$rows[$i]['phone'] = $r->phone;
$rows[$i]['email'] = $r->email;
$i++;
}
//keys total & rows is required on jEasyUI
$result = array('total'=>$data['count'],'rows'=>$rows);
echo json_encode($result);
}
more complete example here

Categories