views:

489

answers:

2

I was told that $.getJSON is the best way to send data to and from external servers. I probably wasted 7 hours of my time trying to use JQUERY's Ajax to do so just to find out that no browsers allow that type of method. I would like to send the data using the Jquery getJSON and I am using cakephp as my receiving end (i.e. My external server) Here is what i have so far.

$.getJSON("http://play.mysite.com/usersessions/store/",{ data: "Hi!"});

I don't want a callback because I dont need it. I just need to send some data to the external server. This is MVC site so usersessions is my controller, store is my action.

Below is my cakephp code. If you don't know it then that is fine. I just really need to know if I am sending the getJSON data correctly

<?php class UsersessionsController extends AppController {

var $name = 'Usersessions';
var $helpers = array('Html', 'Form','Ajax');
var $components = array('RequestHandler');


function store()
{
   Configure::write('debug', 0);
   $this->autoRender = false;

   if($this->RequestHandler->isAjax()) {
    if ($this->params['url']['data'])
    {
     $this->data['Usersession']['data'] = $this->params['url']['data'];
   $this->Usersession->Save($this->data);
   echo 'Success';
     } 
   } 
}

} ?>

Thanks you!

+1  A: 

getJSON() is for reading JSON data from the server. If you just want to send some parameters from the browser to the server, just use get() and don't use the optional callback.

From the docs:

Request the test.php page and send some additional data along (while still ignoring the return results).

 $.get("test.php", { name: "John", time: "2pm" } );

http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype

Scott Saunders
He needs to request from an external url outside the domain, thus $.ajax is not an option.
Kevin Peno
+3  A: 

JQuery provides an easy way to implement JSONP, which is a necessary "hack" to get around cross-site-scripting security policies in browsers. Specifying a callback in the query string of the request is required, along with some special formatting of the response by your server.

Your request would need to implemented in a manner like this:

$.getJSON("http://play.mysite.com/usersessions/store/?jsoncallback=?",
  { data: "Hi!"}, function(){});
Mike
Thanks alot guys. I think this is what I need. Although the $.Post sounds like what I am looking for. I think the only way to send to an external server is to use this particular technique.
numerical25
just to stress out the use of 'jsoncallback=?' appended to the external URL, it's mandatory to work. ;)
sopppas