CakePHP: controller response for Ajax request is incorrect

I use jQuery to make an AJAX request to some controller action. This request is activated using the button as an edit action in the same controller.

My problem: Ajax request returns all edit view code (with all forms and inputs) instead of the expected number. If I put the same ajax button in the add action view, it works fine (it returns a number).

Editing and adding actions remain by default (using bake).

This is jQuery function to make ajax request

        $.ajax({
            type: 'POST',
            url: 'checkTargets',
            data: {target: tgt_array, channel: channel_type},
            success:function(data){
                $('#num_subscribers > span').html(data);
            },
            error:function(){
                $('#num_subscribers > span').html("The subscribers could not be loaded");
            },
            timeout: 5000
        });
    } 

This action

function checkTargets() {
        if ($this->RequestHandler->isAjax()) { 
            if(!empty($this->params['form'])) {
                $data = $this->params['form'];

                if ($data['channel'] === 'SMS') {
                    $channel = 'sms';
                } else {
                    $channel = 'pin';
                }

                $targets = $this->processPostTargets($data['target']);
                $this->RequestHandler->respondAs('text');
                //This echo a NUMBER
                echo ClassRegistry::init('Selection')->countSubscribersInTarget($channel, $targets);

                Configure:: write('debug', 0);
                $this->autoRender = false;
                exit();

            }
        } 

    }

Why is this happening?

thank

+3
source share
2 answers

. URL .ajax( noob)

.

: URL- ajax cakePHP

Ajax:

    $.ajax({
        type: 'POST',
        url: '/myapp/campaigns/checkTargets',
        data: {target: tgt_array, channel: channel_type},
        success:function(data){
            $('#num_subscribers > span').html(data);
        },
        error:function(){
            $('#num_subscribers > span').html("The subscribers could not be loaded");
        },
        timeout: 5000
    });

+4

, , ?

$this->autoRender = false;
$this->layout = 'ajax';

:

$.post("/controller/checkTargets", function(data) {
   alert(data);
}

function checkTargets() {
  $this->autoRender = false;
  $this->layout = 'ajax';
  echo "Im working";
}

.

+5

Source: https://habr.com/ru/post/1762777/


All Articles