dallion
dallion

Reputation: 195

Codeigniter Ajax JSON return not working

I have a view inside which I have a button on which after a click I would like to retrieve some data from the controller.

This is inside the view:

    <script>
    $('.ajaxBtn').click(function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: '/ajaxController',
            data: "",
            dataType:'json',
            success : function(response){ console.log(response); alert(response)}
        });
    });
</script>

My controller looks like this:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class ajaxController extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
    }

    function index()
    {
        echo json_encode("datafromajax");
    }


}

And I have a route defined like this:

$route['ajaxControl'] = "ajaxController/index";

However I have no response data even though the response is 200.

Thanks for any help

EDIT2// Loading a JSON from for an online source works fine

EDIT// Response:

XHR Loaded (index - 200 OK - 39.48300000047311ms - 35.38KB) VM3852:3 http://davids-macbook-pro.local:5757/ajaxController/index VM3853:3 Object {startedDateTime: "2016-04-09T08:45:16.133Z", time: 39.48300000047311, request: Object, response: Object, cache: Object…}cache: Object__proto__: Object__defineGetter__: defineGetter()defineSetter: defineSetter()lookupGetter: lookupGetter()lookupSetter: lookupSetter()constructor: Object()hasOwnProperty: hasOwnProperty()isPrototypeOf: isPrototypeOf()propertyIsEnumerable: propertyIsEnumerable()toLocaleString: toLocaleString()toString: toString()valueOf: valueOf()get proto: get proto()set proto: set proto()connection: "122019"pageref: "page_7"request: ObjectbodySize: 0cookies: Array[2]headers: Array[11]headersSize: 1099httpVersion: "HTTP/1.1"method: "POST"queryString: Array[0]url: "http://davids-macbook-pro.local:5757/ajaxController/index"proto: Objectresponse: Object_transferSize: 35380bodySize: 34973content: Objectcookies: Array[0]headers: Array[10]headersSize: 407httpVersion: "HTTP/1.1"redirectURL: ""status: 200statusText: "OK"proto: ObjectstartedDateTime: "2016-04-09T08:45:16.133Z"time: 39.48300000047311timings: Object__proto__: Object

Upvotes: 0

Views: 1191

Answers (2)

Vivek Mishra
Vivek Mishra

Reputation: 5705

You need to define base_url()

eg.

$arr = array("str"=>"datafromajax");
echo json_encode($arr);

And in the ajax function

url: <?php echo base_url();?> +'ajaxController'

 success : function(response){ console.log(response.str); alert(response.str)}

Upvotes: 0

Abu Sayem
Abu Sayem

Reputation: 1290

Chnage the string to array in json_encode()

From echo json_encode("datafromajax"); To echo json_encode(['data'=>"datafromajax"]);

Upvotes: 0

Related Questions