Question

I am trying to send data over to a cakephp (mvc) website, via $.post(). below is the code

$('#testReq').click(function () {
    console.log('Button Works');
    $.post('http://play.anthonylgordon.com/usersessions/store/', { data: 'test7' }, function (data) {
        //data contains the json object retrieved.
        console.log(data.status);
    }, "json");
})

Below is the cakephp data that retrieves the data and stores it. If you know cake, great but if not it's fine. I am really trying to figure out if i am sending the 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;
           echo 'hello';
            if ($this->params['url']['data'])
            {
                $this->data['Usersession']['data'] = $this->params['url']['data'];
                $this->Usersession->Save($this->data);
                echo 'Success';
            }   
        }
    }
?>

As you can see I put 'hello' before it does any evaluating. I should be able to see that in my console but I dont. I tried this method with the get and I did see the response 'hello'. Which is leaving me to the conclusion that you can not send data CROSS domain via $.post. The only method that seems to work is getJSON() unless someone can prove me wrong.

Was it helpful?

Solution

You cannot perform ordinary cross domain ajax requests. You need to use JSONP and this works only with GET requests (that's because jquery injects a script tag to the DOM in order to perform the request and a script tag can only use GET to fetch javascript).

OTHER TIPS

If you want to be able to do requests cross-domain, you'll need to implement a HTTP proxy on your domain which would make HTTP requests on your behalf via a server side utility/library like Curl or Apache HTTPClient or something.

Edit: JSONP is a solution, but I wouldn't recommend it unless you only need to make GET requests (because that's all that works). JSONP also isn't necessarily REST-friendly, especially in your case where you need to make a POST request. If POST satisfies the semantics of your resource and how you intend to manipulate it, switching to GET just to use JSONP feels ugly to me.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top