2

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.

a7omiton
  • 1,597
  • 4
  • 34
  • 61
  • Not only do you need to echo the result, in the controller there is no need to create the $name, just call the function in the model and echo back the result that you need – John Oct 17 '13 at 21:29

1 Answers1

2

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

Sam Dufel
  • 17,560
  • 3
  • 48
  • 51
  • Hi Sam, yes I've tried that, but when I enter a value that is not in the database, I still get the message saying that title is already in the database. Is there any problem with my json object in the $.post request? – a7omiton Mar 07 '13 at 00:13
  • I'm getting a funny feeling that the argument I'm passing to the models method is not being read – a7omiton Mar 07 '13 at 00:17
  • Are you sanitizing the title value while checking duplicate? It would still work with `$this->input->post('title')` instead of `$_POST['title']`. – kidonchu Mar 07 '13 at 14:09