Welcome Guest, Not a member yet? Register   Sign In
How to handle direct link to controller/function/param?
#1

[eluser]Rob B.[/eluser]
I have a simple controller function which deletes a DB entry (it uses a model function to do so). I have a link to this in one of my views (http://www.example.com/item/delete/3) and I'm using jQuery to display a confirm dialog to make sure the user really wants to delete it. All fine. However if you just enter that URL in your browser the item is deleted without warning.

Is there a way to handle this either in the way I code the controller function or in the model?
#2

[eluser]connors[/eluser]
After the user confirms he wants to delete an entry, you can let the javascript make an AJAX call (I assume you're just redirecting to the URL) and use the following line to restrict the controller/function to AJAX calls only
Code:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
I belive this is the easiest way, especially when you've already use javascript for a confirm dialog - otherwise you could fiddle with some session variables.

Hope that helps Smile
#3

[eluser]Rob B.[/eluser]
I think I figured it out, and that is to make the function private in the controller, i.e.

function _delete($id) {
...delete code goes here...
}
#4

[eluser]n0xie[/eluser]
All you destructive methods should be POST, not GET.
#5

[eluser]mddd[/eluser]
@Rob B: making the function "private" will make it so that you can't call it directly in a url. But then you will have to make another mechanism to call that function. So I don't see how this solves the problem of calling the delete action through a url.

I agree with n0xie that you should not call the action that way.
I usually send some information in POST variables. It's easy to write a small Javascript to set a form value to indicate that the user has indeed agreed to delete something.

Code:
// javascript
function areyousure(id)
{
  var test = window.confirm('Are you sure you want to delete item number '+id+' ?');
  if (test)
  {
  document.myForm.formaction.value = 'delete';
  document.myForm.submit();
  }
}

The uri could be /controller/edit/42 (for editing item 42) and in your 'edit' method you would check to see if $_POST['formaction'] is 'delete'.




Theme © iAndrew 2016 - Forum software by © MyBB