javascript - AJAX to call PHP file which removes a row from database? -
alright, asked question yesterday regarding how save blog posts user makes. figured out database side of it, , works fine. now, want remove blog post based after clicking onclick button. through hours of digging through web, i've found calling jquery ajax function best way go it. i've been tooling around it, can't working.
blog code retrieved database in blog.php:
$connection = mysql_connect("...", "...", "...") or die(mysql_error()); $database = mysql_select_db("...") or die(mysql_error()); $query = mysql_query("select * template") or die(mysql_error()); $template = mysql_fetch_array($query); $loop = mysql_query("select * content order content_id desc") or die (mysql_error()); while ($row = mysql_fetch_array($loop)) { print $template['title_open']; print $row['title']; print '<button class="deletepost" onclick="deleterow(' . $row['content_id'] . ')">remove post</button>'; print $template['title_close']; print $template['body_open']; print $row['body']; print $template['body_close']; } mysqli_close($connection);
this creates following html on home.php:
<div class="blogtitle" class="post3">title <button class="deletepost" onclick="deleterow(3)">remove post</button></div> <div class="blogbody" class="post3">content</div>
which should call remove.js when button clicked (this start lose i'm doing):
$function deleterow(id){ $.ajax({ url: "remove.php", type: "post", data: {action: id} }); return false; };
calling remove.php (no idea i'm doing):
$con=mysqli_connect("...","...","...","..."); if (mysqli_connect_errno()) { echo "failed connect mysql: " . mysqli_connect_error(); } $id = $_post['action']; $query = mysql_query("delete content content_id=$id") or die(mysql_error());
my goal here remove row id table in turn remove blog post entirely since won't see row when loops through database table.
any ideas?
thanks help, kyle
couple of issues in original code: functions in jquery shouldn't use $ sign @ beginning , since need pass single value use query string rather post, , instead of calling "die" in php use affected rows return callback of whether or not value deleted. approach, there other ways i'm sure.
here little improvements in code:
//html <div class="blogtitle" class="post3">title <button class="deletepost" data-item="3" >remove post</button></div> <div class="blogbody" class="post3">content</div> //jquery jquery(document).ready(function($) { $('button.deletepost').each(function(){ var $this = $(this); $this.click(function(){ var deleteitem = $this.attr('data-item'); $.ajax({url:'remove.php?action='+deleteitem}).done(function(data){ //colect data response or custom code when success }); return false; }); }); }); //php <?php $id = $_request['action']; $query = mysql_query('delete content content_id="'.$id.'"'); $confirm = mysql_affected_rows() > 0 ? echo 'deleted' : echo 'not found or error'; ?>
hope sample helps :) happy coding !
Comments
Post a Comment