views:

206

answers:

1

Hello,

I trying to make my first AJAX with JSON call using jQuery and CodeIgniter. But for some weird reason it's not working.

The jQuery code:

var item = "COOL!";
$.post("http://192.168.8.138/index.php/main/test", { "item" : item },
         function(data){
            alert(data.result);
         }, "json");

The CodeIgniter code:

<?php
class main extends Controller {
   function test() {
      $item = trim($this->input->post('item'));
      $array = array('result' => $item);
      echo json_encode($array);
   }
}
?>

I tried to access the http://192.168.8.138/index.php/main/test page manually and it seems to be working, I got: {"result":""}

I also tried to use Firebug to see XMLHttpRequest but saw nothing.

I have no idea what am I doing wrong... Need help really badly. Thank you.

+1  A: 

You may need to set the HTTP content type to application/json to get this to work:

<?php
class main extends Controller {
   function test() {
      $item = trim($this->input->post('item'));
      $array = array('result' => $item);
      header('Content-Type: application/json',true);
      echo json_encode($array);
   }
}
?>)
Justin Ethier
Can you please show me a complete example using the `application/json` type? Thank you.
thedp
I'm sorry this all thing is quite new to me, where do I place it? The CodeIgniter or the jQuery page side? Thanks again.
thedp
Unfortunately it still doesn't work... Could there be something wrong with my CodeIgniter configuration? Maybe I need to add some libs to CI?
thedp
Is your AJAX request being made from another page on the same web server? Why are you using an absolute "path" (IE, with 192.168.8.138) instead of a relative "path" (such as index.php/main/test)?
Justin Ethier
Actually... it's not on the same server. The request it made from desktop to the vmware testing server I have.
thedp
That's likely your problem. AJAX will only work when you make requests to the same domain that your page belongs to. So... put your test page on the same server (you can temporarily just put it in the same dir as index.php) and re-test.
Justin Ethier
Like Justin said - the requesting page that has the javascript on it has to be on the same server as the CI installation - in other words, you can call (via AJAX) a view from another controller, but both the requesting page and the serving page need to be on the same server.
b. e. hollenbeck
You were right, that was the problem. Thank you!But it makes me wonder, if AJAX can only be called on it's own server, how does Twitter, Flicker, Google, etc. do it then?
thedp
One way to solve this problem is to query external those sites from your web server, instead of directly from the client.
Justin Ethier
I tried Flickr API directly from my client, how do they do it?
thedp