2

I am trying to retrieve some data using a combination of jQuery and CakePHP.

I have a feed() method that sends the data back from the database JSON-encoded. The method works fine when I visit the URL using the browser.

function feed($id = null) {
    $this->layout = 'ajax';
    $data = array(
        'test' => true
    );
    echo (json_encode($data));
}

I also have a method that should retrieve the data, but for some reason it isn't.

var address = '/person_availabilities/feed/1';

// JavaScript Document

$(document).ready(function() {
    var events = doAJAXcall(address);
    alert(events)
}


function doAJAXcall(url) {
    $.ajax({
        type : 'POST',
        url : url,
        dataType : 'json',
        data: {
        },
        success : function(data){
            return data;
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            //$('#login_error').show();
        }
    });
}

I suspect that the URL may be wrong, as xdebug does not pick the request up.

Does anyone have any suggestions for me? I've been looking for over four hours now.

EDIT: this is the address of the page localhost/Testing/person_availabilities/feed

4th guy
  • 79
  • 2
  • 9
  • what url are you using in your browser when you browser to it? Does browsing the url "http://localhost/person_availabilities/feed/1" return anything? – ltiong_sh May 06 '12 at 17:55

2 Answers2

3

If you're able to view it using your browser you're using a GET request:

Try:

$.getJSON(url, function(data){
   alert(data);
});

EDIT (additional Information):

Not sure if you're still having issue; but it sounds like you were using the wrong url (missing the Controller portion) in your ajax call per your example:

var address = '/person_availabilities/feed/1';

instead of:

var address = '/Testing/person_availabilities/feed/1';
ltiong_sh
  • 3,186
  • 25
  • 28
  • It doesn't work unfortunately. (updating post with the url I'm using) – 4th guy May 06 '12 at 17:48
  • Does it work if you just simply change POST to GET in your already-existing AJAX request? What about if you remove the `data: {},` and the `dataType: 'json'`? Also, why not try uncommenting your error message so that you can see if there is a problem? Also, what does your debugger or NET tab say when you make the request via AJAX? – jamesmortensen May 06 '12 at 17:53
  • I got something using this url http://localhost/Testing/person_availabilities/feed Thank you for your input. I just need to make sure that this works as intended now. – 4th guy May 06 '12 at 17:57
  • is that the same url you're passing into the getJSON call? – ltiong_sh May 06 '12 at 17:58
  • `var address = '/person_availabilities/feed/1';` No, it isn't. Try putting "Testing" in front of that so you have `var address = '/Testing/person_availabilities/feed/1';`. – jamesmortensen May 06 '12 at 18:04
  • @itong - You should edit your answer to include the things you and the op tried that helped! What you put as an answer didn't solve the problem, but you did contribute in other ways that helped lead to a solution. You could document those things to make your answer more correct ;) Specifically, you brought up the issue with the URL! Good luck! – jamesmortensen May 06 '12 at 18:34
  • @jmort253 sure, thanks. Still not sure if '4th Guy' has his stuff working yet. – ltiong_sh May 06 '12 at 19:08
  • jmort253 is right, thanks again for bringing it to my attention ltiong_sh. I can't vote you up because I have less than 15 reputation. – 4th guy May 07 '12 at 14:43
1

There are two problems that I see with your AJAX request. The first one requires an understanding that AJAX requests are by their very nature asynchronous; hence, the acronym AJAX stands for Asynchronous JavaScript and XML. The asynchronous component is the key thing one must understand.

You have a function where you are sending an AJAX request to the server, but in your success callback function, you are making an attempt to return a value. You cannot do this, because the function actually returns long before the success callback is fired.

function doAJAXcall(url, callback) {
    $.ajax({
        type : 'GET',
        url : url,
        success : function(data){
            // return data; // you cannot return data here
            alert(data);  // should print [ Object ]
            try {
                alert(JSON.stringify(data));  // should print JSON, assuming you're getting JSON
            } catch(e) {
                alert("Error trying to parse JSON. Is your server returning JSON? " + e.message);
            }
            if(callback) callback(data);  // fire a callback function to process the data            
        },
        error : function(XMLHttpRequest, textStatus, errorThrown) {
            //$('#login_error').show();
            alert("error :: " + textStatus + " : " + errorThrown);
        }
    });
}

In the above code, I first created an alert so you can see if any errors are thrown. Second, I added a callback function that will fire after success is called, so that you can then process the data.

Lastly, you will need to make sure that the URL that you are using is correct. You can use the NET tab of the Chrome or Firebug debugger to see if the request is being sent to the server when the AJAX request fires. Look for 500 errors or 404 errors or something that tells you the request was not successful. If so, check the URL to be sure that it is the same one you are using when making the GET request from your web browser's address bar.

What is a callback function?

This is a function that you pass into another function as a parameter. You can then call that function and ensure it's dynamic, meaning that you can change the behavior of your function by simply passing in different functions as a callback.

In your case:

doAJAXcall(url, function() { alert("I am a callback"); });

Would cause this alert to be fired in your success callback, after the alerts. Functions in JavaScript are known as "first-class objects", meaning they can be passed in by reference as parameters to another function!

For more information on callback functions, see this link:

https://stackoverflow.com/a/3616266/552792

Community
  • 1
  • 1
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
  • The first alert works. The second alert also works. (I'm not sure what a callback is, I'm looking into it) – 4th guy May 06 '12 at 18:23
  • This is what I needed to do. Thanks. I didn't know what callback was. This video helped me out http://www.youtube.com/watch?v=VI9LI4DiJ8E – 4th guy May 07 '12 at 14:44