1

I tried build custom validator for jsgrid that check the item.Name is really exist from DB or not before inserting or Editing to avoid any duplicated row.

the problem I read three times the Documents of jsgrid but I didn't get any idea how to fix the problem.

this work https://github.com/tabalinas/jsgrid-php helped me too much and I transformed to be useful for my work and to mysqli.

the idea: I made function check DB if the value exist or not, if exist it return true else false in a php class

public function checkName($name){
    try{
        if(!empty($name)){
            $co_conn = $this->CON_conn->open_connect();
            $getsame = mysqli_query($co_conn,"select Name from category where Name = '$name'");
            if($getsame){
                $numit = mysqli_num_rows($getsame);
                if($numit > 0) return true;
                else return false;
            }
            else return true;
            $this->CON_conn->close_connect($co_conn);
        }
        else return true;
    }
    catch(Exception $er){
        return true;
    }
}

and I called this function in an external file "CheckValue.php"

<?php require_once '////the director of the class';
$chnow = new NameOfMyClass();
$result = true;
switch($_SERVER["REQUEST_METHOD"]) {
    case "CHGO":
        parse_str(file_get_contents("php://input"), $_CHGO);
        //to ensure if it work i tested it.
        $result = $chnow->checkName($_CHGO["Name"]);
    break;
    default:
        $result = true;
    break;
}
header('Content-type: application/json');
echo json_encode($result);
?>

in basic.html

$(function() {
    $.ajax({
        type: "GET",
        url: "../bin/update.php"
    }).done(function(response) {
        response.unshift({ ID: "0", Name: "" });
        $("#jsGrid").jsGrid({
            height: "50%",
            width: "70%",
            selecting: false,
            filtering: false,
            editing: false,
            sorting: false,
            paging: true,
            autoload: true,
            pageSize: 15,
            pageButtonCount: 5,
            controller: {
                loadData: function(filter) {
                    return $.ajax({type:"GET", url: "../bin/update.php",data:filter});
                },
                updateItem: function(item) {
                    return $.ajax({type:"PUT",url: "../bin/update.php",data: item});
                },
                insertItem: function(item) {
                    /*$.ajax({type: "CHGO",url: "..bin/Checkvalue.php",data:item.Name, dataType: "json",
                    success: function(data){
                        JSON.parse(data);
                        consol.log(data);
                        //alert(data);
                        //I used many ways to find why its not work, then I commented it
                        }
                    });
                    //return $.ajax({type: "POST",url: "../bin/update.php",data: item});
                    //return data;

                            //else sweetAlert("error", "this value is exist!", "error");
                            //here I thought merge sweetalert js will give a good look of work not the normal message.
*/
                }
            },
            fields: [
                { name: "ID", type: "number",width: 50, editing:false, inserting:false },
                { name: "Name", type: "text", width: 50, validate: ["required",{
                        message: "this value is exist",
                        validator: function(value,item){
                            if(value != "")
                            {
                                $.ajax({
                                    type: "CHGO",
                                    url: "..bin/Checkvalue.php",
                                    data: item.Name,
                                    success: function(data){
                                        if(data == true) 
                                        //I assume here return the true/false to activate the error message but nothing work..sorry
                                    }
                                });
                            }
                        }
                    } ]
                },
                { type: "control", modeSwitchButton: false, deleteButton: false }
            ]
       });
    });
    $(".config-panel input[type=checkbox]").on("click", function() {
        var $cb = $(this);
        $("#jsGrid").jsGrid("option", $cb.attr("id"), $cb.is(":checked"));
    });     
});

please help, I 'm try for 2 days to fix the problem. thanks for the developers for writing the validate js file I used jsgrid-1.4.1

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345

1 Answers1

2

The reason is that validate supports only synchronous validation, and validation from our example requires ajax call, so it's asynchronous.

You have two options:

  1. Load data to the client beforehand and validate inserting item on the client (so validation will be synchronous)
  2. Validate insertion in insertItem method. Checkout the following issue to know more details https://github.com/tabalinas/jsgrid/issues/190
tabalin
  • 2,303
  • 1
  • 15
  • 27
  • Sorry!, I tried it but didn't success; I think there is a problem in this $.ajax({type: "CHGO",url: "..bin/Checkvalue.php",data:item.Name, dataType: "json"}); I change it to POST but really nothing – Mohammed El-Shawwa Mar 30 '16 at 17:22
  • did you mean use async: false in ajax function – Mohammed El-Shawwa Mar 30 '16 at 22:41
  • No, `async: false` is deprecated. What I meant in the first option is to do something like `$.ajax({ / * request to load existing items in DB */ }).done(function(existingItems) { $("#jsGrid").jsGrid( /* config of jsGrid with validate function, which will try to find value in existingItems before insert */ ) })`. Hope it's more clear. – tabalin Mar 31 '16 at 00:02
  • I did this, I changed my work using `onItemInserting: function(args){}` still same,.... so I made little test returning value from Jquery.ajax like this: .......... onItemInserting: function(args) { if(args.item.Name != "") { var dataa = function(){ var tmp = null; $.ajax({type:"CHGO",url: "../bin/Checkvalue.php",data:({Name:args.item.Name}),success: function (data) {tmp = 123;}});return tmp;}(); if(dataa === 123){ args.cancel = true; alert("Duplicated Value");}}}, ........ what I got is (null) – Mohammed El-Shawwa Mar 31 '16 at 05:42
  • And I supposed maybe should use `done() function` and didn't success – Mohammed El-Shawwa Mar 31 '16 at 05:45
  • yes, `async: false` should help, but be aware it's deprecated http://stackoverflow.com/a/24187226/1140893 – tabalin Mar 31 '16 at 11:26
  • yes, but I used `success function` as what it wrote in jquery document [http://api.jquery.com/jquery.ajax/](http://api.jquery.com/jquery.ajax/) ....... I used `done function` without `async` and didn't success ... and I used jquer 1.11 – Mohammed El-Shawwa Apr 01 '16 at 11:02
  • is that [link](http://stackoverflow.com/questions/11448011/jquery-ajax-methods-async-option-deprecated-what-now) good ? – Mohammed El-Shawwa Apr 01 '16 at 11:29
  • finally, it returns true or false as what I want........... `onItemInserting: function(args) {if(args.item.Name != "") {$.ajax({type:"CHGO",url: "../bin/Checkvalue.php",data:({Name:args.item.Name}),}).done(function(data){if(data === true){ args.cancel = true;swal("Error, Duplicated value");} });}},` ... but however when it return `true` it still inserting (i.e. `args.cancel' not work) ... why? – Mohammed El-Shawwa Apr 01 '16 at 12:29