I'm new to Php/Jquery Programming, and i past all this day trying figuring how to access to a JSON field from a Jquery AJAX call:
I'm using codeingniter, and in my controller the related code is:
if( $this->input->is_ajax_request())
{
$view_data['test'] = 'ajax';
echo json_encode( $view_data );
}
else
{
$view_data['test'] = 'not ajax';
$data = array(
'javascripts' => array(
'js/jquery.dataTables.js',
'js/zona/dataTable_zone.js',
'js/zona/gestisci_zone.js',
'js/jquery-ui-1.8.20.custom.min.js' ,
'js/jquery.ui.error-panel.js',
'js/jquery.validate.min.js' ,
'js/localization/messages_it.js'
),
'style_sheets' => array(
'css/south-street/jquery-ui-1.8.20.custom.css' => 'screen',
'css/jquery.dataTables.css' => 'screen'
),
'content' => $this->load->view( 'zona/gestisci_zone', $view_data, TRUE )
);
$this->load->view( $this->template, $data);
}
` In the view the related code is
<div id="id_test"> <p><?php echo $test ?> </p></div>
and in the javascript file the related AJAX code is
`$.ajax( { type:"POST",
url:this_url,
dataType: 'json',
data: post_data,
success: function(data){
console.log(data);
console.log($("id_test").empty());
$("#id_test").empty().append(data.test);
},
error: function(data){
alert("error");
);`
in this way the AJAX output is Array{"test":"ajax"}
my expected behavior is that using $("#id_test").empty().append(data.test);
the AJAX output will be just the word ajax, but it just return a blank div.
I've tried to access in many modes but i didnt figured how to accomplish this.
Maybe i'm missing something because of my lack of experience or i'm using a wrong approach.
Any advice please? :)
After a little of debug i've arrived to conclusion that is a plaintext / false JSON problem. it is returning just the text rapresentation of the array and not a json array. Now, how i can send the correct json array from controller? (i already forced mimetype to application/json with no effects)