4th guy
4th guy

Reputation: 79

Retrieve data using AJAX in CakePHP

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

Upvotes: 2

Views: 5768

Answers (2)

ltiong_dbl
ltiong_dbl

Reputation: 3216

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';

Upvotes: 3

jamesmortensen
jamesmortensen

Reputation: 34078

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

Upvotes: 1

Related Questions