1

I have the following JQuery code:

 $('#dropdown').bind('change', function() {       
    var formData = $('#newform').serialize()
    $.ajax({
        type: 'POST',
        url: baseUrl+"crm/orders/ajaxEdit",
        data: formData,
        success: function(){ 
            console.log("ok");
        },
        error: function() {
            console.log("not ok");
        }
    });
 });

The ajaxEdit action is very simple:

    function ajaxEdit() {
        $this->layout = 'ajax';
        $this->autoRender = false;
        $this->Order->save($this->data['Order']);
    }

It works fine in that the data from the form is posted to the correct action in my CakePHP controller.

However, regardless of whether the insert query in CakePHP is successful or not, the "ok" message gets echoed to the console unless the HTTP request fails or something.

How can I get cake to send an error back to JQuery that JQuery will recognize as an error and echo "not ok" to the console in the event that there's a validation error or some other insert error in the Cake action?

4

1 回答 1

0

try this: jquery code

$('#dropdown').bind('change', function() {       
    var formData = $('#newform').serialize()
    $.ajax({
        type: 'POST',
        url: baseUrl+"crm/orders/ajaxEdit",
        data: formData,
        success: function(output){ 
            var x =  jQuery.parseJSON( output );
            if(x.success == 1){
                console.log("ok");
            }else{
                console.log("not ok");
            }
        },

    });
});

ajax edit action

function ajaxEdit() {
    $this->layout = 'ajax';
    $this->autoRender = false;
    if($this->Order->save($this->data['Order'])){
        $res = array('success'=>1);
        $str=json_encode($res);
        echo $str; 
    } 
    else{
        $res = array('success'=>0);
        $str=json_encode($res);
        echo $str; 
    }
}
于 2012-07-14T07:15:26.267 回答