A couple of issues here.
Firsly you're sending your request as POST in the javascript:
type: "post"
But then passing your data via the URL string:
url: "ajax.php?action=delete"
What you probably need to do is something like this:
Javascript
function userDeleteAccout() {
$.ajax({
type: "post",
data: { action: "delete" },
url: "ajax.php",
error:function(){
alert("Something went wrong!");
}
});
}
PHP
$data = $_POST['data'];
if($data['action'] == "delete")
{
doSomething();
echo "Delete successfull";
}else{
doSomethingElse();
echo "Something else done";
}
You should check out how to manage requests and responses in JSON. This is helpful for a beginner: http://www.lennu.net/2012/06/25/jquery-ajax-example-with-json-response/
Handling data coming back you can use .done()
:
function userDeleteAccout() {
$.ajax({
type: "post",
data: { action: "delete" },
url: "ajax.php",
error:function(){
alert("Something went wrong!");
}
}).done(function(msg)
{
alert(msg);
});
}
Check out the jQuery docs here: http://api.jquery.com/jQuery.ajax/
Security
But just as a last point, please take security into consideration here as anyone can send a JS request to this url forcing a delete of some sort.
I can go to your page, open my dev tools and run a html request with the post data {action: 'delete'}
and send the request to your ajax script thus deleting something.
So the main thing to do is: