Pregunta

I'm trying to check whether the name being typed in by the user already exists in the database or not, and am using AJAX to do so. However it's never returning true if the name actually exists in the database (I know which ones are in the DB). I just want to know if I'm doing it correctly.

This is my text field:

<input type="text" name="name" id="name"/>
                <div id='check'></div>

This is the $.post request:

<script>
$(document).ready(function() {

$('#name').keyup(function(){
    isAvailable();

});

function isAvailable()
{
    var name = $('#name').val();

    $.post("controller/check", { name: name },
        function(result)
        {
            if(result == 1)
            {
                $('#check').html('It is available.');
            }
            else
            {
                $('#check').html('It's not available.');
            }

        });
}

});

This is the function which is called in the controller:

public function check()
{
    $name = $this->input->post('name');
    return $this->model->check_title();
}

and this is the model:

function check_title()
{
    $this->db->select('name');
    $this->db->from('products');
    $this->db->where('name', $this->input->post('name'));
    $result = $this->db->get();

    $rows = $result->num_rows();
    if($rows > 0)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

I think I know what the problem is, which is that the $name in the controller is not being recognised maybe? Or that the data being passed in $.post is not correct somehow i.e. is the key supposed to be the field name in the database? Really confused and would appreciate some help, thanks.

¿Fue útil?

Solución

You'll need to actually echo the value from your controller function. The return value of a controller function isn't used.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top