I am using two div(s). In the first div, all the WordPress users are shown on a page, with "ADD" Button Option. By adding Users, they get added to the second div using Ajax. But I want to cache the result shown in the second div. The code for users template are as follows-
<?php
/*
Template Name: Users
*/
?>
<style>
.container{
width: 800px;
}
.left{
float:left;
width: 300px;
background: ##66CDAA;
border-right: thick-solid #fff;
}
.right{
overflow: hidden;
width: 300px;
background: powderblue;
}
</style>
<?php
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class="container">
<div class="left" id="xyz">
<table>
<tr>
<th>Name</th>
<th>Gravatar Image</th>
<th>Add to Div</th>
</tr>
<?php
$sql ="SELECT * FROM wp_users";
$results = $wpdb->get_results($sql) or die(mysql_error());
foreach( $results as $result ){ ?>
<tr>
<td id="<?php echo $result->ID; ?>">
<?php echo $result->display_name; ?>
</td>
<td>
<php echo get_avatar( $result->user_email, 42); ?>
</td>
<td>
<input type="button" class="submit" data-id="<?php echo $result->ID; ?>" data-name="<?php echo $result->display_name; ?>" data_image="<?php echo get_avatar_url($result->user_email, 42); ?>" value="ADD"><p style="display:none;">Added</p>
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="right">
<p>Added Users</p>
<table>
<tr>
<th>Name<th>
<th>Image</th>
</tr>
</table>
</div>
</div>
</main>
</div>
<?php get_footer(); ?>
Now, in ajax.js I have the following code:
(function($) {
$(document).ready(function() {
$(".submit").on("click", function(e){
e.preventDefault();
$(this).css("display", "none");
$(this).closest("td").find("p").css("display", "block");
var id = $(this).data('id');
var name = $(this).data('name);
var image = $(this).data('image');
$.ajax({
url: ajax_url,
method: 'post',
data: { action: 'work', id:id, name: name, image:image},
success: function(response){
var test = jQuery.parseJSON(response);
name1 = test.myname;
url1: test.url;
id: test.id;
$('.table').append('<tr id=" ' + id1+ ' "><td>' + name1 + '</td><br><td><img src=" ' + url1 + ' "></td><td><input type="button" value="Cancel" class="cancel"></td></tr>');
$('.cancel').on("click", function(e){
e.preventDefault();
var id2 =$(this).closest.("tr").attr('id');
$('td[id=' + id2 + ']').closest('tr').find('p').css('display', 'none');
$('td[id=' + id2 + ']').closest('tr').find('input').css('display', 'block');
$(this).closest("tr").hide();
})
}
})
})
})
})(jQuery);
Now, In ajax.php, I have the function which is as follow:
function work() {
$id = $_POST['id'];
$name = $_POST['name'];
$image_url = $_POST['image'];
$myObj->myname = $name;
$myObj->url = $image_url;
$myObj->id = $id;
$myJSON = json_encode($myObj);
echo $myJSON;
wp_die();
}
I want to add users to the second div using Ajax and also want to cache the result for some time. Also, suggest if there is a better way of hiding Add button or can I apply a condition to check whether a particular user has been added should not be added twice. But my primary question is that how can I cache ajax result.
This may help you, go through the below code snippet
// ask the browser to cache this response
$expires = 60 * 15; // 15 minutes
header('Pragma: public');
header('Cache-Control: maxage=' . $expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
Related
I want to create a column that has a text box inside each table row. The user can write any text inside the text box and click the 'Save' button to save it in the database. Additionally, the text box can be edited unlimited times. My code is the following:
index.php
<?php
...
while($row = $result->fetch_assoc()){
echo "<form action= 'search.php' method='post'>";
echo "<form action='' method='get'>";
echo "<tr>
<td><input type='checkbox' name='checkbox_id[]' value='" . $row['test_id'] . "'></td>
<td> ".$row['test_id']." </td>
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
<td> ".$row['path']." </td>
<td> ".$row['video1_path']." </td>
<td> ".$row['video2_path']." </td>
<td> ".$row['video3_path']." </td>
<td> ".$row['video4_path']." </td>";
if(empty($row["directory"])){
echo "<td></td>";
}else {
echo "<td><div><button class='href' id='" . $row['test_id'] . "' >View Report</button><div></td>";
}
echo " <td style='display: none;'> ".$row['directory']." </td>
</tr>";
}
?>
</table> <br>
<input id= 'select_btn' type='submit' name='submit' value='Submit' class='w3-button w3-blue'/>
</form>
</form>
</div>
<!-- Opens the pdf file from the pdf_report column that is hidden -->
<script type="text/javascript">
$(document).on('click', '.href', function(){
var result = $(this).attr('id');
if(result) {
var dir = $(this).closest('tr').find("td:nth-child(9)").text();
window.open(dir);
return false;
}
});
</script>
<!-- Updates text input to database -->
<script type="text/javascript">
$(document).on('click', '.name', function(){
var fcookie1= 'mycookie1';
var fcookie2= 'mycookie2';
var name = $(this).attr('id');
if(name) {
var text1 = $(this).closest('tr').find("td:nth-child(2)").text();
var text2 = $(this).closest('tr').find("td:nth-child(3)").text();
document.cookie='fcookie1='+text1;
document.cookie='fcookie='+text2;
$.ajax({
url: "name_edit.php",
type:"GET",
success: function() {
// alert("Edited Database");
}
});
}
});
</script>
name_edit.php
<?php include 'dbh.php' ?>
<?php include 'search.php' ?>
<?php
if (isset($_COOKIE["fcookie1"]))
echo $_COOKIE["fcookie1"];
else
echo "Cookie Not Set";
if (isset($_COOKIE["fcookie2"]))
echo $_COOKIE["fcookie2"];
else
echo "Cookie Not Set";
$var1 = $_COOKIE["fcookie1"];
$var2 = $_COOKIE["fcookie2"];
$conn = mysqli_connect($servername, $username, $password, $database);
$sql = "UPDATE test_data SET name='$var2' WHERE id='$var1'";
$query_run= mysqli_query($conn,$sql);
if($query_run){
echo '<script type="text/javascript"> alert(Data Updated)</script>';
} else {
echo '<script type="text/javascript"> alert(Data Not Updated)</script>';
}
?>
My idea was for the user to write any text. Then i will 'grab' the text and its expected id and save it to a cookie, when the save button is clicked. The cookie will then be echoed in name_edit.php and insert it in the sql code which will then update my database.
Im not sure what to include in 'value' inside the form tag. If there is data inside the database then display it inside the text box which can also be edited, else display blank for a text to be inserted.
I am new to coding and I'm a bit confused if my idea is correct or should i approach it another way.
I did some research and found out i did not have to use form but instead use 'contenteditable'. To edit the specific column i changed
<td><input type='text' name='name' value='<?NOT SURE WHAT TO INCLUDE HERE ?>'/></td>
<td><input type='submit' value='Save' id='" . $row['test_id'] . "' class='name' /></td>
to this:
<td class='name' data-id1='" . $row['test_id'] . "' contenteditable='true'>".$row['name']."</td>
and for my jquery i added the following:
<style>
.editMode{
border: 1px solid black;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
// Add Class
$('.name').click(function(){
$(this).addClass('editMode');
});
// Save data
$(".name").focusout(function(){
$(this).removeClass("editMode");
var id = $(this).closest('tr').find("td:nth-child(2)").text();;
var value = $(this).text();
$.ajax({
url: 'name_edit.php',
type: 'post',
data: { value:value, id:id },
success:function(response){
alert('Edits Saved');
return false;
}
});
});
});
</script>
and in the php side, i simply did the following:
<?php include 'dbh.php' ?>
<?php
$conn = mysqli_connect($servername, $username, $password, $database);
$field = $_POST['field'];
$value = $_POST['value'];
$id= $_POST['id'];
$sql = "UPDATE test_data SET name='".$value."' WHERE test_id='".$id."'";
mysqli_query($conn,$sql);
echo 1;
?>
I'm trying to create a add/delete/edit post system using php for a website. I have the add working, so when the user enters in information it gets added to the database and then asynchronously gets added onto the page using ajax. I want a similar function that deletes asynchronously as well. Right now, when I click delete, only the oldest post gets deleted AFTER refreshing the page. It does not delete the post as soon as I click the delete button which is my goal. This is what I have so far. The home.php is where my form is that collects the information and also prints out the information from the database. handledelete.php is where the deleting is handled.
home.php
<script>
$(function() {
$('#deleteButton').click(function(event) {
event.preventDefault();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
beforeSend: function(){
}
, complete: function(){
}
, success: function(html){
$("#show_entries").append(html);
}
});
});
});
</script>
<div id="entry">
<form method="GET" action="handle_insert.php">
<table align="center" width="30%" border="0">
<tr>
<td><input type="text" name="activity" id="activity" placeholder="Activity" required /></td>
</tr>
<tr>
<td><input type="text" name="duration" id="duration" placeholder="Duration (hours)" required /></td>
</tr>
<tr>
<td><input type="text" name="date" id="date_" placeholder="Date (YYYY-MM-DD)" required /></td>
</tr>
<tr>
<td><button type="submit" name="submitButton" id="submitButton">Add input</button></td>
</tr>
</table>
</form>
</div>
<!-- shows the previous entries and adds on new entries-->
<div id="show_entries">
<?php
$userID = $_SESSION["user"];
$link = mysqli_connect('localhost', 'oviya', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '<button type="submit" name="deleteButton" data-id='.$entry_id.' id= "deleteButton">Delete</button>';
//echo '<button type="submit" name="editButton" data-id='.$entry_id.' id="editButton">Edit</button>';
echo '</div>';
}
?>
</div>
handle_delete.php
session_start();
$user = 'oviya';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_GET["entry_id"])){
$entry_id = mysqli_real_escape_string($link, $_GET["entry_id"]);
$sql = "DELETE FROM dataTable WHERE entry_id = '$entry_id'";
$result = mysqli_query($link, $sql);
die();
mysqli_close($link);
}
This line is the problem. It would add elements if your AJAX call were returning HTML, which it isn't:
$("#show_entries").append(html);
Instead, you want to remove the deleted element, which you can reference directly and remove from the DOM:
$('#deleteButton').click(function(event) {
event.preventDefault();
// Get a reference to the whole row element.
var row = $(this).parent();
$.ajax({
type: "GET",
url: "handle_delete.php",
data : { entry_id : $(this).attr('data-id') },
success: function(html){
// Remove the row
row.remove();
}
});
});
I have this JavaScript code refreshing my watcher.php file every 5 seconds and that works great. The first page load is fine but after the 5 seconds and so on the while loop gets killed. Any reason?
index.php file
<script type="text/javascript">
var auto_refresh = setInterval(function(){
$('.view').load('watcher.php');
}, 5000); // refresh div time
</script>
<body>
<div class="view">
<?php include 'watcher.php'; ?>
</div>
</body>
...
watcher.php file
include 'config.php';
$sql = "SELECT id, name, available, will_return, status FROM check_in_out";
$result = $conn->query($sql);
echo '<div style="margin-top:35px;"><center>';
echo '<table class="pure-table">
<thead>
<tr>
<th>Name</th>
<th>Available</th>
<th>Status/Comments</th>
<th>I\'ll Return At:</th>
<th>Returned</th>
</thead>
</tr>
';
if ($result->num_rows > 0) {
$i = 1;
// output data of each row
while ($row = $result->fetch_assoc()) {
echo '<tr>';
echo '<td><img style="vertical-align:middle" src="imgs/card.jpg"> <a class="various" href="#'.$i.'"/>'.$row["name"];'</a></td>';
echo "<td>";
if ($row['available'] == 1) {
echo "<img src='imgs/available.gif'/>";
echo "Online";
} else {
echo "<img src='imgs/not-available.gif'/>";
echo "<span style='vertical-align:middle'>Away</span>";
};
echo "</td>";
echo '<td>'.$row["status"];'</td>';
echo '<td>'.$row["will_return"];'</td>';
echo '<td></td>';
echo '</tr>';
echo '<div align="center" id="'.$i++.'" style="display:none;width:520px;">
<h2>'.$row["name"].'</h2>
<!-- <h4>Current Status: '.$row["status"].'</h4> -->
<form method="post" action="statusChange.php" />
<input type="hidden" value="'.$row["id"].'" name="id"/>
<textarea rows="4" cols="50" placeholder="Enter Comment/Status Here..." name="comment"></textarea>
<br/><br/>
When will you return? - <input type="time" name="e_time">
<br/><br/>
<input class="pure-button pure-button-primary" type="submit" value="Leave/Return">
</form>
</div>';
}
} else {
echo "0 employees";
}
echo '</tr></table>';
echo '</div></center>';
$conn->close();
UPDATE:
What is by this is that look at image below. You will notice that after the first load (5 seconds) the clickable (href) gets killed...
<script type="text/javascript">
var updateWatcher = function() {
$.ajax({
url: 'watcher.php',
success: function(response) {
$('.view').html(response);
window.setTimeout(function(){
updateWatcher();
}, 3500);
}
});
}
updateWatcher();
</script>
Granted, this could be solved more elegantly with something like promises, but as far as a simple fix you could try something like this where the timer is only setup once the response has been successfully received. This should be more reliable.
Here is a simple fiddle: http://jsfiddle.net/agentfitz/26mahomm/3/ (look in the console).
I have the following script:
index.php
<?php include("db.php"); ?>
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
</head>
<body>
<div align="center">
<table cellpadding="0" cellspacing="0" width="500px">
<?php $sql = "SELECT * FROM items ORDER BY ID DESC";
$items= mysql_query($sql);
while ($item= mysql_fetch_array($items)){
$id = $item[ID]; ?>
<tr style="border: solid 4px red;">
<td>
<div class="<?= $id ?>">
<button class="my-btn" type="button" value="<?= $id ?>">BUTTON <?= $id ?></button>
</div>
</td>
</tr>
<?php } ?>
</table>
<div id="flash" align="left" ></div>
<ol id="update" class="timeline"></ol>
<div id="old_updates"></div>
</div>
<script src="script.js"></script>
</body>
</html>
script.js
$(function() {
$(".my-btn").click(function() {
var dataString = $(this).val();
$("#flash").show().fadeIn(200).html('');
$.ajax({
type : "POST",
url : "update_data.php",
data : {'not' : dataString},
cache : false,
success : function(html){
$("#update").prepend(html).find("li:first").slideDown("slow");
$('#content').val('');
$("#flash").hide();
}
});
});
$('.delete_update').live("click",function() {
var ID = $(this).attr("id");
var dataString = 'msg_id='+ ID;
if(confirm("Sure you want to delete this update? There is NO undo!")){
$.ajax({
type : "POST",
url : "delete_data.php",
data : dataString,
cache : false,
success : function(html){
$(".bar"+ID).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
update_data.php
<?php
include('db.php');
if(isSet($_POST['not'])) {
$not = $_POST['not'];
mysql_query("insert into items (name) values ('$not')");
$sql_in = mysql_query("SELECT wave, ID FROM actions order by ID desc");
$r = mysql_fetch_array($sql_in);
$msg = $r['name'];
$id = $r['ID'];
}
?>
<li class="bar<?php echo $msg_id; ?>">
<div align="left">
<span style=" padding:10px"><?php echo $msg; ?> </span>
<span class="delete_button">
X
</span>
</div>
</li>
delete_data.php
<?php
include("db.php");
if($_POST['msg_id']) {
$id = $_POST['msg_id'];
$id = mysql_escape_String($id);
$sql = "delete from items where ID='$id'";
mysql_query( $sql);
}
?>
I posted the whle code to be more specific and easy to understand.
The problem appear only with the delete function.
When i hit the link to delete an item, this item don't disappear instantly but is removed from sql database.
To see the item deleted i need to refresh the page and i don't want that.
I think the problem is with the second function of script.js but i can't figured it out what exactly is.
Well, I think it might be easier to explain my question by the image below:
As can be seen in the picture, if user select "By title", a textbox will be appeared where user can write a movie title (I also used jQuery auto-completion for this textbox). Then, if user click on the button "Movies by this title", a new window will be shown where there is a list of movies containing the term in the textbox.
My question:
I would like to integrate a small image of each of these movies beside them (and maybe some other information like movie year, genre..) like what amazon does (Please see here). I used renderitem for the auto-complete part and it works fine, but actually I have no idea how to do the same in the new window.. I would be very grateful if someone can help me.
This is my code:
<div id="m_scents" class="field">
<label style="margin-bottom:10px;" for="m_scnts"></label>
<input class="autofill4" type="textbox" name= "q27[]" id="q" placeholder="Enter movie titles here" />
<input type="button" value="Movies by this title" id="btnMove" style="display:none;"/>
</div>
<script type="text/javascript">
var selected;
$(document).ready(function () {
$("input[id='selectType']").change(function(){
if ($(this).val() == "byTitle") {
$("#m_scents2").hide();
$("#btnMove").show();
$("#m_scents").show();
$("#q").focus();
$("#q").autocomplete({
minLength: 0,
delay:5,
source: "query.php",
focus: function( event, ui ){
event.preventDefault();
return false;
},
select: function( event, ui ) {
window.selected = ui.item.movieName;
return false;
}
}).data("uiAutocomplete")._renderItem = function( ul, item ) {
return $("<li></li>")
.data( "item.autocomplete", item )
.append( "<a>" + (item.posterLink?"<img class='imdbImage' src='imdbImage.php?url=" + item.posterLink + "' />":"") + "<span class='imdbTitle'>" + item.movieName + "</span>" + "<div class='clear'></div></a>" )
.appendTo( ul );
};
}
});
$('#btnMove').on('click', function (e) {
popupCenter("movieBytitle.php","_blank","400","400");
});
</script>
This is movieBytitle.php:
<body>
<div id= "field"
</div>
<script type="text/javascript">
var selected = parent.window.opener.selected;
$.ajax({
url: 'childfilm.php',
datatype: "json",
data:{p:selected},
success: function(response) {
$("#field").html(response);
}
});
</script>
</body>
and this is childfilm.php:
<?php
if(isset($_GET['p']) && !empty($_GET['p'])){
try{
include('imdbConnection.php');
$sql = $conn->prepare("SELECT DISTINCT movieName FROM films WHERE movieName LIKE :p");
$sql->execute(array(':p' => '%'.$_GET['p'].'%'));
while($row = $sql->fetch(PDO::FETCH_ASSOC)){
$option = '' . $row['movieName'] . '<br />';
$html .= $option;
}
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
echo $html;
exit;
}
?>
UPDATE:
This is the new childfilm.php (Thanks to #ghost help):
if(isset($_GET['p']) && !empty($_GET['p'])){
include('imdbConnection.php');
$sql = $conn->prepare("SELECT DISTINCT movieName FROM films WHERE movieName LIKE :p");
$sql->execute(array(':p' => '%'.$_GET['p'].'%'));
}
?>
<table>
<tr>
<th></th>
<th>Title</th>
<th>Year</th>
<th>Genre</th>
</tr>
<?php while($row = $sql->fetch(PDO::FETCH_ASSOC)): ?>
<tr>
<td><img class='imdbImage' src='imdbImage.php?url="<?php echo $row['posterLink'];?>'</td>
<td><?php echo $row['movieName']; ?></td>
</tr>
<?php endwhile; ?>
</table>
and this is imdbImage.php:
<?php
header("Content-type: image/jpeg");
$url = rawurldecode($_REQUEST['url']);
echo file_get_contents($url);
?>
New problem:
This is the result (Still, the image is not shown properly):
If you already got those information in the table, then just include it in the fetching and present it in tabular form:
<?php
if(isset($_GET['p']) && !empty($_GET['p'])){
include('imdbConnection.php');
$sql = $conn->prepare("SELECT DISTINCT movieName FROM films WHERE movieName LIKE :p");
$sql->execute(array(':p' => '%'.$_GET['p'].'%'));
}
?>
<table>
<tr>
<th></th>
<th>Title</th>
<th>Year</th>
<th>Genre</th>
</tr>
<?php while($row = $sql->fetch(PDO::FETCH_ASSOC)): ?>
<tr>
<td><img src="path/to/images/<?php echo $row['filename']; ?>" alt="" /></td>
<td><?php echo $row['movieName']; ?></td>
<td><?php echo $row['year']; ?></td>
<td><?php echo $row['genre']; ?></td>
</tr>
<?php endwhile; ?>
</table>