I have a like and dislike system in a page, like and dislike works only on the first page but not on others post. Here is what I have tried
This is how I fetch information
Here is the php part
Like.php
if(isset($_POST['id'])){
$send = mysqli_query($connecDB, "UPDATE portfolio SET `like`='$view' WHERE `id`='$id'"); }
Javascript part
<script type="text/javascript">
$(".btn-success").click(function() {
var id = $('#id').val();
$.ajax({
type : "POST",
url : "ajax/like.php",
data: "id=" + id,
success: function(data) {
$('#result').html(data);
}
});
});
</script>
Here is the HTML part
$sql = "SELECT * FROM post ORDER BY id DESC LIMIT 10";
$result = mysqli_query($connecDB, $sql);
while($rowsmall = mysqli_fetch_array($result)){
<button class="btn btn-success btn-stroke" id="result"><?php echo $rowsmall['like']; ?> <i class="fa fa-thumbs-o-up fa-lg"></i> </button>
<input type="hidden" name="id" id="id" value="<?php echo $rowsmall['id']; ?>"> <?php } ?>
The problem I'm facing is that the javascript is again and again sending same hidden id.
In HTML id attribute must has an unique value in whole page and this line (var id = $('#id').val();) always return id of first post, use dataattributes to simply access post id, just like this
PHP
<?php $sql = "SELECT * FROM post ORDER BY id DESC LIMIT 10";
$result = mysqli_query($connecDB, $sql);
while($rowsmall = mysqli_fetch_array($result)){
<button class="btn btn-success btn-stroke" data-id="<?php echo $rowsmall['id']; ?>" >
<?php echo $rowsmall['like']; ?> <i class="fa fa-thumbs-o-up fa-lg"></i>
</button>
<input type="hidden" name="id" value="<?php echo $rowsmall['id']; ?>">
<?php } ?>
JavaScript
<script type="text/javascript">
$(".btn-success").click(function() {
var id = $(this).data('id'); // get data-id atrribute
var element = this;
$.ajax({
type : "POST",
url : "ajax/like.php",
data: "id=" + id,
success: function(data) {
$(element).html(data);
}
});
});
</script>
Related
I am fetching image with "id"(dynamic) and i want to delete image using ajax, Image is deleted successfully but unable to hide (div) dynamically (which i deleted)
Here is my html code
<?php
$banner=$store->banner;
if(!empty($banner))
{
$ban = explode(',', $banner);
$i="1";
foreach($ban as $key => $img)
{
$img;
$info=$img;
?>
<input type="hidden" id="id" name="id" value="<?php echo $store->id; ?>">
<input type="hidden" id="imgname" name="imgname" value="<?php echo $img; ?>">
<div class="form-group" id="<?php echo $key; ?>"> <!-- Creating div with id (dynamic) -->
<label for="status">image <?php ?></label>
<img src="<?php echo base_url(); ?>/<?php echo $img; ?>" width="80" height="80">
<a class="btn-sm btn-danger text-light" onclick="deleteFun(<?php echo $key; ?>)" href="#"> Delete</a>
</div>
<?php
$i++;
}
}
?>
Here is my ajax function,I just want to hide div(which i select/deleted),How can i do this ?
<script type="text/javascript">
function deleteFun(ImgId)
{
if (confirm("Are you sure you want to delete this banner ?")) {
var imgname = $('#imgname').val();
var id = $('#id').val();
$.ajax({
type: "POST",
url: "<?php echo base_url('upload_controller/deleteImage'); ?>",
data: {'id': id,'imgname':imgname,'ImgId':ImgId},
success: function(data){
$("#ImgId").remove();
console.log(data);
}
});
}
}
</script>
In your JS, you have to specify DIV id as a concatenated value to target the specific id as the id you are taking is coming in to the function as an argument.
<script type="text/javascript">
function deleteFun(ImgId)
{
if (confirm("Are you sure you want to delete this banner ?")) {
var imgname = $('#imgname').val();
var id = $('#id').val();
$.ajax({
type: "POST",
url: "<?php echo base_url('upload_controller/deleteImage'); ?>",
data: {'id': id,'imgname':imgname,'ImgId':ImgId},
success: function(data){
$("#" +ImgId).hide();
console.log(data);
}
});
}
}
</script>
i m trying to send a value from one page to another by using java script, where the user is redirected to the other php page oncick,
the problem i m having is sending a value to the other page
the code on 1st page is
<html>
<body>
<div id="management" onclick="myFunction()" class="col-md-2">
<p>Management</p>
</div>
<script>
function myFunction() {
var search="Assam";
location.href = "search.php";
}
</script>
</body>
</html>
and i want the value of search to be forwarded to the second search.php page
$search=how do i get the variable here;
$query = $pdo->prepare("select * from collegetable where name LIKE '%$search%' OR courses LIKE '%$search%' OR address LIKE '%$search%' OR affiliation LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">College Names</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Courses</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Price</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['name'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['courses'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['fees'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
use query string for forward to second page
<html>
<body>
<div id="management" onclick="myFunction()" class="col-md-2">
<p>Management</p>
</div>
<script>
function myFunction() {
var search="Assam";
location.href = "search.php?q=" + search;
}
</script>
</body>
</html>
and in second page get q from URL
$search= $_GET['q'];
$query = $pdo->prepare("select * from collegetable where name LIKE '%$search%' OR courses LIKE '%$search%' OR address LIKE '%$search%' OR affiliation LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">College Names</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Courses</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Price</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['name'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['courses'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['fees'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
U may use get parameters of url, for example:
<script>
function myFunction() {
var search="Assam";
location.href = "search.php?q=" + search;
}
</script>
To get parameters on search.php use $_GET method http://php.net/manual/en/reserved.variables.get.php
$search = $_GET['q'];
Ajax is the solution for you.
Plain ajax looks like this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
I would recommend using the jquery ajax, because it's way more simple and beginner friendly.
An example for your use case would look like this:
<script>
var search="Assam";
$.ajax({
method: "GET",
url: "some.php?search=" + urlencode(search)
}) .done(function( response ) {
$("#field-for-response").html(response);
});
</script>
In PhP you can read the value over $_GET["search"]. If you just want to locate the client just on the php page, you should have a look on this, but Ajax gives you the advantage of no need to reload the page and this is what makes the user experience much smoother.
Try this
Javascript
$scope.submitForm = function (form, e) {
if(form.$valid){
// e.preventDefault(e);
$http({
method : "POST",
url : "search.php",
data: {
"givenName":"james",
"displayName":"Cameroon"
},
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, X-Requested-With",
"Content-Type": "application/json"
}}).then(function(response) {
console.log(response);
}, function(response) {
console.log("Error"+response);
});
}
}
HTML
<form id="attributeVerification" name="vm.attributeVerification" onsubmit="submitForm(vm.attributeVerification)" novalidate>
<div class="attr" id="attributeList">
<ul>
<li>
<div class="attrEntry">
<label for="givenName">First name</label>
<div class="helpText" role="alert" aria-live="polite" tabindex="1">This information is required.</div>
<input id="givenName" name="givenName" class="textInput" type="text" placeholder="First name" title="Your given name (also known as first name)." required maxlength="15" ng-model="userInfo.givenName" aria-required="true">
</div>
</li>
<li>
<div class="attrEntry">
<label for="displayName">Last name</label>
<div class="helpText" role="alert" aria-live="polite" tabindex="1">This information is required.</div>
<input id="displayName" name="displayName" class="textInput" type="text" placeholder="Last name" title="Your display name." required maxlength="25" ng-model="userInfo.displayName" aria-required="true">
</div>
</li>
</ul>
</div>
<div class="buttons">
<button id="continue" aria-label="Create" type="submit">Continue</button>
</div>
</form>
change html to :
<html>
<body>
<div id="management" onclick="myFunction()" class="col-md-2">
<p>Management</p>
</div>
<script>
function myFunction() {
var search="Assam";
location.href = "search.php?search="+search;
}
</script>
</body>
</html>
php to :
$search = $_GET['search'];
$query = $pdo->prepare("select * from collegetable where name LIKE '%$search%' OR courses LIKE '%$search%' OR address LIKE '%$search%' OR affiliation LIKE '%$search%' LIMIT 0 , 10");
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table style=\"font-family:arial;color:#333333;\">";
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">College Names</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Courses</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;background:#98bf21;\">Price</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['name'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['courses'];
echo "</td><td style=\"border-style:solid;border-width:1px;border-color:#98bf21;\">";
echo $results['fees'];
echo "</td></tr>";
}
echo "</table>";
} else {
echo 'Nothing found';
}
I have a PHP script which Produces the n number of buttons as an output based on database records. Each value is associated with a respective button.
When I click any button, I always get the value of first button.
How can I get the value of button which is clicked only?
<button class='btn btn-danger question_delete' value=".$row['action_id']."</button>
My jQuery script:
$(document).ready(function(){
$(".question_delete").click(function(){
var action_value = $(this).val();
if(action_value){
$.ajax({
type:'POST',
url:'delete_question_group.php',
data:{delete_action:action_value},
success:function(data){
refresh_table();
refresh_paper();
}
});
}else{
// $('#select_qtype_list').html('<option value="">Select Question First</option>');
}
});
});
My PHP:
<?php
session_start();
$name =$_SESSION['name'];
$id = $_SESSION['id'];
include("database.php");
$run = mysqli_query($conn,"select * from users where id='$id' AND name='$name' ");
$user = mysqli_fetch_array($run);
$subject_id = $user['subject_id'];
$user_name = $user['name'];
$run1 = mysqli_query($conn,"select * from subject where sub_id='$subject_id'");
$subject = mysqli_fetch_array($run1);
$subject_name = $subject['sub_name'];
$query = $conn->query("select * from action where subject_id='$subject_id' AND user_id='$id'");
//Count total number of rows
$rowCounts = $query->num_rows;
//Display states list
if($rowCounts > 0){
$i=1;
while($row = $query->fetch_assoc()){
//echo '<option value="'.$row['qtype_id'].'">'.$row['qtype_name'].'</option>';
echo "<tr>";
//$q_id = $query['question_id'];
//$question_type_id = $query['question_type_id'];
echo "<td>$i</td>";
echo "<td>".$row['action_name']."</td>";
echo "
<td>
<button class='btn btn-danger question_delete' value=".$row['action_id'].">
<i class='fa fa-trash' aria-hidden='true'>
</i>
</button>
</td>
<td>
<button id='question_update' class='btn btn-primary' data-toggle='modal' data-target='#myModal_update' value=".$row['action_id'].">
<i class='fa fa-pencil' aria-hidden='true' >
</i>
</button>
</td>
</tr>
";
$i++;
}
}else{
echo '<td colspan="4" style="text-align: center; color:red;"><strong>No Questions are Selected</string></option>';
}
?>
Probably because the property action_id inside the value on each button don't change. Also you forgot to close the button tag, maybe that's why it doesn't work
<button class='btn btn-danger question_delete' value=".$row['action_id']."></button>
-This Problem is Solved and Worked Perfectly. Description of solution is as follow:
-First onclick attribute is used. and a function is created which takes the value of button each time when button will click.
Following Code is worked:
<button class='btn btn-danger' onclick='myfunction(this.value)' id='question_delete' value=".$row['action_id']."><i class='fa fa-trash' aria-hidden='true'></i></button>
JQuery Code:
$(document).ready(function(){
myfunction1 = function(e){
if(e){
$.ajax({
type:'POST',
url:'update_question_group.php',
data:{update_action:e},
success:function(html){
$('#update_action_list').html(html);
$('#update_action_list').selectpicker('refresh');
}
});
}else{
// $('#select_qtype_list').html('<option value="">Select Question First</option>');
}
}
});
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 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.