Delete any row in MySQL with button click - javascript

First, I will summary my demo for you: I have a form for me to type an api link and type of the chart I want to draw from my api link. After that, I will click the button to create chart and insert my input to MySQL database to show it on screen. Each chart have a button for me to delete it if I want.
Everything worked fine except delete funtion to delete my input from database. When I press delete button, it's only delete in html, not delete in my database. Can you help me? Thank you!
Here is my code:
My input form:
<!--HTML Form input-->
<div class = "login-block">
<form id="form1" style="display: block" method="POST" action="chart_test.php">
<!--Input link api-->
<b>Link: </b><input type="text" id="link" name="apilink"><br>
<br>
<!--Chart Type-->
<b>Chart Type:</b>
<label class="custom-select">
<select id="chartType" name="chartType">
<option value="">Select</option>
<option value="pie">Pie Chart</option>
<option value="column">Column Chart</option>
<option value="bar">Bar Chart</option>
</select>
</label>
<br><br>
<!--Button create chart-->
<div class ="wrapper">
<button type="submit" name="create" onClick="drawChart()">Create</button>
<br><br>
</div>
</form>
</div>
Insert input to database and show to screen:
<!--insert form data to mysql-->
<?php
$con = mysql_connect("localhost","root","123456");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
mysql_select_db("activiti_report");
//check data when first load page to not showing notice error
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$apilink = $_POST["apilink"];
$chartType = $_POST["chartType"];
}
if(isset($_POST['create'])) {
$sql = "INSERT INTO chartinfo (link, typeChart) VALUES ('$apilink', '$chartType')";
$result = mysql_query($sql);
header("Location:chart_test.php");
exit;
}
?>
Query database to show chart on screen and the button with script to delete:
<?php //query data from database
$result = mysql_query("SELECT * FROM chartinfo");
?>
<?php //while loop to read data from query result
while($db_field = mysql_fetch_assoc($result)):
?>
<?php //unique chartId for not the same to show more chart
$idChart = 'chartContainer_' . uniqid();
?>
<!--Show chart from database-->
<br>
<div class = "chart-block">
<?php // 2 lines about chart infomation
echo ("<b>API Link:</b> "); print $db_field['link'] . "<BR>";
echo ("<b>Chart Type:</b> "); print $db_field['typeChart'] . "<BR>";
?>
<!-- The <div> and <script> to show the chart -->
<div id="<?=$idChart?>" style="height: 360px; width: 70%;"></div>
<script>
$(document).ready(function() {
var dataPointsA = []
var text = document.getElementById('chartType')
var strChart = text.options[text.selectedIndex].value
$.ajax({
type: 'GET',
url: "<?php echo $db_field['link']?>", //assign URL from query result field
dataType: 'json',
success: function(field) {
for (var i = 0; i < field.length; i++) {
dataPointsA.push({
label: field[i].name,
y: field[i].value
});
}
var chart = new CanvasJS.Chart("<?=$idChart?>", {
title: {
text: "Activiti Report"
},
data: [{
type: "<?php echo $db_field['typeChart']?>", //assign type of chart from query result field
name: "chart",
dataPoints: dataPointsA
}]
});
chart.render();
}
});
});
</script>
<br>
<!--Button to delete the chart and row in database-->
<button type="submit" name="delete" onClick="removeParent(this.parentNode)">Delete</button>
<!--Script remove <div> contain the chart-->
<script>
function removeParent(parent) {
parent.remove();
}
</script>
<!--Script delete form data from mysql-->
<?php
if(isset($_POST['delete'])) {
$sql = "DELETE FROM chartinfo (link, typeChart) WHERE link ='" .$db_field['link']. "' AND typeChart = '" .$db_field['link']. "'";
$result = mysql_query($sql);
header("Location:chart_test.php");
exit;
}
?>
I know I should use mysqli_* instead mysql_* but this is just a demo for me to understand PHP, I learned it only a few days. Sorry for a lot of code but I think I should show to you to understand what I am doing.
Thank you very much!

Your delete button trigger its action from the js code not the php code. It only remove from the view but will appear on reload. You can use ajax in your remove function or use a delete link instead of button

<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>
$("#btn_del).on("click", function(){
var btn_this = $(this);
var id= $(this).attr('name');
$.ajax({
type: 'GET',
url: "delete.php",
data: {id:id},
success: function(resp) {
btn_this.parentNode.remove();
}
});
});
<?php
if(isset($_GET['id'])) {
$sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';
$result = mysql_query($sql);
}
?>

<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>
<script>
$("#btn_del).on("click", function(){
var btn_this = $(this);
var id= $(this).attr('name');
$.ajax({
type: 'GET',
url: "delete.php?id="+id,
success: function(resp) {
btn_this.parentNode.remove();
}
});
});
</script>
<?php
if(isset($_GET['id'])) {
$sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';
$result = mysql_query($sql);
}
?>

Related

How do i solve this php ajax and js issue?

am new with php.
Am creating a form with a dropdown list option from my db, i want this option to display the rest of the details in the text field when a user select any.
In the DB i have id, employee_name, employee_salary, employee_age.
This my Html file
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script type="text/javascript" src="script/getData.js"></script>
</head>
<body>
<select id="employee" class="form-control" >
<option value="" selected="selected">Select Employee Name</option>
<?php
$sql = "SELECT id, employee_name, employee_salary, employee_age FROM employee";
$resultset = mysqli_query($conn, $sql);
while( $rows = mysqli_fetch_assoc($resultset) ) {
?>
<option value="<?php echo $rows["id"]; ?>"><?php echo $rows["employee_name"]; ?></option>
<?php } ?>
</select>
<br>Craft 1<br>
<input type="text" id="craft_1_points" name="craft_1_points" value="">
<br>Craft 2<br>
<input type="text" id="craft_2_points" name="craft_2_points" value="">
<br>Craft 1<br>
<input type="text" id="craft_3_points" name="craft_3_points" value="">
<br>Craft 2<br>
<input type="text" id="craft_4_points" name="craft_4_points" value="">
</body>
</html>
</center>
<?php include('include/footer.php');?>
I have managed to add the names to the drop down list which is working and i used ajax and java to link.
But when i select any option e.g. Tiger Nicxin it supposed to fill the text field with the rest info of the selected name, id,age and salary. It's not working
please what do i have to do.
JS file
$(document).ready(function(){
$("#employee").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url: 'getlist.php',
dataType: "json",
data: dataString,
cache: false,
success: function(empData) {
if(empData) {
$("#errorMassage").addClass('hidden').text("");
$("#recordListing").removeClass('hidden');
$("#empcraft_1_points").val(empData.id);
$("#empcraft_2_points").val(empData.employee_name);
$("#empcraft_3_points").val(empData.employee_age);
$("#empcraft_4_points").val("$"+empData.employee_salary);
} else {
$("#recordListing").addClass('hidden');
$("#errorMassage").removeClass('hidden').text("No record found!");
}
}
});
})
});
Ajax file
<?php
include_once("include/db_connect.php");
if($_REQUEST['empid']) {
$sql = "SELECT id, employee_name, employee_salary, employee_age
FROM employee
WHERE id='".$_REQUEST['empid']."'";
$resultSet = mysqli_query($conn, $sql);
$empData = array();
while( $emp = mysqli_fetch_assoc($resultSet) ) {
$empData = $emp;
}
echo json_encode($empData);
} else {
echo 0;
}
?>
please help me with solution
in ajax your datatype changed to dataType: "json" and your id was wrong.
and include your DB connection in a index file or main file
you js file:
$(document).ready(function(){
$("#employee").change(function() {
var id = $(this).find(":selected").val();
var dataString = 'empid='+ id;
$.ajax({
url: 'getlist.php',
dataType: "json",
data: dataString,
success: function(empData) {
if(empData) {
$("#errorMassage").addClass('hidden').text("");
$("#recordListing").removeClass('hidden');
$("#craft_1_points").val(empData.id);
$("#craft_2_points").val(empData.employee_name);
$("#craft_3_points").val(empData.employee_age);
$("#craft_4_points").val("$"+empData.employee_salary);
} else {
$("#recordListing").addClass('hidden');
$("#errorMassage").removeClass('hidden').text("No record found!");
}
}
});
})
});

Can I pass variables into an ajax query?

I'm creating a website and I want to load different queries onto a page depending on which button is clicked.
Can I do it like this?
The HTML :
<div id="Proceed">
4 Projects have been suggested to proceed.
</div>
<div id="result">
<!-- The title of the projects will be loaded here -->
</div>
<button id="foo"> Search </button>
The javascript:
$('#foo').on('click' function(){ //the button
var x = $(this).find('div').attr('id'); // get the id
$.ajax({
url: 'profile/inbox',
type: 'POST',
data: { id: x },
success: function(res){
('#result').html(res);
}
})
})
On profile.php:
function Inbox(){
$id = $_POST['id'];
$query = $this->db->query("SELECT `title` FROM `table` WHERE id=?",$id);
$load = $query->result_array();
$this->d['load'] = $load;
}
EDIT: I added some html to show where I plan to load the results of the query.
For eg:(This is your code I just slightly modified because for
example)
<div id="Proceed">
<select id="city" name="city">
<option value="">City:</option>
<option value="glasgow">Glasgow</option>
<option value="london">London</option>
</select>
</div>
<div id="result">
</div>
<button id="foo"> Search </button>
Script:(For eg:)
$("#foo").click(function() {
$.ajax({
url: 'profile/inbox', //Pass this value to the corresponding URL
type: 'POST',
dataType: "html",
data: {
"city": $('#city').val(), //Here request the value for id name is city
},
success: function(response){
$("#result").html(response); //Retrieve value form URL to pass the view page and value to set in <div id="result">
}
});
});
This is my url page(you just see what are the process there.. This is
for eg)
$sql = "SELECT * FROM entries";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
  while($row = $result->fetch_assoc()) {
  echo "success"."id: " . $row["id"]. " - City: " . $row["city"]. "<br>";
  }
} else {
  echo "0 results";
}
When you want to use a POST variable from PHP side you have to use
$_POST/$_REQUEST method in your case $id = $_POST['id']; this will work

json increments one id but displays all ids

i am using json for like button. when users clicks it correctly increases the like count and stores in database for corresponding id but it shows increment for all ids in browser which is wrong. i want to display for only id where users has liked but it shows for all.
test url is http://way2enjoy.com/app/check/test/indexp.php
indexp.php file is
<?php
include('/home/xxx/con.php');
$query="Select * from users_jokes order by id desc limit 10";
$result=mysql_query($query);
?>
<html>
<head>
<meta charset="utf-8">
<script src="jquery-3.1.0.min.js"></script>
<script type="text/javascript">
var ajaxSubmit = function(formEl) {
var url = $(formEl).attr('action');
var comment=document.getElementById("jokes_comment").value;
var joke_id=document.getElementById("joke_id_hidden").value;
$.ajax({
url: url,
data:{
'action':'addComment',
'comment':comment,
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result) {
console.log(result);
$.ajax({
url: url,
data:{
'action':'getLastComment',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result) {
$('#jokes_comment').val("");
console.log(result[0].description);
$("#header ul").append('<li>'+result[0].description+'</li>');
},
error: function(){
alert('failure');
}
});
},
error: function(){
alert('failure');
}
});
// return false so the form does not actually
// submit to the page
return false;
}
var ajaxLike=function()
{
var joke_id=document.getElementById("joke_id_hidden").value;
// setup the ajax request
$.ajax(
{
url: 'likeskk.php',
data:{
'action':'increment_like',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result)
{
$.ajax(
{
url: 'likeskk.php',
data:{
'action':'display_like',
'joke_id':joke_id
},
dataType: 'json',
type:'POST',
success: function(result)
{
console.log(result);
$("label[for='like_counter']").text(result.likes);
},
error: function(result)
{
alert("error 2");
},
});
},
error: function()
{
alert('failure');
}
});
return false;
}
</script>
<p>commnet list</p>
<div id="header">
<ul id="commentlist" class="justList">
<?php
$query="Select * from comment where joke_id='2'";
$result=mysql_query($query);
while($data = mysql_fetch_array($result)){
$cont = $data['description'];
?>
<li><?php echo $cont;
?></li>
<?php
}
?>
</ul>
</div>
<?php
?>
<form method="post" action="processkk.php" onSubmit="return ajaxSubmit(this);">
<input type=text id="jokes_comment" name="jokes_comment">
</input>
<input type="submit" value="comment">
</form>
</body>
</html>
<?php
while($data = mysql_fetch_array($result)){
$id = $data['id'];
$cont = $data['content'];
$likes = $data['likes'];
?>
<p><?php echo $cont;?></p>
<input type="hidden" value="<?php echo $id ;?>" id="joke_id_hidden">
<p><button onClick="ajaxLike();">Like</button> <label for="like_counter"><?php echo $likes;?></label></p>
<?php }
?>
</body>
</html>
likeskk.php
<?php
include('/home/xxxxxxx/con.php');
$action=$_POST['action'];
if($action=="increment_like")
{
$joke_id=$_POST['joke_id'];
$query="update users_jokes set likes =likes+1 where id='".$joke_id."'";
$result=mysql_query($query);
// setup our response "object"
$retVal=array("Success"=>"true");
print json_encode($retVal);
}
if($action=="display_like")
{
$joke_id=$_POST['joke_id'];
$query = "select likes from users_jokes where id = '$joke_id'";
$qry = mysql_query($query);
while($rows = mysql_fetch_array($qry)){
$likes = $rows['likes'];
}
header('Content-Type: application/json');
// print json_encode(array('foo' => 'bar'));
print json_encode(array('success'=>'true','likes'=>$likes));
}
?>
when i click on one like all like increases. when i post comment on one id it appended and displays in all id
Copy and paste it.
<html>
<head>
<script>
function clickCounter(element)
{
element.value = parseInt(element.value) + 1;
}
</script>
</head>
<body>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
<input type="button" value="0" onclick="clickCounter(this)"/>
</body>
</html>
Because you are using the same id. id must be unique
<input type="hidden" value="4638" id="joke_id_hidden">
Rather than using a hidden input for each entry you could use a dataset on the button itself with the corresponding ID. When the button is clicked the javscript function could read that dataset value and use that in the ajax POST request. So, as an example:
<!doctype html>
<html>
<head>
<title>Like the jokes...</title>
</head>
<body>
<form id='bttns'>
<?php
/* pseudo generate some jokes with buttons and labels to emulate your page */
for( $i=1; $i < 20; $i++ ){
$random=rand(1,20);
echo "
<p>Funny joke...[{$i}]</p>
<input type='button' value='Like' data-id='$i' />
<label class='counter'>{$random}</label>";
}
?>
</form>
<script type='text/javascript'>
var col=document.querySelectorAll('#bttns input[type=\"button\"]');
for( var n in col )if(col[n].nodeType==1)col[n].onclick=function(e){
var el=typeof(e.target)!='undefined' ? e.target : e.srcElement;
var label=el.nextSibling.nextSibling;
var id=el.dataset.id;
label.innerHTML=parseInt( label.innerHTML )+1;
alert( 'use ajax to POST this id: '+id );
}
</script>
</body>
</html>
I should add perhaps that the ajax callback function would be the place to update the value of likes for each joke rather than as here - it's just example code showing how you could do away with hidden fields and the problem of duplicate ids.

how should i put data fetched from ajax call in hidden div box

i am working on a project and come across a module.
page1
user have to search from search bar which will take him to page 2.
page2
On page 2 all fetched results will get displayed to user in div's. Each result has a checkbox associated with it.
when i click on add to compare check box ,ajax call is executed and fetched selected result should appear in hidden div.
my problem is it is only shows first result in hidden div and not working with another result.
My code of page 2
<script type="text/javascript">
$(document).ready(function()
{
var check = $('#compare').val();
$("#compare").change(function() {
if(this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').html(data);
}
});
$("#compare_box").show();
}
else
{
$("#compare_box").hide();
}
});
});
</script>
</head>
<body>
<?php
$query = $_GET['search_bar'];
$query = "call fetch_data('$query')"or die(mysqli_error($conn));
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result))
{
$id = $row['course_id'];
$title = $row['course_title'];
$description = $row['course_description'];
$course_url = $row['course_url'];
$video_url = $row['course_video_url'];
$fee = $row['course_fee'];
$duration = $row['course_duration'];
$start_date = $row['course_start_date'];
$university = $row['university_name'];
$course_provider = $row['course_provider_name'];
$instructor = $row['instructor_name'];
$_SESSION['result'][$id] = Array('id'=> $id,'course_title' => $title,'course_description'=> $description,'course_url' => $course_url,'video_url' => $video_url,'fee' => $fee,'course_duration'=>$duration,'start_date'=>$start_date,'university' => $university,'course_provider'=>$course_provider,'instructor'=>$instructor);
?>
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
<?php
}
?>
page3 compare.php
<?php
session_start();
include 'includes/dbconfig.php';
$check = $_POST['value'];
$sql = "SELECT * from course_info_table where course_id = '$check' " or die(mysqli_error($conn));
$result = mysqli_query($conn,$sql);
$index = 0;
while($row = mysqli_fetch_array($result))
{
$title = $row['course_title'];
?>
<?php
}
echo json_encode($title);
?>
You can change
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">
to
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">
^you can only have one unique 'id' value in your html doc, which means your first id="compare" will work fine and others with id="compare" will be ignored by the DOM tree
Reference:
http://www.w3schools.com/tags/att_global_id.asp

inline update in mysql using jquery/php

I'm performing CRUD oprations using JQuery/Ajax and php/MySQL
i'm able to insert/select and delete data but i gotta stuck in edit/update. im pulling data into text box when i click on edit button but after editing when i click on save button unable to update in mysql db!!
Any help is Appreciated Thanks
html code
<span class="noedit name" idl='<?php echo $row->id;?>'>
<?php echo $row->url;?>
</span>
<input id="url1" name="url1" class="form-control edit name url1" value="<?php echo $row->id;?>"/>
<a ide='<?php echo $row->id;?>' id="edit" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
Jquery code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
alert(IdEdit);
$.ajax({
url:"pages/feeds.php",
type:"post",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
$('#id').val(show.id);
$('#url1').val(show.url);
}
});
});
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('error in updating');
}
});
});
PHP Code
if(isset($_POST['editvalue']))
{
$sql = "select * from test where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
if(isset($_POST['update']))
{
$sql = "
update test
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
I don't see an #id input in your code. is it there? I think the problem is here.
If this input exists, use the following tips:
Check if all values (id, url) are sended to your PHP script.
You can use console.log in Javascript or print_r, var_dump functions in PHP.
Change
$('.update').click(function(){
to
$('.saveEdit').click(function(){

Categories

Resources