Calling javascript function from controller codeig

2020-06-30 00:27发布

问题:

I am developing site using codeigniter.I have a form which contains add button and textbox. once the user enters the data i have to check whether it exist in database,if yes generate a dynamic textbox in the page else alert user. I have written javascript to generate dynamic textbox. My question is how to check in database??? how to call controller from javascript or to call javascript function from controller???

回答1:

This is actually so much easier than you expect.. and you will start to use this allover your developments once you see how great it is!

So first off -- we're going to use jQuery's native POST function.

Create a function inside your controller that you want to access, my suggestion is to prefix the function name with "ajax_"

So here's an example of the controller function:

function ajax_lookUpUsername(){
    $username = $this->input->post('username');
    $this->db->where('username', $username);
    $query = $this->db->get('accounts');
    if ($query->num_rows() > 0){
       echo 0;
    } else {
       echo 1;
    }
}

and here's your simple onclick javascript function:

function lookUpUsername(name){
    $.post( 
        'http://yourwebsite/controller/ajax_lookUpUsername',
         { username: name },
         function(response) {  
            if (response == 1) {
               alert('username available');
            } else {
               alert('username taken');
            }
         }  
    );
}

the second parameter { username: name } is where your post values will go, the term "username" here is the key, name is the value passed in. So this is a post key-value pair that would normally get sent with a post message.

The variable response being passed into the callback function is the echo given back by your controller. Communication made extremely easy.

The simplicity is amazing, while I only had you deal with php returning 0 or 1, you can return very advanced json objects that you can power an entire front-end program with.

For more advanced responses you can echo from your controller array's this way:

echo json_encode($array_of_data); 

and this will return to you a perfect json dataset that you can use with any object oriented approach. I use this allover, you will soon too im sure :)

Good luck man! Feel free to contact w/ any questions about expanding responses past simple 0 or 1 echos



回答2:

You can do it by making an ajax call to a php page in the server that checks if data exists in db. If you are using jquery, you can do it in an easier way, here you can find very good examples: http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

If you don't, you can do it anyway, with some more lines of code.