views:

15

answers:

2

I'm tryin to validate an input field with an ajax call to a cakephp controller My Ajax is:

$("#UserAlphaCode").change(function () {
        $.ajax({
            type: "post",
            url: '<?php echo $this->webroot ?>' + "/alpha_users/checkCode",
            data: ({code : $(this).val()}),
            dataType: "json",
            success: function(data){
                alert (data);
            },
            error: function(data){
                alert("epic fail");
            }
        });
    });

My controller code

function checkCode() {
        Configure::write('debug', 0);
        $this->autoRender = false;
        $codePassed = $this->params['form']['code'];
        $isCodeValid = $this->find('count',array('conditions'=> array('AlphaUser.code' => $codePassed)));
        if ($isCodeValid == 0){
            $codeResponse = false;
        } else {
            $codeResponse = true;
        }
        echo json_encode ($codeResponse);   
    }

I'm pretty sure I'm using $this->params wrong here to access the data sent from the ajax request. What should I be doing instead?

+1  A: 

Try something like:

$codePassed = $_POST['code']

you might also try putting:

$this->log($codePassed,LOG_DEBUG);

somewhere in there and examine the output in tmp/logs/debug.log

Using firebug will help debug the transport.

Leo
After trying your suggestiong $codePassed = $_POST['code']I am able to return that back to the alert(data)I tested this by changing my controller output fromecho json_encode ($codeResponse); toecho json_encode ($codePassed);This worked.But when I try to return$isCodeValid I get a null response.
wcolbert
Perhaps there is something wrong with my $isCodeValid = $this->find('count',array('conditions'=> array('AlphaUser.code' => $codePassed)));
wcolbert
I checked the header content and I get nothing, but there is an error in the chrome debugger that says "Uncaught TypeError: Cannot read property 'codeResponse' of null"
wcolbert
You're in the controller, right?the line should read: $isCodeValid = $this->AlphaUser->find(...
Leo
Ugh, stupid mistake! Thanks. It's all good now! You da' man.
wcolbert
You're welcome ;)
Leo
A: 
Lèse majesté