###前提・実現したいこと
非同期通信にて取得した値をDBに登録し、送信後の値をリアルタイムに表示させたい。
###発生している問題・エラーメッセージ
非同期通信にてモーダルを閉じる処理、次の動画を呼び出す処理及びDBにデータを保存するまでは実行できましたが、送信後の値(afterP)が送信前(beforeP)の値となってしまう。
手動でブラウザのリロードを行うと送信後の値(afterP)を取得できるが、元の動画に戻ってしまう。
dataType:"json"にすると送信時にアラートが表示 Error : SyntaxError: Unexpected end of JSON inputが出てしまい次に進みません。 index.ctpのJSON.encodeと JSON.parseを外すと上記エラーは出ませんが、videosの値をjsファイルに渡す方法がわからず外せていません。
###該当のソースコード
php
1Point.php 2class Point extends AppModel { 3 public function sumByUserId($userId) { 4 $data = $this->find('all', 5 array( 6 'conditions'=> array('user_id' => $userId), 7 'fields' => array('sum(point) as sumPoints'), 8 ) 9 ); 10 return $data['0']['0']['sumPoints']; 11 } 12}
php
1PointsController 2他のコード省略 3public function beforeFilter() { 4 parent::beforeFilter(); 5 $userId = $this->Auth->user('id'); 6 $beforeP = $this->Point->sumByUserId($userId); 7 $this->set(compact('beforeP')); 8} 9 10public function index() { 11 $this->set('videos', $this->Video->find('all')); 12} 13 14public function addPoint() { 15 if (!$this->request->is('ajax')) { 16 throw new BadRequestException(); 17 } 18 $userId = $this->Auth->user('id'); 19 $data = array( 20 'Point' => array( 21 'user_id' => $this->Auth->user('id'), 22 'point' => $this->request->data['point'], 23 ) 24 ); 25 $this->Point->create(); 26 $this->Point->save($data); 27 28 $afterP = $this->Point->sumByUserId($userId); 29 $this->viewClass = 'json'; 30 $this->set(compact('afterP')); 31 $this->set('_serialize', array('afterP')); 32 //$this->set('_serialize',(res));のまま使ってしまい気付ずこの時間になってしまいました。 33 }
javascript
1point.js 2他のコード省略 3$(".send").on("click",function(){ 4 $.ajax({ 5 type: "POST", 6 url: "/aaa/bbb/addPoint", 7 dataType: "json", //やっとjsonで動きました!有難うございます。 8 data: { 9 "point": point 10 }, 11 success: function(res) { 12 //モーダルを閉じる処理; 13 //次の動画を呼び出す処理; 14 $('#sumPoints').text(res.afterP); 15 }, 16 error: function(XMLHttpRequest, textStatus, errorThrown) { 17 alert('Error : ' + errorThrown); 18 } 19 }); 20 return false; 21 } 22});
html
1index.ctp 2他のコード省略 3<p>送信前:<?php echo $beforeP; ?> pt</p> 4<p>送信後:<span id="sumPoint"></span> pt</p> 5 6<?php 7function json_safe_encode($data){ 8 return json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); 9} 10 11$videos = json_safe_encode($videos); 12//$afterP = json_safe_encode($afterP);(削除) 13 ?> 14 15<script> 16var videos = JSON.parse('<?php echo $videos; ?>'); 17//var afterP = JSON.parse('<?php echo $afterP; ?>');(削除) 18</script>
###補足情報(言語/FW/ツール等のバージョンなど)
より詳細な情報
XAMPP 5.6.14-0
cakephp-2.7.8
jquery 1.11.0
10.0.17-MariaDB
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/06/02 14:33
2016/06/03 09:34 編集
2016/06/03 14:09
2016/06/04 09:22
2016/06/04 09:51