0

Purchase table has two fields purchase_id which primary key and purchase_order_no which is unique key. I have a simple html form. And there is one field .i.e purchase_order_no. I want to set unique id validation for purchase_order_no field using jquery or javascript. So how do I do that?

Kedar B
  • 774
  • 5
  • 18
  • 47

2 Answers2

1

If that's about checking if unique in your database, you might want to use the jQuery $ajax method: grab the typed id, send it to your PHP file where you check/validate it, then display the result in your form in the same $ajax callback method...

Take a look at this answer...

Your HTML Form:

<form id="foo">
    <label for="bar">The Order No: </label>
    <input id="purchase_order_no" name="purchase_order_no" type="text" value="" />
    <input type="submit" value="Check Number" />
    <p id="result"></p>
</form>

Then your javascript:

$(document).ready(function(){
    $("#foo").submit(function(event) {
        $("#foo").attr("disabled","disabled"); // better to disable the submit button during the ajax call...
        $.ajax({
            url: "tester.php",
            type: "post",
            data: "number_to_test=".$("#purchase_order_no").val(),
            success: function(data) {
                if (data == 'ok')
                   $("#result").html('The Order number is valid');
                else if (data == 'no_ok')
                   $("#result").html('The Order number is not valid');
                else 
                   $("#result").html('Error in the returned value');
            },
            error:function() {
                $("#result").html('There is an error somewhere');
            }
        });
    });
});

Then in your file tester.php:

<?php
    $numberToTest = $_POST["number_to_test"];
    /* here you test what you want, check the database, whatever */
    if ($numberToTest == "123") echo "ok";
    else echo "not_ok";
?>
Community
  • 1
  • 1
JBA
  • 2,889
  • 1
  • 21
  • 38
  • I modified the answer with an example for POSTing $ajax... that should help you – JBA Feb 18 '15 at 07:08
  • What will be the query and what should I return from php function?? – Kedar B Feb 18 '15 at 07:12
  • Answer edited to add rough example... although not tested it, this should be the right way to go despite maybe some typos... – JBA Feb 18 '15 at 07:27
  • Instead of writing the codes in submit event you can do it in keyup event so that it looks easy and user friendly – Rajesh Feb 18 '15 at 07:37
  • Onkeyup would process a request on each typed char, not a very good thing... But your idea would be good for on focus losed if the field contains some text yes... – JBA Feb 18 '15 at 07:55
0

You can check the values with jQuery's unique() function: http://api.jquery.com/jquery.unique/

iavery
  • 554
  • 3
  • 9