Transferring JSON to CodeIgniter via AJAX

5

I'm not able to pass a string in the format JSON to a controller of CodeIgniter via AJAX.

The string JSON:

var avaliacao= {"avaliacao":[{"pergunta":"Qual sua idade?"}[{"resposta_certa":"99","resposta_err1":"11","resposta_err2":"15",
"resposta_err3":"14","resposta_err4":"27"}]]}

The JS:

var controller = 'endereco/controller';
var base_url = 'dominio/do/site';

function grava_avaliacao(){ 

    jQuery.ajax({
        url : base_url + '/' + controller + '/add',
        type : 'POST', 
        data : avaliacao,
        dataType: 'json',
        success : function(data){ 
                        alert(data);
                    }
    });
}

The controller:

public function add(){
    var_dump(json_decode($this->input->post('avaliacao')));
}
    
asked by anonymous 11.02.2014 / 19:56

1 answer

3

Use JSON.stringify() to convert your object to a Json string in the data attribute of the ajax function.

The parameter data accepts a string or an object, but it does not automatically convert to Json and instead to the query string format. It's a common mess.

Example:

jQuery.ajax({
    url : base_url + '/' + controller + '/add',
    type : 'POST', 
    data : { 'avaliacao': JSON.stringify(avaliacao) },
    dataType: 'json',
    success : function(data){ 
                    alert(data);
                }
});

Update

According to the comments, there was a problem with the URL as well, because the driver method did not even run. So, you should always check that the URL used in Ajax commands is correct, especially when using frameworks that abstract path .

    
11.02.2014 / 20:03