40

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 );
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Bryan Learn
  • 1,563
  • 3
  • 15
  • 13

7 Answers7

95
return $this->output
    ->set_content_type('application/json')
    ->set_status_header(500)
    ->set_output(json_encode([
        'text' => 'Error 500',
        'type' => 'danger'
    ]));
Mr.Singh
  • 1,421
  • 6
  • 21
  • 46
Cliff Richard Anfone
  • 1,426
  • 12
  • 14
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 );
}
clami219
  • 2,958
  • 1
  • 31
  • 45
Sundar
  • 4,580
  • 6
  • 35
  • 61
  • Returned (an empty string) – Bryan Learn Sep 16 '13 at 06:33
  • Shown: {"a":1,"b":2,"c":3,"d":4,"e":5} – Bryan Learn Sep 16 '13 at 06:35
  • that's correct then you have to add full URL in that ajax url: 'http:///index.php/user/signin' then check it – Sundar Sep 16 '13 at 06:36
  • I added ../index.php/user/signin – Bryan Learn Sep 16 '13 at 06:38
  • But it is not working still. Since Domain name will change, I cannot put a static domain name there. – Bryan Learn Sep 16 '13 at 06:38
  • 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 http://api.jquery.com/submit/ – Sundar Sep 16 '13 at 06:54
  • Hi Sundar, I am using code igniter. I am not able to parse the json_encode. – Bryan Learn Sep 16 '13 at 07:30
  • http://php.net/manual/en/function.json-encode.php try here above 5.2 version this is inbuild functionalty otherwise you have to install it – Sundar Sep 16 '13 at 08:52
  • 1
    It worked . But it overrited some features such as cache in Output class. So Cliff Richard Anfone's answer is better. – mbo Feb 18 '16 at 09:27
  • 1
    `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. – Sundar Feb 18 '16 at 09:41
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);
    }
}
Player1
  • 2,878
  • 2
  • 26
  • 38
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']);
Ghazaleh Javaheri
  • 1,829
  • 19
  • 25
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)}
     });
}); 
plain jane
  • 1,009
  • 1
  • 8
  • 19
Sundar
  • 4,580
  • 6
  • 35
  • 61
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']);
cdsaenz
  • 520
  • 1
  • 10
  • 15
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

Sohan Arafat
  • 93
  • 2
  • 16