Jenny Jenny -4 years ago 62
Javascript Question

How to get Ajax function for onkeyup event in Codeigniter

I have 2 files in

VIEW
folder:
addcustomer.php
and
phoneError.php
.

addcustomer.php

<input type="text" id="textHint" onKeyUp="showHint(this.value)" name="phone" placeholder="1235558888">
<span id="txtHint"></span>

<script type="text/javascript" >
function showHint(str) {
var base_url = <?php echo base_url(); ?>
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};

// Get $p from phoneError.php
(xmlhttp.open("GET", "phoneError.php?p=" + str, true));
xmlhttp.send();
}
}
</script>

<input type="text" id="textHint" onKeyUp="showHint(this.value)" name="phone" placeholder="1235558888">
<span id="txtHint"></span>


phoneError.php

<?php
defined('BASEPATH') || exit('No direct script access allowed');

$p = $_REQUEST['p']; // required

$string_exp = "/^[0-9]{3}[0-9]{3}[0-9]{4}$/";


if ($p == !preg_match($string_exp, $p)) {
echo $error_message .= '<span style="color:red">Oops! The Phone you entered does not appear to be valid.</span>';
}
?>


I want to add Ajax function into
onkeyup
event in addcustomer form to check valid phone number entered. I called addcustomer method and also loaded
phoneError
in Controller but did not work. I am not sure I put correct url for
xmlhttp.open "GET"
.

Answer Source

Well if your are using Codeigniter you should know basic structure of it. So put php code in same controller file which loads your view and name it as

public function phoneError(){
    // your php code..
}

In html side

change id of span as id should be unique in same page.

Replace

<span id="txtHint"></span>

with this

<span id="txtResult"></span>

In input tag remove onKeyUp attr. So replace with this

<input type="text" id="textHint" name="phone" placeholder="1235558888"> 

And some change in js

So basically your view file is as

addCustomer.php

<input  type="text" id="textHint"  name="phone" placeholder="1235558888" value="">
        <span id="txtResult"></span>

        <script type="text/javascript" >
                $(document).ready(function () {

                    $("#textHint").keyup(function () {
                        var str = $(this).val();
                        $.get("http://localhost/sitename/controllername/phoneError?p=" + str, function (data) {
                            $("#txtResult").html(data);
                        });
                    });
                });
            </script>

Now try with this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download