R
R
Ruslan2021-12-13 11:44:27
AJAX
Ruslan, 2021-12-13 11:44:27

How to debug ajax request to controller in opencart?

Hello! I'm trying to make my comments module on the opencart 2.3 site. Sending data on click on an element

$('#ret').click(function(){
    var name = $('.add_com input[type=\'text\']').val();
    var image = $('.add_com input[type=\'hidden\']').val();
    var text = $('.add_com textarea').val();
    $.ajax({
      url: 'index.php?route=extension/module/comments/addComment&token=<?php echo $token; ?>',
      type: 'post',
      data: { name: name, image: image, text: text },
      dataType: 'json',
      beforeSend: function() {
        console.log($('.add_com input[type=\'text\']'));
      },
      error: function (json) {
                                console.trace(json);
                                alert(json['name']);
      },
      success: function(json) {
        console.log('added');
        console.log(json);
                                location.reload();
      }
    });
    return false;
  });

In the controller, the addComment function looks like this
function addComment(){
      $json = array();
      $json['name'] = 'Test';
      $this->response->addHeader('Content-Type: application/json');
      $this->response->setOutput(json_encode($json));
}

As a result, according to the result of working out ajax, this code is triggered
error: function (json) {
                                console.trace(json);
                                alert(json['name']);
      },

And the alert displays an undefined value. So it turns out nothing is returned from the controller ...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BogSala, 2021-12-13
@kuchuluk

I had a similar error, the first thing to check is network in the browser, and second, you need to make sure that your php code to which you send the request is in a separate file, and is not called by methods like require from somewhere else, it should only be called by ajax , and try to remove the data type, it also sometimes interferes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question