Janaka Dombawela
Janaka Dombawela

Reputation: 1357

ajax php form validation not working

I have written a php file and jquery to retrieve data from a database and validate on a textfield blur event to check the typed value is whether available or not. Below are my code:

On form php:

<script>
        $("#catname").blur(function() {
            $.post("./scripts/checkavailability.php", {
                nameava: $("#catname").val(),
            }, function(data) {
                alert(data);
            });

            var setr = "<?php
                         include './scripts/checkavailability.php';
                         $dbava = getfromdb("name", "tbl_category");
                         $avams = check($txtval, $dbava, "$name");
                         echo $avams;
                         ?>";
            $("#jinx").html(setr);

        });
    </script>

checkavalilability.php :

<?php

if (isset($_POST['nameava'])) {
$txtval = mysql_real_escape_string($_POST['nameava']);
}


function getfromdb($field, $table) {
$avres = mysql_query("SELECT `" . $field . "` FROM `" . $table . "`");
return $avres;
}

function check($curval, $qres, $s_field) {
while ($a_row = mysql_fetch_array($qres)) {
    $dbval = $a_row[$s_field];

    if ($curval == $dbval) {
        return "This value is taken";
        break;
    } else {
        return "This value is available";
    }
}
}

?>

Note: catname is the textfield id and jinx is the div id.

Upvotes: 0

Views: 115

Answers (1)

Reza Mamun
Reza Mamun

Reputation: 6189

I think you are trying something like this:

jQuery:

<script>
    $("#catname").blur(function() {
        $.post("./scripts/checkavailability.php", {
            nameava: $("#catname").val(),
        }, function(data) {
            alert(data);
            $("#jinx").html(data);
        });

    });
</script>

PHP:

<?php

function getfromdb($field, $table) {
    $avres = mysql_query("SELECT `" . $field . "` FROM `" . $table . "`");
    return $avres;
}

function check($curval, $qres, $s_field) {
    while ($a_row = mysql_fetch_array($qres)) {
        $dbval = $a_row[$s_field];

        if ($curval == $dbval) {
            return "This value is taken";
            //break;
        } else {
            return "This value is available";
        }
    }
}

if (isset($_POST['nameava'])) {
    $txtval = mysql_real_escape_string($_POST['nameava']);
    $dbava = getfromdb("name", "tbl_category");
    $avams = check($txtval, $dbava, "name");
    echo $avams;
}
exit();
?>

Upvotes: 2

Related Questions