Convert CI_Model to JSON and then Send to AJAX - php

How to convert an object to JSON using json_encode and then send this JSON to AJAX as response?
CI_Model :
<?php
class TResponse extends CI_Model
{
private $status;
private $topics;
public function __construct()
{
parent::__construct();
}
}
Inside Controller :
$response = new Model\TResponse ();
$response->status = true;
echo json_encode($response);
AJAX :
$('#myform').on('submit', function (e)
{
e.preventDefault(); // prevent page reload
$.ajax ({
type : 'POST', // hide URL
url : 'My_Controller/exec', // form validation file
data : $('#myform').serialize (),
dataType: 'json',
success : function (data)
{
console.log("ok");
}
, error: function(xhr, status, error)
{
console.log(status+" "+error+" "+xhr)
}
});
PROBLEM :
When i execute that code result error. the error is "error Internal Server Error [Object object]". How to solve my problem?

I don't understand why you're using $response = new Model\TResponse();. It not "the codeigniter way" to load a model. But I think it must be related to the problem because the code belows works perfectly for me.
Notice I have made both class properties public. Private properties are not exposed and so would not be "presented" to json_encode().
class TResponse extends CI_Model
{
public $status = FALSE;
public $topics = ['php', 'stackoverflow', 'json'];
public function __construct()
{
parent::__construct();
}
}
In the controller
$this->load->model('TResponse');
$this->TResponse->status = TRUE;
echo json_encode($this->TResponse);
Your javascript is fine as is.
If I use this
success: function (data) {
console.log(data);
}
This is what the console reports
Object
status: true
topics: Array[3]
0: "php"
1: "stackoverflow"
2: "json"
length: 3

Controller
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode( $response ));
in the view
$.ajax({
type: "POST",
url: "<?php echo base_url('path/to_your_controller/function')?>",
data: {some_data: val},
success: function (data) {
var options = '';
$.each(data, function (key, value) {
// read data , each element of the JSON object
});
}
});

Related

how to update an object, instantiate in the constructor, after an ajax call?

I just want to know if it is possible to instantiate an object (or a service) in a constructor controller and update this object with differents ajax call.
First, the injection in my controller works fine, I already try to do that with session or cookie, but in reality myObj is more complex than one number to increment, so it doesn't seem to be what I need.
class MyController extends Controller
{
private $myObj;
public function __construct(MyObj $myObj)
{
$this->myObj = $myObj;
}
public function indexAction(Request $request)
{
$aData['pageTitle'] = 'exemple';
$aData['pageSubtitle'] = 'on stackoverflow';
return $this->render('Bundle:page.html.twig', $aData);
}
public function ajaxAction(Request $request){
$this->myObj->increment_nbDomain();
return new JsonResponse('ok');
}
}
My object
class myObj
{
public $nbDomain = 0;
public function increment_nbDomain(){
$this->nbDomain++;
}
}
The jQuery function
$('.buttonPlus').on('click', function () {
$.ajax({
url: '{{ path('route_to_ajaxAction') }}',
type: "POST",
dataType: "json",
async: true,
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
});
nbDomain is always equal to zero

Can't call a custom method on a controller from AJAX

I am trying to call a controller function from an AJAX call. The view loads from the same controller, but I'm not able to call the function.
Here is the controller code:
// This function will get ajax call where pass two variables and a method name doSomeAction
class Posts extends \Core\Controller
{
public function addNewAction()
{
View::renderTemplate('Posts/addnew.html', [
// 'posts' => $posts
]);
}
public function doSomeAction()
{
echo "here";
// your action code ....
}
}
Here is my Ajax script call function
<script>
$(".submitcontr").click(function() {
$.ajax({
url: 'POST/doSomeAction',
dataType: 'json',
data: {
id: 'value'
},
success: function (data) {
console.log(data);
},
error: function () {
alert('error');
}
});
});
</script>

CakePHP - How to pass url with ajax?

I'm using cakePHP 3.0 and I have a problem while using ajax. Indeed, I would like to execute the action "viewTab" of my controller "SpecimensController" on an array coming from my view "specimen"
<script type="text/javascript" >
var tab = new Array();
function updateResult(){
$.ajax({
type:"POST",
url:"<?php echo Router::url(array('controller'=>'specimens','action'=>'index'));?>",
data:{datas: $("select[name='filtreVariable\\[\\]']").map(function(){return $(this).val();}).get()},
dataType: 'text',
async:false,
success: function(data){
alert('success');
},
error: function (data) {
alert("error");
}
});
}
$("#filtre").submit(function(){
updateResult();
});
</script>
The action "viewTab" is just doing:
echo "success";
But I can't find the right url so the function success can be called. I tried many things and I always have the function error of ajax that is called. :/
If you haven't yet, place this line of code in your AppController where your initialize function is:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
In your controller for the function you're calling via ajax, try something like this:
public function index()
{
$data = ['testing'];
$this->set(compact('data'));
$this->set('_serialize', 'data');
}
http://book.cakephp.org/3.0/en/controllers/components/request-handling.html

prestashop ajax controller call

I am trying to call controller in module using Ajax in prestashop 1.5, and I'm having hard time doing this.
I've created controller in module under the path:
$refresh_url = ($this->_path)."front/blockdiscoversellers.php";
and made instructions for button in js like:
var refresh = {
call: function() {
var $refresh = $("#manufacturer-refresh");
$refresh.click(function(e) {
refresh.ajax();
e.preventDefault();
});
},
ajax: function() {
var url = $("#manufacturer-refresh").data("url");
$.ajax({
url: url,
type: 'get',
data: {
controller : 'BlockDiscoverSellers',
ajax : true
},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
};
and the body of controller looks like :
class BlockDiscoverSellers {
public function __construct()
{
die(var_dump($this->refreshManufacturers()));
}
public function refreshManufacturers()
{
$result = array("test" => "TESTER");
return Tools::jsonEncode($result);
}
}
I'm getting success in Ajax call but it looks like class and constructor are not initiated, so I am quite stuck with this problem.
It appears that prestashop when you use ajax call uses only structural type of programming. That means in ajax call there can be no class of any sort bootstrap will never initiate it even with controller parameter, and you have to die at the end of file ...

WordPress ajax function in child class

If i have this classes
class something {
public function __construct() {
add_action('wp_ajax_ajax_func', array( $this, 'ajax_func' ) );
}
public function ajax_func() {
}
}
class stchild extends something {
public function __construct() {
}
public function ajax_func() {
echo "Test child1";
}
}
How to call only ajax_func function in stchild class by ajax ?
when i try this code
jQuery.ajax({
url: 'admin-ajax.php',
data: {action : 'ajax_func'},
success: function(data){
console.log(data);
}
});
it get all functions which called ajax_func, I want to define specific class to get this function from it.
Note that there is many child classes from something class and all are activated.
You could wrap it inside an action function.
add_action( 'wp_ajax_do_something', 'my_do_something_callback' );
function my_do_something_callback() {
$object = new stchild;
$object->ajax_func();
die();
}
JS:
jQuery.ajax({
url: ajaxurl, // Use this pre-defined variable,
// instead of explicitly passing 'admin-ajax.php',
data: { action : 'do_something' },
success: function(data){
console.log(data);
}
});

Categories