Cakephp ajax function not working

607 Views Asked by At

I am new to cakephp and trying to implement ajax in it. my controller photographers function api_search is:

/*resides in photographers_controller.php*/

function api_search() {
        return 'Demo';
    }

And the search.ctp is :

<script>

$(document).ready(function() {
    get_search_results();
});

function get_search_results() {
    //get the selected location_id

    var gal_location_id = 0;

    //get the selected package
    var starting_package_wedding = 1;

    var data = "gal_location_id="+gal_location_id+"&starting_package_wedding="+starting_package_wedding;

    //var url_to_call = '<?php echo $html->url(array("controller"=>"gal_providers","action"=>"api_search")); ?>';
    var url_to_call = "http://localhost/myshaadi/photographers/api_search";

    $.ajax({
        type: "GET",
        url: url_to_call,
        // async: false,
        dataType: "json",
        data: data,
        error:function(resp){

        },
        success: function(resp){
            alert('Upto here');
            //render_search_result(resp);
        }
    });
}

</script>

I was expecting an alert of Upto here, but it is not alerting anything after page loads ! Whats wrong?

2

There are 2 best solutions below

0
On

Firstly, you don't return data from your controller, you need to output it:

function api_search() {
    echo 'Demo';
}

Now, obviously that's not JSON data, but you should still receive it in your success function if you're outputting it rather than returning it. If you return that data, your AJAX request won't collect any data. Chances are that your current AJAX request is going to the error callback instead of the success, and since you haven't declared anything to do in it, it will look wrong. It's a good idea (while developing/testing) to put something simple into the error callback just so you know what's going on.

Also, it's not good practice to hard code the URL into your javascript variable like you have done. The commented out line is much better, or use something like this:

var url_to_call = "<?=BASE_URL?>/photographers/api_search";

Try this:

$.ajax({
    type: "GET",
    url: url_to_call,
    dataType: "json",
    data: data,
    error:function(resp){
        console.log('Error callback triggered:');
        console.log(resp);
    },
    success: function(resp){
        alert('Upto here');
    }
});

At least in this case you will see in your console window that you're getting an error.

0
On

the first silly mistake can be not including jquery in your head statement in layout.

The second thing is as the above answer says, you should log the resp to see the error

The third thing is you use var data = "gal_location_id="+gal_location_id+"&starting_package_wedding="+starting_package_wedding; as a data but the dataType is "json", please remove dataType:json, that way it will work.