用AJAX“回头”

i'm new to AJAX and i'm still learning, i use it to delete an user account.

So, thats my main.js code:

function userDeleteAccout() {
 $.ajax({
  type: "post",
  url: "ajax.php?action=delete",
  error:function(){
   alert("Something went wrong!");
  }
 });
}

Runs perfect.

My ajax.php should be like:

if() {
 header("");
 OR
 echo "";
}
else {
 header("");
 OR
 echo "";
}

But this doesn't run. So i need to handle the result, again (using AJAX?) Thank you!

$action = $_REQUEST['action'];
if($action == 'delete') {
 // perform delete operation
}

echo '1';
exit;

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: