Question

Hi i'm really new with YII, please help me to solve a simple problem. I'm trying to pass some values from js to action and then to put them into database. Most of this code i got from tutorial

public function actionInsert(){
    $post = file_get_contents("php://input");
    $data = CJSON::decode($post, true);
    $read = new Read();
    $read->attributes = $data;
    $response = array();

    $read->save();
}

Then i send:

$.ajax({
            type: "POST",
            url: "/read/insert/",
            data: "name=imja&short_desc=korotkoe&author=avtor&image=photo",
            error: function (){
                 alert('Error');
            },
            success: function(data){

            alert('success');

            }
    });

But i get an 'error' alert and nothing goes to DB.

Était-ce utile?

La solution

The values from .ajax don't get submitted as a JSON array, the values should simply be in the $_POST array. Also I like to return something like 'complete'. Try changing your code to this:

public function actionInsert(){
    $read = new Read();
    $read->attributes = $_POST;
    $response = array();
    $read->save();
    echo 'complete';
    die();
}

Or you can send it as a JSON array from the javascript side:

var data = {
    name: 'imja',
    short_desc: 'korotkoe',
    author: 'avtor',
    image: 'photo'
};
$.ajax({
    type: "POST",
    url: "/read/insert/",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify(data),
    error: function (){
         alert('Error');
    },
    success: function(data){
        alert('success');
    }
});

However even if you do this apache will see the header type and still populate the $_POST array correctly. So it really isn't needed.

Also if you haven't already install Firebug onto Chrome or Firefox so you can see that actual ajax calls in the console. See what error you are getting from your action function in your controller.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top