0

I have a javascript file from which I am trying to make a ajax call to execute method of a different php file.

Javascript file - a.js

function update() {
        $.ajax({
            url:"abcd.php",
            type: "POST",
            dataType: 'json',
            data: {"updateMethod()"}

            success:function(result){
                console.log(result);
            }
         });
}

PHP file - abcd.php

<?php

class abcd {
    public function updateMethod() {
        //execute this part of the code
    }

    public function insertMethod() {

    }

    public function deleteMethod() {

    }


}

I am not able to make a call to the PHP method. What is wrong with my AJAX query or what do I need to do in PHP file side to call the method.

Ad-vic
  • 519
  • 4
  • 18

3 Answers3

3

I don't know what you try to do, but you can do it this way:

function update() {
    $.ajax({
        url:"abcd.php",
        type: "POST",
        dataType: 'json',
        data: {methodName: "updateMethod"},
        success:function(result){
            console.log(result);
        }
     });
}

On server side:

<?php

class abcd {
    public function updateMethod() {
        //execute this part of the code
    }

    public function insertMethod() {

    }

    public function deleteMethod() {

    }
}

$abcd = new abcd();
$method = $_POST['methodName'];
$result = $abcd->$method();
u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

Remove this line

dataType: 'json',

and send data without json

If you sending json in php must be:

$data = file_get_contents('php://input');

PHP "php://input" vs $_POST

Or beter jquery:

var methodName = "YourMethodName";
var y = "Cymbal";

$.post( "test.php", { methodName: methodName, lastname: y })
  .done(function( data ) {
   alert( "Data Loaded: " + data );
});
SampleMi
  • 26
  • 2
0

Maybe something like this is more secure and I think you also need function arguments for CRUD actions(Not tested):

backend:

class CRUD
{
    public function update($args) 
    {
       $input = $args['exampleInput'];
       // sanitize input 
       // prepared query
       // $stmt->execute($input);
    }
}


function access($class, $method, $args) 
{
    if (method_exists($class, $method)) {
        return call_user_func_array([$class, $method], [$args]);
    } 
}

$data = file_get_contents('php://input');
access('CRUD', $data->method, json_decode($data->args));

js:

function handleAction(methodName, arguments) {
  $.ajax({
    url: "crudFile.php";
    type: "POST",
    data: { method: methodName, args: arguments },
    dataType: 'json',
    success: function (result) {
      console.log(result);
    }
  });
}

var inputs = {
  exampleInput: function () {
    return document.getElementById('your-div-id').textContent();
  },
};

// usage

handleAction('update', inputs);
bgul
  • 136
  • 7