Nic
Nic

Reputation: 27

Check mysql DB on input using JS

&I have a qty field for goods receiving. I want to check the receipts table against the orders table and make sure that value being entered does not exceed the total order value. I have this code in my field:

<div class="pure-control-group">       
    <label for="rec_qty">Qty Received:</label>
    <input type="text" name="rec_qty" id="rec_qty" onChange="receiptTotal()"></input>
</div>

Javascript Code:

function receiptTotal(){
    $.ajax({
        type: "GET",
        url: "receipts.php?do=checkrec&id="+row.pur_ID,
        //dataType: 'json', 
        success : function(data) { 
            // Here I want to do the comparisons of the two fields.
            // If data.rec_qty + form.rec_qty > pur_qty then throw error.
        }
    }); 
}

Finally PHP Code:

if($_GET['do'] == "checkrec") {
    $rec = [];
    //First get the receipts total for this ID
    $getRows = $db->query(sprintf("SELECT sum(rec_qty) as total_qty, pr.pur_qty from receipts inner join purchases pr on rec_purID = pr.pur_ID WHERE rec_purID = '$groupid' GROUP BY pur_ID")) or SQLError();
    while($rec = $getRows->fetch_assoc()) {
        $result[] = $rec;
    }
    echo json_encode($result);
 }

I am a complete novice just incase anyone was wondering. I would really appreciate the help!

Upvotes: 0

Views: 766

Answers (1)

Kylie
Kylie

Reputation: 11749

At first I thought you were asking how to do it in your database, but now I see you are already getting the data from your server and returning it. So I'll answer now, hopefully its what you meant.

function receiptTotal(){
  $.ajax({
    type: "GET",
    url: "receipts.php?do=checkrec&id="+row.pur_ID,
    //dataType: 'json', 
    success : function(data) { 
        var rec_qty = $('#rec_qty').val();
        if((data.rec_qty+rec_qty) > data.pur_qty){
           alert('Value is too high!!'); // or whatever error you want
        }
    }
  }); 
}

I will say this though.....you are basically firing a server request along with a database request, every time the field changes. Which is extremely inefficient. You should just load the data once, and then refer to it locally for the check. But I'll let you figure that out on your own :)

Upvotes: 1

Related Questions