Sasha
Sasha

Reputation: 8705

Jquery and ajax, when not success response

I have code like this:

 $(".delete").click(function() {    
    var commentContainer = $(this).parent();
    var id = $(this).attr("id");            
    var string = 'id='+ id ;
    $.ajax({   
        url: "<?php echo site_url('admin/delete_admin') ?>",
        type: "POST",
        data: string,
        cache: false,
           error: function(){
            $(this).parent().append('You can not delete admin. Please contact main admin .');
        },
        success: function(){
            commentContainer.slideUp('slow', function() {$(this).remove();});               
        }         
    });
    return false;
});

and PHP:

function delete_admin()
{        
    $q = $this->admin_model->get_admin();
    if($q->privilege == 'main_admin')
        {
      $this->admin_model->delete_admin( $_POST['id']);         
        } 
        else 
        {
            return false;
        }
}//end of delete_admin

How to send message that user can't do delete? Function is working like it is success every time (container is sliding).

Upvotes: 0

Views: 202

Answers (2)

Guffa
Guffa

Reputation: 700322

The response data is sent to the success callback function, so you can pick it up and check the value.

If you return the string "ok" for success:

success: function(data) {
  if (data == "ok") {
    commentContainer.slideUp('slow', function() {$(this).remove();});               
  } else {
    $(this).parent().append('You can not delete admin. Please contact main admin.');
  }
}

Upvotes: 2

Mridul Kashatria
Mridul Kashatria

Reputation: 4187

you can set the header to any of the error codes. Use php's header function to set header to 400.

Using codeigniter, you can use this kind of call to convey error message;

$this->output->set_header("HTTP/1.0 400 Bad Request");

In your PHP code do,

function delete_admin()
{        
  $q = $this->admin_model->get_admin();
  if($q->privilege == 'main_admin')
    {
      $this->admin_model->delete_admin( $_POST['id']);         
    } 
    else 
    {
        $this->output->set_header("HTTP/1.0 400 Bad Request");
    }
}

Upvotes: 0

Related Questions