I want to create a program where I can delete mysql records using button with ajax. My problem is that I don't know how to pass a mysql data as ajax parameter so if it matches with the query in the php file, it will be removed. I created one with php alone but it's a static program, I want it to be dynamic with ajax.
index.php :
<?php
require_once 'dbconfig.php';
$query = $con->query("SELECT * FROM statuspost ORDER BY id DESC");
while($i = $query->fetch_object()){
echo $i->post ?><button onclick='ajaxWallpost('.<?php
$i->id ?>.')'>Remove</button>
<?php
}
?>
<script src='https://ajax.googleapis.com/ajax/libs/prototype
/1.7.2.0/prototype.js'></script>
<script>
function ajaxWallpost(status){
new Ajax.Request('wallpost.php?type=post&
id='+status, {
method:'get',
onSuccess: function(transport) {
},
onFailure: function() { alert('Something went
wrong...'); }
});
}
</script>
wallpost.php :
<?php
require_once 'dbconfig.php';
if(isset($_GET['id'], $_GET['type'])){
$post = $_GET['type'];
$id = (int)$_GET['id'];
switch($post){
case 'post':
$con->query("DELETE FROM statuspost WHERE id={$id}");
break;
}
}
Any help will be greatly appreciated. Thanks
Try this it will work :
Since AJAX happens "behind the scenes" (so to speak) your redirect will just interrupt the response to your javascript handler. So PHP cannot redirect your browser now, javascript
can. So use javascript
to redirect the user.
You'll need to return the URL and have your callback kick the browser to a new location.
"You're doing the ajax call - the php header will redirect the ajax response... not the page that the user is currently sitting on. You will have to modify your javascript code in the client to change the location."
A javascript redirect is as simple as window.location.href = "http://mylocation";
Solution to your problem with Ajax and Javascript :
<script>
function ajaxWallpost(status){
new Ajax.Request('wallpost.php?type=post&id='+status, {
method:'get',
onSuccess: function(transport)
{
window.location.href = "index.php";
},
onFailure: function()
{
alert('Something went wrong...');
}
});
}
</script>
Solution to your problem without Ajax and Javascript :
<?php
require_once 'dbconfig.php';
if(isset($_GET['id'], $_GET['type'])){
$post = $_GET['type'];
$id = (int)$_GET['id'];
switch($post){
case 'post':
$con->query("DELETE FROM statuspost WHERE id={$id}");
break;
}
}
$query = $con->query("SELECT * FROM statuspost ORDER BY id DESC");
while($i = $query->fetch_object())
{
?>
<a href="index.php?id=<?php $i->id ?>&type=post>Remove</a>
<?php
}
?>
An HTTP redirect just says "The thing you were looking for? It's actually over there."
It won't make the browser stop processing it using XHR and start processing it as if you followed a link.
The contents of index.php
will be in transport.responseText
.
If you want to send the browser to a new page, then don't use Ajax.