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 );
}
This question is related to
javascript
php
codeigniter
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);
}
}
return $this->output
->set_content_type('application/json')
->set_status_header(500)
->set_output(json_encode(array(
'text' => 'Error 500',
'type' => 'danger'
)));
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)}
});
});
Source: Stackoverflow.com