MPrinsloo
MPrinsloo

Reputation: 146

Codeigniter PHP JSON sends HTML response

I have a problem with Codeigniter and JSON. Here is my coding:

$.post("Admin/Admin/addschool", {test: 'test'}, function(data){             
  if (data.status == 'ok')
    alert(data);
  else 
    alert(data);
}, "json");

... and in my controller:

public function addschool() {
  $data = array("status" => "ok", "message"=> "something ");  
  echo json_encode($data);  
  exit(); 
}

But each time my json reply with the HTML of my whole view e.g my response

<!doctype html>

<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://localhost:10090/css/layout.css" />
<title>Administration</title>
<meta name="description" content="">
<meta name="author" content="">
</head>

Upvotes: 5

Views: 2772

Answers (3)

adib.mosharrof
adib.mosharrof

Reputation: 1634

Probably there is a problem with the url. Let me give u an example of url routing problem

Lets say, the admin controller index function loads the admin home page, so in the load method, in the url part, if u just write "addschool", the ajax call will go to addschool function.

A chaining is done automatically, admin/addschool

But say for example, the function admin/load_view loads ur view page, now if u type addschool in the url, chaining will take place, and the url will become

admin/load_view/addschool

So you have to check the codeigniter function that is loading the view page, then use the appropriate chaining

Upvotes: 1

Frederick Lasmana
Frederick Lasmana

Reputation: 21

Try use absolute URL

$.post("/Admin/Admin/addschool", {test: 'test'}, function(data){             
  if (data.status == 'ok')
    alert(data);
  else 
    alert(data);
}, "json");

And it is better return then exit inside codeigniter function

public function addschool() {
  $data = array("status" => "ok", "message"=> "something ");  
  echo json_encode($data);  
  return; 
}

Upvotes: 1

Fortran
Fortran

Reputation: 593

First, it is good practice not to you used "echo", and you use the 'return'. Try to put down the controller directly to url and see if your return json

Upvotes: 2

Related Questions