Ajax call, snippet, best solution?

Hi (sorry for my english),
I have a lot of actions that are called by ajax and I would like to know the best solution

My script it’s similiar to this:

$.ajax({
    			type: "POST",
    			url: "ajax-call.html",
    			cache: false,
    			datatype: "text",
    			data: {  
    			        "azione": "azione2",
    					"par1": 'par1',   
    					"par2": 'par2', 					
    					},
....

Resource ajax-call.html simply contains the snippet [[!sAjaxCall]]
sAjaxCall is a static snippet with hundreds of actions based on the “azione” parameter of the ajax call
I use custom tables and the bootstrap.php file works fine :slight_smile:

In file snippet if put this:

//Some check
$azione = $_POST['azione'];
$ns='Custom\\Model\\';
//The hundreds of action :)
if($azione == 'azione1') {
       //Code
       $qAz = $modx->newQuery($ns.'CustomClass');
       //return code
}
if($azione == 'azione100') {
       //Code
      $qAz = $modx->newQuery($ns.'CustomClass');
      //return code
}

all it’s ok, but if i use functions instead of if statement like this:

$azione = $_POST['azione'];
$ns='Custom\\Model\\';
return $azione();
//The hundreds of action :)
function azione1() {
       //Code
       $qAz = $modx->newQuery($ns.'CustomClass');
       //return code
}
function azione2() {
       //Code
       $qAz = $modx->newQuery($ns.'CustomClass');
       //return code
}

I have the following error

 Call to a member function newQuery() on null 

I do not know why, where is the error?
I tried adding the package inside the functions, calling the complete class in the query but nothing

Besides this, what is the best solution for a similar case where I have hundreds of ajax actions to call?

Inside the function, the variable $modx is not defined (because it’s out of scope).

You could either pass $modx as an argument

return azione1($modx);
function azione1($modx) {
    $qAz = $modx->newQuery($ns.'CustomClass');
}

or maybe use a closure

$azione1 = function () use (&$modx) {
    $qAz = $modx->newQuery($ns.'CustomClass');
};
return $azione1();

Don’t put all your code in one snippet. It’s probably better to use classes instead.
For example create the classes Custom\Actions\Azione1, Custom\Actions\Azione2, etc.
Then in the snippet, generate the class name from the $_POST parameter. If the class exists (class_exists($class_name)), instantiating the class ($action = new $class_name($modx);) and run some method that everyone of your classes has (e.g. $action->execute()).

Many, many, many thanks, I’m embarrassed it was so obvious :flushed:

For best solution i study classes because i’m dummies with modx’s classes :grinning:

1 Like