Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP AJAX call

I am using CakePHP and this is my first project on this framework. I am going to send the value of an input to UsersController's check_username() action. And fill an element having id na with the string returned by check_username(). So far what I did is:

//in my form
<input type="text" name="data[User][username]" style="width: 60%" required="required" id="username" oninput="check_username(this.value)">
<label style="margin-left: 20px; color: red" id="na">Not Available!</label>

//after the form
<script type="text/javascript">
    function check_username(un) {
        $.ajax({
            type: 'POST',
            url: '/oes/users/check_username',
            data: {username:un},
            cache: false,
            dataType: 'HTML',
            beforeSend: function(){
                $('#na').html('Checking...');
            },
            success: function (html){
                $('#na').val(html);
            }
        });
    }
</script>

//and my check_username() is
public  function check_username(){
    return 'Test string';
}

But this isn't working. Anybody know why or how to modify it so that it works?

like image 421
A. K. M. Tariqul Islam Avatar asked Feb 15 '23 03:02

A. K. M. Tariqul Islam


1 Answers

It could be problem with your check_username controller action. CakePHP-way is to use JsonView class to send any data throw XHR (see http://book.cakephp.org/2.0/en/views/json-and-xml-views.html). It allows you to call any action with .json extension (ex.: /oes/users/check_username.json) and get response in serialized JSON format without manual conversion beetween array data and JSON.

This method is recommended for your needs, but not obligated, of course.

Now I think that CakePHP tries to render check_username view, but could not do this because you have not specified or created it. Try to change your action code to something like this:

public function check_username(){
     $this->autoRender = false;
     echo 'Test string';
}

Also, try not to use such code construction in the future.

like image 51
Andrew Bashtannik Avatar answered Feb 23 '23 15:02

Andrew Bashtannik