Search code examples
phpjavascriptajaxexpressionengine

Expression Engine - PHP - Can't run function


I'm trying to run a PHP Script with ExpressonEngine tags from my page using Ajax. I've set up the PHP script according to documentation, but I can't seem to actually call the function in the PHP script. I must be missing something.

My Ajax:

function createNew(obj) {
    $.ajax({
    url: 'createNew.php',
       data: "call=create_new",
    type: 'GET',
       success: function(data){
        obj.innerHTML = data;
    }
    });
}

My PHP:

<?php

if($_SERVER['REQUEST_METHOD']=="GET") {
$function = $_GET['call'];
if(function_exists($function)) {        
    call_user_func($function);
} else {
   echo 'Function Not Exists!!' . $function;

}
}

class CreateNewEntry {
    public function create_new() {
        $this->EE->load->library('api');
        $this->EE->api->instantiate('channel_entries');
        $this->EE->api->instantiate('channel_fields');
        $channel_id = $this->channel_id;

        $data = array(
                'title'        => 'Ny entry',
             'entry_date'  => time(),
                 'ping_servers'=> array(),
                'url_title'    => 'new-entry',
                'field_id_2'   => '5.0',
                'field_id_3'   => '10%',
                'field_id_4'   => 'Author',
             'field_id_5'   => '4x4',
             'field_id_6'   => '<p>Some text</p>'
        );

        if ($this->EE->api_channel_entries->submit_new_entry($channel_id, $data) === FALSE)
            { 
            $errors = $this->EE->api_channel_entries->errors;
             echo $errors;
          }     
        echo 'Success';

    }
}
?>

At first, I tried not using a class and a function. But I got errors on $this, which seems to need to be in a function inside a class. So I did that. But it's still not working. Any ideas?


Solution

  • The create_new is a class method so you can not use only call_user_func( $function) to execute it.

    I have 2 solutions:

    $obj = new CreateNewEntry();
    call_user_func(aray($obj, $function));
    

    OR

    call_user_func("CreateNewEntry::".$function);
    

    (the 2nd way need the create_new method declared as static method.