jquery - CakePHP Return Array From Ajax Post Call -
i know there ton of other 'duplicate' questions out there, regarding topic. i'm still stuck. i'm trying console log array passed 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 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 json. still, when try console log months in ajax success function, null.
if i'm not understanding correctly, please fill me in, or share sources will. thank kindly.
mate, can use cake's js helper. on 'succes' @ js->request method, data received "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);' // should print returned data console ) ) ); //now, print buffered script js helper: echo $this->js->writebuffer(); //to print script block $this->append('script'); echo $this->js->writebuffer(); $this->end();
your controller method should echo array instead set $this->set(). receive data js must echo data json_encoded script can use it.
//on queue method, instead $this->set('months', $months); echo json_encode($months); exit();
Comments
Post a Comment