How to run php Delete query in jquery without refreshing page - php

I want to delete value from database using PHP.
Using a table row and placed a button like "Delete" and I create a function like onClick='window.location='page.php?action=del&id=1' and in PHP for delete.
if($_REQUEST['action'] == 'del'){
$req_id = $_REQUEST['id'];
$del_query = mysql_query("DELETE FROM table WHERE id='$req_id'");
}
It's working well but, I don't want to refresh the page. Please tell me how can I do it without page refresh?

<button id='delete'>Click Me To Delete</button>
$('#delete').on('click',function(){
$.ajax({
type:'POST',
url:'page.php',
data:'action=del&id=1',
success:function(result){
//Deleted
}
});
});

Try this:
delete
<script type="text/javascript">
function delData(control,id){
$.ajax({type:'POST', url:'page.php?action=del&id='+id, success:function(result){
//alert('deleted');
$(control).parents('table').eq(0).remove();
}
});
}
<script>
NOTE:
You will need to add jQuery file for this.
This process is called ajax. Google it.
Then try to pass the data in post parameter rather than in query string.
Update: Note that now the 'this' is passed as a reference of this control to the method delData.

Related

display data via ajax when using $_GET

How do I display data based on `$_GET', which is to say without refreshing the page ?
I have this for example, and it shows the correct result whenever I click add (increments by 1), but of course it always first refreshes the page.
How do I make it do the same thing without visible page refresh, using ajax?
php and html
if (isset($_GET['add'])) {
$_SESSION['numbers']++;
}
echo $_SESSION['numbers'];
?>
<br>
add
<div id="response"></div>
And if for example I wanted to pull something from the database via post and print it, I would do something like this:
$.post('print_something.php', function(response) {
$('#response').html(response);
});
But how do I change that for get, since there is stuff in the URL plus sessions?
EDIT:
I tried this, I removed all php from the current script, added it to get.php which is now like this:
session_start();
if (isset($_GET['add'])) {
$_SESSION['numbers']++;
}
echo $_SESSION['numbers'];
And inside my main index script I have this:
$('a.add').click(function() {
$.get('get.php', function(response) {
$('#response').html(response);
});
return false;
});
Now it does not increment each time i click add, it just shows 1 the first time and doesn't change afterwards.
You are not passing the add parameter to your $.get, so isset($_GET['add']) is false. Add add to your ajax call
$.get('get.php', {add:true}, function(response) {
$('#response').html(response);
});
I put {add:true}, but true could be anything, as you are only checking if it is set, not the value
alternatively, you could also just add it to your url
$.get('get.php?add=true', function(response) {
$('#response').html(response);
});
Please find the example code below:
$('a.add').click(function(e) {
e.preventDefault();
var request = $.ajax({
url:"get.php", //Please provide the absolute URL to avoid errors.
type:"GET",
data:""
});
request.done(function(response){
$("#response").empty().html(response);
});
});

ajax $_POST data then redirect to new page

I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.

Run PHP code when user clicks link and pass variables

I need to run a PHP code from external server when user clicks a link. Link can't lead directly to PHP file so I guess I need to use AJAX/jQuery to run the PHP? But how can I do it and how can I pass a variable to the link?
Something like this?
<a href="runcode.html?id=' + ID + '"> and then runcode.html will have an AJAX/jQuery code that will send that variable to PHP?
use something like this in you page with link
Some text
in the same page put this somewhere on top
<script language='javascript'>
$(function(){
$('.myClass').click(function(){
var data1 = 'someString';
var data2 = 5;//some integer
var data3 = "<?php echo $somephpVariable?>";
$.ajax({
url : "phpfile.php (where you want to pass datas or run some php code)",
data: "d1="+data1+"&d2="+data2+"&d3="+data3,
type : "post",//can be get or post
success: function(){
alert('success');//do something
}
});
return false;
});
});
</script>
on the url mentioned in url: in ajax submission
you can fetch those datas passed
for examlple
<?php
$data1 =$_POST['d1'];
$data2 =$_POST['d2'];
$data3 =$_POST['d3'];
//now you can perform actions as you wish
?>
hope that helps
You can do this with an ajax request too. The basic idea is:
Send ajax request to runcode.html
Configure another AJAX to trigger from that page
Considering, this as the markup
<a id="link" href="runcode.html'">Test</a>
JS
$("#link").on("click", function() {
$.get("runcode.html", { "id" : ID }, function(data) {
//on success
});
return false; //stop the navigation
});

Php return data from database into a table which contains an onlclick button function

Basically i have php code which retrieves data from a database into a table, i have placed a button with an onclick function in each row of the table. the buttons aren't working cause its php(server side).
Could someone point me in the right direction to do this? retrieve data from Db put into a table with a button in each row with an onclick event.
thanks
Just use an anchor in each row and assign a class name for example :
<a class="delete_btn" href="index.php?action=fetchdta&id=1">Delete</a>
then use this jquery code on top of your page in a script tag :
<script>
jQuery(document).ready(function ($) {
$('.delete_btn').click(function(){
var urlt = $(this).attr('href');
$.ajax({
url: urlt,
success: function(data) {
//do Everything you want
}
});
return false;
});
</script>

Submit Value With Javascript

I'm a stuck with the following function:
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
parent.removeChild($child);
}
}
</script>
x
This function deletes a child element, and its content, which works great client-side! But I am wanting to pass a value to the server, in the same instance, so the content of the element can be deleted from the mysql database too. I have no idea how to do this, so any suggestions will be very appreciated!
Notes: $child, and $parent are strings generated within the php file, that I use to give each element a unique ID.
To make your life easier, use jQuery or similar framework. Here's how you would do it in jQuery:
$(function() {
$('.delete').click(function() {
var link = $(this);
var id = link.attr('id').replace('element_', '');
$.ajax({
url: 'handler.php',
data: {
element: id
},
type: 'post',
success: function() {
link.remove();
// Or link.closest('tr').remove() if you want to remove a table row where this link is
}
});
return false;
});
});
The HTML:
Remove
And handler.php:
mysql_query("DELETE FROM `table` WHERE id = '".mysql_real_escape_string($_POST['element'])."'");
Always remember to escape database input!
If you're a total noob as you said, you probably won't understand all of this so I suggest you read something about jQuery's AJAX capabilities and about overall development using jQuery or similar JavaScript framework.
Lets say I want to delete an entity using a ID
JQUERY - $.post()
This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). Jquery post docs
On the server assuming you have an open database connection.
mysql_query("DELETE FROM TABLE WHERE ID = ".$_POST['ID']);
more on mysql_query found here
EDIT:
So the following will only remove the element when the ajax post is complete. Note the first arg is the url to the script that will take the action , second is the data to be sent, in this case the ID post value will be {child.id} and the third is a anon inline callback function that will take action to remove the element client side.
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
$.post('{URLTOSCRIPT}', 'ID=$child.id',function () { parent.removeChild($child); });
}}
</script>
When you call the function, you'd want to put your PHP variables in tags like so:
<?php echo $parent; ?>
and
<?php echo $child; ?>
In the function definition, you will want to get rid of the PHP style variables and use something like:
function removeElement(parentDiv, childDiv) {
//CODE
}

Categories