2014-02-10 58 views
0

我卡住了,任何幫助將不勝感激。在Yii提交表單與ajax

我有一個表單提交ajax鏈接。

形式鏈路如下:

<div class="row buttons"> 
     <?php echo CHtml::Button('SUBMIT AJAX',array('onclick'=>'send();')); ?> 
</div> 

功能send包含以下內容:

function send() 
{ 

    var data=$("#comment-form").serialize(); 



    $.ajax({ 
    type: 'POST', 
    url: '<?php echo Yii::app()->createAbsoluteUrl("post/ajax"); ?>', 
    data:data, 
    success:function(data){ 
       alert(data); 
       }, 
    error: function(data) { // if error occured 
     alert("Error occured.please try again"); 
     alert(data); 
    }, 

    dataType:'html' 
    }); 

} 

而在控制器中的AJAX動作包含以下內容:

public function actionAjax() { 

$model=new Comment; 
if(isset($_POST['Comment'])) 
     { 
      $model->attributes=$_POST['Comment']; 

      if($model->validate()) 
      { 
      //$model->save(); 

      print_r($_REQUEST); 
      return; 
      } 
     } 
     $this->render('comment',array('model'=>$model)); 

} 
} 
?> 

print_r輸出顯示所有字段已填充:

Array 
(
    [Comment] => Array 
     (
      [post_id] => 2 
      [author] => sss 
      [email] => [email protected] 
      [url] => http://www.mysite.com 
      [content] => sksjdjh 
      [status] => 1 
     ) 

) 

當我取消了$model->save(),我得到完整性錯誤post_id cannot be null

看來我的模型是空的,我怎樣才能將模型設置爲$_REQUEST

非常感謝您的幫助。

+0

是否要更新記錄或創造新的紀錄? –

+0

做一個'print_r($ model-> attributes)'以確保它具有正確的值。 – Pitchinnate

+0

我做了print_r($ model-> attributes),然後post_id是空的!你知道爲什麼嗎 ? @Pitchinnate – klark

回答

0
<?php $form=$this->beginWidget('CActiveForm', array(
            'id'=>'customer-form-guest', 
            'enableClientValidation'=>true, 
            'clientOptions'=>array(
            'validateOnSubmit'=>true, 

             'afterValidate' => 'js:function(form, data, hasError) { 
       if(hasError) { 
        return false; 
     } 
       else 
       { 
     // return true; it will submit default way 
        ajaxSubmitHappen(form, data, hasError); and it will submit by ajax function 
       } 
      }', 
'htmlOptions'=>array('role'=>"form"))); ?> 

現在AJAX子,麻省理工學院的功能

function ajaxSubmitHappen(form, data, hasError) 
{ 
    if(!hasError) 
{ 

           $.ajax({ 

            "type":"POST", 
            "url":"<?php echo $url; ?>", 
            "data":form.serialize(), 
            "success":function(data){ 
            }, 

            }); 
    } 
     else 
    { 
     alert('error'); 
    } 

通過這種方式,您可以提交通過AJAX的形式....