How to return JSON response from controller
Asked Answered
A

8

42

How do I return response from the controller back to the 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; 
}); 

Data is returned null (blank)!

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

Controller -

public function signin() {
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);    
    echo json_encode( $arr );
}
Agrobiology answered 16/9, 2013 at 6:18 Comment(3)
verify have you call the particular method.. The call is reached signin methodHanseatic
Yes, the call has reached sign inAgrobiology
success : function(response){ console.log(response)} modify this line and add the header //add the header here header('Content-Type: application/json')Hanseatic
H
53
//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 );
}
Hanseatic answered 16/9, 2013 at 6:30 Comment(10)
Returned (an empty string)Agrobiology
Shown: {"a":1,"b":2,"c":3,"d":4,"e":5}Agrobiology
that's correct then you have to add full URL in that ajax url: 'http://<domain>/index.php/user/signin' then check itHanseatic
I added ../index.php/user/signinAgrobiology
But it is not working still. Since Domain name will change, I cannot put a static domain name there.Agrobiology
Submit is an function so it's trying to send the form details into your form action URL. I think your action URL is empty so it's does the self post instead of ajax submit. Add the Action URL in from tag and you can try api.jquery.com/submitHanseatic
Hi Sundar, I am using code igniter. I am not able to parse the json_encode.Agrobiology
php.net/manual/en/function.json-encode.php try here above 5.2 version this is inbuild functionalty otherwise you have to install itHanseatic
It worked . But it overrited some features such as cache in Output class. So Cliff Richard Anfone's answer is better.Grew
set_status_header is not always to be 500. My response return the status code as 200 is for success. Cliff Richard Anfone explains about how to return internal server error response.Hanseatic
S
96
return $this->output
    ->set_content_type('application/json')
    ->set_status_header(500)
    ->set_output(json_encode([
        'text' => 'Error 500',
        'type' => 'danger'
    ]));
Shortfall answered 27/2, 2015 at 10:2 Comment(6)
Why is the "type" value "danger"?Bricole
@VictorS that is your response data, basicly anything you wantMelisa
Working great with 'type' => 'danger' thank you for that tip!Cauldron
Please, for Codeigniter 4 use something like: return $this->response->setJSON( array( 'text' => 'Error 500', 'type' => 'danger' ) );Hirza
This answer is missing its educational explanation.Welcy
Sorry for the late reaction but I found this as helper for me return $this->response->setStatusCode(500)->setJSON(['text' => 'Error 500', 'type' => 'danger'] ); when using CI4Levona
H
53
//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 );
}
Hanseatic answered 16/9, 2013 at 6:30 Comment(10)
Returned (an empty string)Agrobiology
Shown: {"a":1,"b":2,"c":3,"d":4,"e":5}Agrobiology
that's correct then you have to add full URL in that ajax url: 'http://<domain>/index.php/user/signin' then check itHanseatic
I added ../index.php/user/signinAgrobiology
But it is not working still. Since Domain name will change, I cannot put a static domain name there.Agrobiology
Submit is an function so it's trying to send the form details into your form action URL. I think your action URL is empty so it's does the self post instead of ajax submit. Add the Action URL in from tag and you can try api.jquery.com/submitHanseatic
Hi Sundar, I am using code igniter. I am not able to parse the json_encode.Agrobiology
php.net/manual/en/function.json-encode.php try here above 5.2 version this is inbuild functionalty otherwise you have to install itHanseatic
It worked . But it overrited some features such as cache in Output class. So Cliff Richard Anfone's answer is better.Grew
set_status_header is not always to be 500. My response return the status code as 200 is for success. Cliff Richard Anfone explains about how to return internal server error response.Hanseatic
J
6

For CodeIgniter 4, you can use the built-in API Response Trait

Here's sample code for reference:

<?php namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class Home extends BaseController
{
    use ResponseTrait;

    public function index()
    {
        $data = [
            'data' => 'value1',
            'data2' => 'value2',
        ];

        return $this->respond($data);
    }
}
Joachim answered 7/10, 2020 at 19:19 Comment(0)
B
5

in my case , I'm using ci4 , I send response to clinet like this: e.g in App\Controllers\Category:setOrder my Category controller extends BaseController

  return $this->response->setJson(['msg'=>'update-success']);
Bigmouth answered 10/7, 2021 at 6:42 Comment(0)
H
0

This is not your answer and this is an alternate way to process the form submission

$('.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)}
     });
}); 
Hanseatic answered 16/9, 2013 at 6:53 Comment(1)
This secondary (non-resolving) advice should have been a comment under the question.Welcy
D
0

In Codeigniter 4.3, I've used this within a before Filter, that doesn't have a $this->response as Controllers do:

return response()->setContentType('application/json')                             
                 ->setStatusCode(401)
                 ->setJSON(['error' => 'Access Denied']);
Diaphysis answered 7/3, 2023 at 17:12 Comment(0)
T
0

If anyone is looking for a 4.3.x version solution it is this:

return $this->response->setJSON($data);

Source: https://codeigniter4.github.io/userguide/outgoing/response.html#setting-the-output

Teets answered 24/3, 2023 at 2:10 Comment(0)
P
0

For codeigniter 3+ use this to return output as json. Put this code in controller.

return $this->output->set_output(json_encode($data));

For codeigniter 4+ you can use this.

return $this->respond(json_encode($data), 200);

Hope this help

Poverty answered 12/6 at 4:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.