user765368
user765368

Reputation: 20346

show jquery ajax execution status

Let say I'm making an ajax call to some cakePHP controller action to delete some data from a database. But before I delete the data (which happens of course in my cakePHP controller action), I want to check whether or not the user who's requesting to delete the data has the permission to do so. What I'm trying to do is to display to the user the steps of executions, for example I have something like this:

$.ajax({
    type: 'POST',
    url: '.../some_cakePHP_controller_action',
    beforeSend: function(){
        $("my_loading_div").html("Checking permissions...");
    }
    success: function(){
        // do stuff on success
    }
});

1- When user clicks DELETE, I want to show him a loading div with a message like Checking permissions...

2- If the user has permissions to delete the data, the message changes for Removing data...

Now, as you can see above, the problem is that when the user clicks DELETE, he will have the message Checking permissions...., but my data may have been removed because I'm already inside my cakePHP function. So, the user will have the wrong message. How do I achieve this behavior please?

Thanks in advance for any help

Upvotes: 3

Views: 416

Answers (4)

javagenie
javagenie

Reputation: 11

Personally, I would check the permissions before giving them the option to delete something. More than likely I would simply do this when the page is being rendered. Something like:

<?php if (hasPermission) { ?> 
  html to show delete function 
<?php } else { ?> 
  html to login to delete
<?php } ?>

Upvotes: 1

It's not safe to validate if user is allowed or not via JS!!! JS can be modified before clicking on "Delete". You should validate it via PHP or both.

Upvotes: 1

Shyju
Shyju

Reputation: 218722

You may probably wants to make 2 ajax calls. First to check the permission and if permission available then to delete the item.

$("statusDiv").html("Checking permissions").fadeIn(100,function(){

   $.post("checkpermission?item=23",function(data){

         if(data=="allowed")
         {
             $("#statusDiv").html("Deleting...");
             $.post("mycontroller/delete/23",function(result){
               if(result=="deleted")
               {
                  $("#statusDiv").html("Deleted Successfully");
               }
            });    
    });

});

Upvotes: 1

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57650

You need multiple ajax call for this. The steps will be something like this,

  1. ajax call to check permission.
  2. On php end check if you have delete permission with is_writable function.
  3. Return the status of previous step and show this as ajax response
  4. According to the status of step 3. Send the delete request to php by ajax
  5. Call unlink on php end. Then check again if the file exists by file_exists
  6. Return the status of previous step and show message to user accordingly

Upvotes: 3

Related Questions