Search code examples
phpjqueryjsonajaxcakephp

CakePHP Return Array From Ajax Post Call


I know there are a ton of other 'duplicate' questions out there, regarding this topic. But I'm still stuck. I'm simply trying to console log an array passed from PHP through ajax.

In CakePHP 2.X:

In View:

<button class="quarter q1" value="1" value>Quarter 1</button>
<button class="quarter q2" value="2">Quarter 2</button>
<button class="quarter q3" value="3">Quarter 3</button>
<button class="quarter q4" value="4">Quarter 4</button>

<script type="text/javascript">
  jQuery(document).ready(function($){
    $('.quarter').click(function(e){
        e.preventDefault();
        var quarter_val = this.value;

        $.ajax({
            url: "/rep/testQueue",
            type: "post",
            data: {quarter_val:quarter_val},
            success: function(data) {
                var months = <?php echo json_encode($months); ?>;

                console.log(months);
            },
            error: function(){

            },
            complete: function() {
            }
        });

    });
  });
</script>

In my Controller:

public function queue() {
  if($this->request->isPost()) {
    $this->autoRender = false;
    $this->layout = false;

    $quarter_chosen = $this->request->data['quarter_val'];
    $month s= $this->_get_quarter($quarter_chosen);

    $this->set('months', $months);
   }
  }


  public function _get_quarter($quarter_chosen){
      switch($quarter_chosen) {
          case 1: return array('January', 'February', 'March');
          case 2: return array('April', 'May', 'June');
          case 3: return array('July', 'August', 'September');
          case 4: return array('October', 'November', 'December');
      }
  }

I've tried multiple different things. array_map, JSON.parse, setting dataType to json. Still, when I try to console log months in the ajax success function, I get null.

If I'm not understanding something correctly, please fill me in, or share sources that will. Thank you kindly.


Solution

  • Mate, you can use the cake's JS helper. On the 'succes' at the Js->request method, the data will be received as "data".

    //somewhere on view
    $this->Js->get('.quarter')->event('click', 
        'var quarter_val = $(this).val();' .
        $this->Js->request(
          array('controller' => 'ya controller', 'action' => 'ya action' , 'ya arguments (if needed)'),
          array(
              'async' => true,
              'dataExpression' => true,
              'data' => '{quarter_val: quarter_val}',
              'method' => 'POST',
              'success' => 'console.log(data);' // It should print the returned data into your console
            )
          )
    );
    
    //Now, to print the buffered script by the JS helper:
    echo $this->Js->writeBuffer();
    
    //To print it into your script block
    $this->append('script');
    echo $this->Js->writeBuffer();
    $this->end();
    

    Your controller method should echo the array instead set it with $this->set(). You will receive the data with JS so you must echo the data json_encoded so your script can use it.

    //On your queue method, instead $this->set('months', $months);
    echo json_encode($months);
    exit();