0

I have the below ajax js. I am trying to make a POST to my controller with the id . In the line starting with let id ... when I log it to console, I can see the id number but the controller doesn't receive it. Also in XHR/payload I see [object Object] which do not know why.

$(document).on('click', '.delete-task', function(event){
    // id comes from data-id
    let id = $(event.currentTarget).attr('data-id');
    $.ajax({
        url:  ajaxUrl+'/admin/tasks/delete',
        type: 'POST',
        // what data you passing.
        data: {
            'id' : id
        },
        processData: false,
        contentType: false,
        dataType: 'json',
        success: function(data) {
            console.log(data);
        }
    });
});

Route is; $routes->match(['get', 'post'], '/admin/tasks/delete', 'Admin\Task\Task_Controller::task_delete');

For my controller, I have the below. As it is a post, I expect to be able to get the id by using $this->request->getVar('id') but doesn't work. I always get 'success' => '0 'msg' => "No Task To Delete" returned. Any pointers appreciated.

```
public function task_delete(){
    $id = $this->request->getVar('id');
    if(empty($id)){
        $response = [
            'success' => 0,
            'msg' => "No Task To Delete",
        ];
        echo json_encode($response);
    } else {
        $task = new TaskModel();
        $task->task_delete($id);
        $response = [
            'success' => 1,
            'msg' => "Task Deleted",
        ];
        echo json_encode($response);
    }
}```

So I can see id=103 in the payload in the console but for somereason but reaching the controller. Interesting also is when I log log_message('error', $request->getMethod()); it is a critical error as blank. Even log_message('error', $request->isAjax()); is critical error as blank.

spreaderman
  • 918
  • 2
  • 10
  • 39
  • 1
    Why are you appending the id value to the route URL, when you say you want to send it via POST? – CBroe Jun 20 '22 at 07:24
  • Ok, I mixed up two patterns. Thanks for spotting. I have removed /'+id, and changed my routes to not expect a number in the URL. It still comes back "no task to delete" and Request Payload shows; [object Object] for some reason. – spreaderman Jun 20 '22 at 07:43
  • 1
    Show us your route definitions in `app\Config\Routes.php`. In addition, show us, the output of `$this->request->getPost()`. Lastly, show us the output of `$this->request->getPath()` – steven7mwesigwa Jun 20 '22 at 07:46
  • _"Request Payload shows; [object Object] for some reason"_ - probably due to `processData: false`. – CBroe Jun 20 '22 at 07:55
  • Here is the route: $routes->match(['get', 'post'], '/admin/tasks/delete', 'Admin\Task\Task_Controller::task_delete'); Here is the output of $this->request->getPath()/ getPost() which captures in ci4 logs. getPost -> ERROR - 2022-06-20 09:09:51 --> getPath -> ERROR - 2022-06-20 09:09:51 --> admin/tasks/delete – spreaderman Jun 20 '22 at 08:10
  • I change processData to true. I can now see id=103 (example) in the payload window but doesn't get to controller for some reason. – spreaderman Jun 20 '22 at 08:12
  • Unless you're sending/submitting [multipart/form-data](https://stackoverflow.com/questions/4526273/what-does-enctype-multipart-form-data-mean), you *shouldn't* be using [`processData: false`](https://api.jquery.com/jquery.ajax/#:~:text=By%20default%2C%20data%20passed%20in%20to%20the%20data%20option%20as%20an%20object) – steven7mwesigwa Jun 20 '22 at 08:13
  • [Edit your question](https://stackoverflow.com/posts/72683513/edit) and show us your HTML form snippet where you define the `data-id` HTML element attribute. In addition, please remove the [`processData: false`](https://api.jquery.com/jquery.ajax/#:~:text=By%20default%2C%20data%20passed%20in%20to%20the%20data%20option%20as%20an%20object) and [`contentType: false` declarations](https://api.jquery.com/jquery.ajax/#:~:text=When%20sending%20data%20to%20the%20server%2C%20use%20this%20content%20type) from the AJAX settings and try again. – steven7mwesigwa Jun 20 '22 at 08:43
  • The payload is being sent, eg, id=103. For info, the id in the table is being generated by javascript in datatables but I dont think the error is there. Here it is though: "columns": [ {"data":null, render: function ( data, type, row ) { return ' '+data.id+' | '; } }, – spreaderman Jun 20 '22 at 08:53
  • Inside your controller, can you log a `var_dump` of the `$request` object and post the contents? That might help. – parttimeturtle Jun 21 '22 at 17:32
  • As it is an sqyncronis request, I put this in my method in my controller: log_message('error', print_r(var_dump($request))); It just returns 1. Same with $_POST... maybe there is a better way to see info? – spreaderman Jun 22 '22 at 01:56
  • If I comment out dataType: 'json', I can see a lot of info in the console. This is shown; ["body":protected]=> string(6) "id=103" ["headers":protected]=> array(17) { ["Content-Type"]= – spreaderman Jun 22 '22 at 02:14
  • @spreaderman Passing a `var_dump` output to `print_r` is redundant and you're missing the second parameter to `print_r` anyways: `log_message('error', print_r($request, TRUE));` – parttimeturtle Jun 22 '22 at 21:57
  • @parttimeturtle thank you for your explanation. I have added that line but the $request is blank as follow; ERROR - 2022-06-23 00:33:24 --> – spreaderman Jun 22 '22 at 23:34
  • Does this answer your question? [$_POST array empty in PHP after an a request with post data](https://stackoverflow.com/a/33961235/7376590) – steven7mwesigwa Jun 23 '22 at 00:02
  • Where are you defining that variable `$request` from? Do you intend to mean `log_message('error', json_encode($this->request));` – steven7mwesigwa Jun 23 '22 at 00:06
  • sorry, huge dump json_encode($this->request)); but no id 103 anywhere in the dump. [get] => Array ( ) [post] => Array ( ) – spreaderman Jun 23 '22 at 03:58
  • Do you still have the AJAX configurations for `processData` and `contentType` as they are in the question? If that isn't the case, please update your question. – steven7mwesigwa Jun 23 '22 at 04:35

0 Answers0