Delete sql row using button without refreshing page [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to delete a row from table with delete button with confirmation from user but without page refreshing with help of jQuery ajax.
I know a little about php, html, javascript, jquery, and sql. I dont know how to go about doing this but what i really want to do is to be able to pull data from a sql table (i already know how to do this).
Then display the data with a button next to it (i also already know how to do). When they click the button it will remove the element that hold the visible data and also send a sql statment to delete the row in the database. A very crude code over view.
<?php
echo '<p>Data 1: '".$someDataFromDB."'<button id='deleteThisRow'></button></p>;
?>
from this I would like to:
Click the button
remove the paragraph element so they users know it was deleted
then send an sql statement to delete the row from the sql table
All this without refreshing the page. Is that at all possible?

Yes it is possible but you should only send the id of the entry to a particular page to delete the entry.never the entire sql statement.
<button id="<?php echo $row['id']; ?>" class="delbutton"></button>
add this script to your page
<script type="text/javascript" >
$(function() {
$(".delbutton").click(function() {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type : "POST",
url : "delete_entry.php", //URL to the delete php script
data : info,
success : function() {
}
});
$(this).parents(".record").animate("fast").animate({
opacity : "hide"
}, "slow");
}
return false;
});
});
</script>
and last but no the least your delete script
<?php
include 'connection.php';
$id=$_POST['id'];
$delete = "DELETE FROM table WHERE id=$id";
$result = mysql_query($delete) or die(mysql_error());
?>

Related

jQuery responds with html table containing a (form in each row plus jquery code to edit each row) newly created forms ignore submit()

Three days and I cannot find an answer to this or a solution. I am far from being a jQuery guy.
User arrives at a php page that shows a form to choose the language code and submit. Form gets submitted and the jQuery response builds a table in a div container in the original page. So far so good. The resulting table contains hundreds of rows where the language variables can be edited. On clicking the edit button, I get nothing, no errors in console, nothing. If I use on click, I can fire an alert. On submit, bind, and many others do not work.
I am attempting to load the table, perform basic editing, submit the edits to the db, and refresh the div.table.row with the edited results. I have not gotten to the part where I refresh the rows with the edited data, still stuck trying to submit the dynamic form in each row.
One interesting thing that happens when I use on click, it works with just the first button I click on, it somehow disables all the other rows. I need to be able to submit a row for changes, have that row refresh and move on to the next row all without redirecting. Is this too much to ask? Or should I just move them from page to page?
The ajax php page returns the table using the following code:
if(!empty($_POST['edit_language']) && $_POST['edit_language'] == 1){
edit_language($_POST['lang']); //call function to edit language
} else {
echo "You got here but no variables<br>"; //testing
print_r($_POST); //testing
}
function edit_language($lang){
//query table to get language vars list
$sql = "SELECT lang_site.lid, lang_codes.iso_code, lang_codes.`language`, lang_varnames.varid, lang_varnames.varname, lang_site.varval FROM lang_codes LEFT JOIN lang_site ON lang_site.langid = lang_codes.langid LEFT JOIN lang_varnames ON lang_site.varid = lang_varnames.varid where lang_codes.iso_code = '" . $lang . "'";
$result = db_query($sql);
//generate report table
echo "<table cellspacing='0' border='1'><tr><th>Count</th><th>Language</th><th>Variable Id</th><th>Variable Name</th><th>Variable Value</th><th>Edit</th></tr>";
$a=1; //count the rows to number the rows for easy viewing
while($data = db_fetch_assoc($result)){
//create form in each tr
echo "<form name='edit_" . $data['lid'] . "' id='edit_" . $data['lid'] . "' action=''><tr><td>" . $a++ . "</td><td>" . $data['language'] . "</td><td>" . $data['varid'] . "</td><td>" . $data['varname'] . "</td><td><textarea class='form-control' name='varval' id='varval' cols='100' wrap='virtual'>" . $data['varval'] . "</textarea></td><td id='editresponse'><button type='submit' class='button' type='submit' id='but_" . $data['lid'] . "'>Edit</button></td></tr></form>";
?>
//jquery to post edits
<script language="javascript">
$(document).ready(function()
{ //using $.ajax() function
//alert("document ready"); //this alerts each row
//this function will not work, no errors, simply nothing
$(document).on("submit", "#edit_<?php echo $data["lid"]; ?>", function(e)
{
//alert("button clicked"); //this does not work
var data = $("#edit_<?php echo $data["lid"]; ?>").serialize();
$.ajax({
type : "POST",
url : "/lang/ajax_langs.php",
data : data,
success : function(response)
{
{
$("#editresponse").html(response);
};
}
});
e.preventDefault();
});
});
</script>
<?php
}
echo "</table>";
}
?>
How do I get the jQuery to submit the individual form in each row to effect an edit and then refresh each row individually as languages are edited? I need to add another form to each row to delete an entry then remove the row dynamically, but I am stuck here without being able to submit any of these forms.
I should add that this generated form shows well in the website, but is not shown in view source. Using chrome browser. I'm open to any suggestions. Thanks in advance for reading. I seriously hope I can find a solution here. Otherwise, I'm back to the 90's on this software.
It's not working because you are only submitting one id. You need to make each of your forms be of the same class. Therefore, any form clicked will be processed. Like
<form class="myForm" .....
Then, the Jquery would look like this
$(".myForm").submit(function(e){
var inputToChange = this.varval; // saw input varVal, but use whatev
var dataToChange = inputToChange.value;
// then send the data to php for processing using ajax or post
Then, use inputToChange.value = whatever new value you want to put into the form input or other div/td etc. you want to change. If you want to change data that isn't in an input, just make that td a text input and disable it from being edited by the client
<input type="text" name="lname" disabled>
then on callback send new data to this.lname.value = (many other ways to do this as well)
Don't forget, if you send through ajax you want to stop the form itself from submitting so use e.preventDefault()

How to update a table without changing the onscreen data displayed

I need to display a simple list of hundreds of items which are on a MySQL table, review the list onscreen and click on a link beside each unwanted item to delete it from the table. This is an internal management procedure; no outside user is involved. I do not need the item to disappear from the list immediately; I will refresh the list periodically so items deleted from the table are no longer listed. I do not need any message to confirm that the item has been deleted. The important thing is that I don't want to lose sight of the list each time I delete an item and have to click on a "go back" button to return to the list.
The table uses MySQL. All my coding to date has been in PHP. So I am using php to display the list of items, on a non-html screen. This is the code for each item:
echo $item." <a href='item_delete.php?id=".$item."'>Delete item</a><br />";
This is the code for item_delete.php:
<?php
require ('connect.php'); // To define connection $con
$id = $_POST['id'];
mysqli_query($con, "DELETE FROM `items_table` WHERE `id` = $id");
?>
The item is deleted correctly but a blank screen is (understandably) displayed.
I have done a lot of searching but most people needing help want to do more advanced things and - because I have so far managed to avoid learning JavaScript, jQuery and AJAX - I can't even work out which of those technologies I need to update a table without changing the screen.
I get the impression that each PHP script always takes "focus" with it, so maybe I need a little JavaScript script to do this ?
If so:
- can I just change item_delete.php to item_delete.js or do I have to define the non-html list as an html one ?
- what js code is needed in item_delete.js ?
I have read about using: header("location:javascript://history.go(-1)");
or: header('Location: ' . $_SERVER['HTTP_REFERER']);
but they don't go back to the onscreen list.
I don't think I want the js script to perform a virtual "go back" because the list is originally produced by using (about 20) $_POST parameters, so I still seem to have to refresh it each time.
So I'd like a solution to remain with the list - rather than leave it and return to it. Thanks.
It would make a lot of sense to do the deletion asynchronously using javascript. However, the simplest and messiest way to achieve what you want, is to add target="_blank" to the links, (which will leave you with a open blank tab for each delete request you do).
echo $item." <a href='item_delete.php?id=".$item."' target='_blank'>Delete item</a><br />";
Or you can solve it by adding checkboxes in front of every item, check the items you want to delete and submit them as form parameters to the delete script.
If you want to delete to row in the onscreen table after the actual PHP code has run you can use the following implementation:
The HTML structure for the link requires a unique class name, such as:
echo 'Delete item'
Note the item id is stored inside a HTML5 data attribute. I have also added an onclick event handler which returns false to avoid the link refreshing the page.
The javascript used to delete the item use the JQuery AJAX method and binds to the specified class, which is: item-delete. The implementation requires Jquery version >= 1.9.0
(function(){
$('.item-delete').click(function(event) {
var target = $(event.target);
var id = target.data('item-id');
$.ajax({
url: 'item_delete.php',
method: 'POST',
data: {
id: id
},
}).done(function() {
target.remove();
}).error(function(err) {
console.error('Could not delete item with ID: ' + id);
console.error(err);
});
});
}())
The event listener is defined inside a self-executing function, which is automatically executed when the page-load completes and avoids poluting the global namespace.
You can delete the item directly on the same page without moving to another
page by passing the id through a hyperlink and then get it to finally delete
the unwanted item. CHECK THIS OUT, and please let me whether or not is what you
wanted :-)
// connection
mysql_connect("host", "user", "password");
mysql_select_db("your database name");
// select all the items from table.
$selectQuery = mysql_query("SELECT * FROM table_name" );
// use while loop to list all the items...
while( $row = mysql_fetch_array($selectQuery) )
{
// list the items as a hyperlink, passing their id through the URL.
?>
<?php echo "delete " . $row["item_name"]; ?>
<?php
}
// Below is the code to delete the item.
if( isset( $_GET["id"] ) )
{
$itemId = $_GET["id"];
// query to delete item
$deleteQuery = mysql_query("DELETE FROM table_name WHERE id = '$itemId' ");
//-----------THE MOST IMPORTANT PART. >>>
// redirect if delete is successfull.
if( $deleteQuery )
{
// reload the page to get the items minus the deleted one...
// let's say your sript name is delete.php
header("Location:delete.php");
}
}
?>
</code>

jquery cookies / javascript cookies [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm have planned to design a jewelry website with add to cart option. but i still don't know how to keep the selected items on the cart even after refreshing the page through jquery. so if anyone knew please provide an step by step example or tutorial.
You can use a simple JQuery get method which links to a PHP file which adds the product to the Site cookies; when you want to view the cart, explode the cookie.
An example:
$(document).ready(function(){
$("#product").click(function(){
// However you want to get the item ID
var itemID = document.getElementById("productID").value;
$.get("/inc/addtocart.php", { item: itemID }, function(data){
document.getElementById("result-sec").innerHTML=data;
});
});
});
Your PHP file will look like this:
if(isset($_GET['item'])){
$_COOKIE['cart_ids'] = $_COOKIE['cart_ids'] . '::' . $_GET['item'];
}
To view your cart items, simply:
$all_items = explode("::", $_COOKIE['cart_ids']);
foreach($all_items as $item):
echo $item . "<br />";
endforeach;

include content from html files into one main html file and then download it [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I want to create a page in which I have some checkboxes like:
Add headers:
"Add header-1", "Add header-2" "Add header-3"
Add contents:
"Add content-1", "Add content-2" "Add content-3"
and the same for "footers"
For each one of these checkboxes corresponds an html file, for example "header-1" corresponds to a file on my server called "header-1.html" and the same for the other files.
What I want to do is adding a button called "Download" and after the user checks, let's say "add header-1" and "add-content-1" and click "Download" they will receive an archive with the selected files merged into one main file called "index.html" .
This is an overall view about what I'm trying to achieve.
Is this possible using PHP ? If so can you give me some suggestions from where can I start?
What you could do, is use file_get_contents() on each of the files that have been selected, and then just concatenate those strings together. You'd have to come up with a way to determine which file has been selected, but then you'd just replace the file names with variables.
$fileOne = file_get_contents(file1.html);
$fileTwo = file_get_contents(file2.html);
$fileThree = file_get_contents(file3.html);
$fileToDownload = $fileOne.$fileTwo.$fileThree;
Then write the file :
$rHandler = fopen('my-new-file.html', r+);
fwrite($rHandler, $fileToDownlod);
fclose($rHandler);
Then just provide a link to whereever you wrote the HTML file.
<a href='my-new-file.html'>Download here</a>
UPDATE
You wanted to offer a zip file. Taken from http://php.net/manual/en/zip.examples.php
<?php
$zip = new ZipArchive();
$filename = "./my-html-files.zip";
if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
exit("cannot open <$filename>\n");
}
$zip->addFromString("testfilephp.txt" . time(), "#1 This is a test string added as testfilephp.txt.\n");
$zip->addFromString("testfilephp2.txt" . time(), "#2 This is a test string added as testfilephp2.txt.\n");
$zip->addFile($thisdir . "/too.php","/testfromfile.php");
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
?>
Then just offer a new download link
<a href='my-html-file.zip'>Download here</a>

PHP multiple records insert

I am attempting to reword my issue.
I have a datatable that can return thousands of records, each with multiple columns. There is a checkbox in the first column that, once the user checks it, they then click a button, and the CONTAINER_NUMBER that is associated with the row is sent to a modal window to be used in a form.
Here is the code for the checkbox:
echo "<tr><td><input type=\"checkbox\" id=\"{$Row[CONTAINER_NUMBER]}\" name=\"checkMr[]\" /></td>";
This is the javascript that retrieves the CONTAINER_NUMBER and sends it to the modal window:
<script type="text/javascript">
$(function()
{
$('a').click(function()
{
var selectedID = [];
$(':checkbox[name="checkMr[]"]:checked').each(function()
{
selectedID.push($(this).attr('id'))
});
$(".modal-body .containerNumber").val( selectedID );
});
});
</script>
This is the section of the modal window that displays the CONTAINER_NUMBER:
<div class="modal-body">
<form action="" method="POST" id="serviceModalForm" name="serviceModalForm">
<input type="text" name="containerNumber" id="containerNumber" class="containerNumber">
Here is the section of PHP that takes the id="containerNumber" and converts it to a PHP variable. After that, there is an INSERT statement that inserts the containerNumber into a database table:
<?php
$container = $_POST['containerNumber'];
if(isset($_POST['submit'])){
$container = mysql_real_escapse_string(stripslashes($container));
$sql = "INSERT INTO myTable (container_num) VALUES ('$container')";
if(mysql_query($sql)){
echo "Insert complete";
}
else {
echo "Insert was not completed";
}
?>
This code is fine. It works good. It does what it's supposed to do...for when the user checks ONE checkbox. It DOES NOT work when the user checks multiple checkboxes.
Basically, from what I've been researching is that I need to separate the records from the variable $container, as there can be multiple containers in that variable, which is why the query does not work when there are more than one container numbers selected.
I need to be able to separate the container numbers and store them in an array or something. The query will read each record separately and generate multiple INSERT statements for each record.
I've tried several times to create an array and get the sql statement to recognize it, but have been unsuccessful. I'm not sure if I'm placing the array in the right place. I'm not sure if this has to be done in the javascript before the container gets sent to the modal window.
I know I need to utilize a FOREACH loop to go through the array, but like I said, I'm not sure where the array needs to go in my code.
Please help. I know I need to learn PDO or MYSQLI. I will be sure to utilize PDO or MYSQLI on my next application. Until then, please help me with this issue.
Thank you, and sorry for so much wording.
Your containerNumber will be posted as a converted string from a js array. Something like id1, id2, id3[...]
In your php code, convert the $container back to an array ($containerArray = explode(",", $container)) and construct the sql dynamically to add all the rows in a single query so that the statment becomes something like
INSERT INTO myTable (container_num) VALUES ('$containerArray[0]'), ('$containerArray[1]')[...]

Categories

Resources