kris016
kris016

Reputation: 147

How to return ajax response with error http code from PrestaShop ModuleFrontController?

I start working with PrestaShop 1.7.6 (before I worked with Symfony) and I write few custom modules to PrestaShop, but now I want send json data from my front controller module to user. Everything works fine if I send json with http code 200, but now I want send error message with proper http code (e.g 400). In Symfony I can do that by using JsonResponse (I try to do that here but it's not working as expected).I saw in presta controller are just two methods with ajax response (ajaxDie - which is deprecated and ajaxRender), but both of them doesn't takes as parameter http code response and always send 200.

    if (!$product) {
         $json = Tools::jsonEncode(['status' => false]);
         $this->ajaxRender($json);

         //return new JsonResponse($json, Response::HTTP_BAD_REQUEST);// doesn't send proper code
    }

Can anyone tell me how to send error code from module front controller which extends ModuleFrontController?? Now only possible to me action is send error message with http code 200 (but I think it's bad idea to send error with that code). Thanks a lot for any help.

Upvotes: 0

Views: 2090

Answers (1)

Crezzur
Crezzur

Reputation: 1481

The proper way to send and receive data using AJAX is displayed below. More information can be found at Prestashop Docs

Ajax post

    $.ajax({
        type: 'POST',
        dataType : 'json',
        url: 'linktoyourfile.php',
        data: { action: 'getMyrequest' },
        success: function(data) {
            alert(data.result);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            alert('Error: ' + textStatus + ' ' + errorThrown);
        }
    });

Module Front Controler

    class TestModuleFrontController extends ModuleFrontController
    {
        public function init()
        {
            parent::init();
        }

        public function displayAjaxGetMyrequest()
        {
            // ERROR HANDELING
            if ($this->errors) {
                die(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors)));
            } else {
                echo Tools::json_encode(array('result' => 'test result'));
            }
        }
    }  

Upvotes: 0

Related Questions