Подтвердить что ты не робот

Code Igniter - как вернуть ответ Json от контроллера

Как вернуть ответ от контроллера обратно в JQuery Javascript?

Javascript

$('.signinform').submit(function() { 
   $(this).ajaxSubmit({ 
       type : "POST",
       url: 'index.php/user/signin', // target element(s) to be updated with server response 
       cache : false,
       success : onSuccessRegistered,
       error: onFailRegistered
   });        
   return false; 
}); 

Возвращается значение null (пустое)!

function onSuccessRegistered(data){
    alert(data);
};

Контроллер -

public function signin() {
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);    
    echo json_encode( $arr );
}
4b9b3361

Ответ 1

//do the edit in your javascript

$('.signinform').submit(function() { 
   $(this).ajaxSubmit({ 
       type : "POST",
       //set the data type
       dataType:'json',
       url: 'index.php/user/signin', // target element(s) to be updated with server response 
       cache : false,
       //check this in Firefox browser
       success : function(response){ console.log(response); alert(response)},
       error: onFailRegistered
   });        
   return false; 
}); 


//controller function

public function signin() {
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);    

   //add the header here
    header('Content-Type: application/json');
    echo json_encode( $arr );
}

Ответ 2

return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode(array(
                    'text' => 'Error 500',
                    'type' => 'danger'
            )));

Ответ 3

Это не ваш ответ, и это альтернативный способ обработки отправки формы.

$('.signinform').click(function(e) { 
      e.preventDefault();
      $.ajax({
      type: "POST",
      url: 'index.php/user/signin', // target element(s) to be updated with server response 
      dataType:'json',
      success : function(response){ console.log(response); alert(response)}
     });
});