2

I have a class file on root of the application, and in that class I have a public function deleteUser method. I want to call that method from frontend via ajax. The examples I have seen are something like this:

$.ajax({
            url: '/deleteUser.php',
            type: 'DELETE',
            success: function(){
                alert('cat deleted');
            }
        });

But what is throwing me off is I don't have a php file that just does delete code (deleteCat.php in this above example). I have that delete code inside my class. How am I to trigger an exact method inside a class from ajax without using url:XX?

tereško
  • 58,060
  • 25
  • 98
  • 150
Zach Smith
  • 5,490
  • 26
  • 84
  • 139
  • 3
    AJAX doesn't trigger a class or method, it makes a request to a PHP file like any other HTTP request. You would have *server-side* code which performs the logic you want. – David Oct 10 '17 at 21:10
  • so if you have a large application, and you want a simple method in it to be triggered, you have to create a file just for that class method? that seems weird to me. – Zach Smith Oct 10 '17 at 21:12
  • Who said you have to create a separate file for every method? That would indeed seem weird to me as well. But you *would* need to make an HTTP request to some PHP file which would execute your server-side code. – David Oct 10 '17 at 21:15
  • u will want to send **data** with that ajax request that includes the user id that should get deleted. and maybe check the response to see if successful or exploded rather than just alerting success – Andrew Oct 10 '17 at 21:15
  • mega6382 i will work through them this week thanks – Zach Smith Oct 11 '17 at 15:47
  • did any of the provided solutions work for you? – mega6382 Nov 20 '17 at 08:09

2 Answers2

0

you could do this:

Use data in your Ajax function to post a Json like:

data : { 'type' : 'delete' }

And set type to POST

In you php file do

If ($_POST['data']['type'] == 'delete') {
  delete();
}
SIMDev
  • 29
  • 2
  • 6
  • your answer is incorrect, check here https://stackoverflow.com/questions/2153917/how-to-send-a-put-delete-request-in-jquery – mega6382 Oct 10 '17 at 21:15
  • No. 'DELETE' is a Http Verb 'designed' to delete recourses on the server. So there's nothing wrong in using it... – Jeff Oct 10 '17 at 21:16
  • Thanks, didn't know that. Edited my answer. – SIMDev Oct 10 '17 at 21:24
0

Try the following inside the method deleteUser:

if($_SERVER['REQUEST_METHOD'] == "DELETE")
{
    //Delete query here
}

This will determine if the request is of type Delete or not. And if it is you can call your delete query. But make sure that call the method too, just defining it isn't enough.

mega6382
  • 9,211
  • 17
  • 48
  • 69