This is a migrated thread and some comments may be shown as answers.

how to get the result (true or false) of an operation (create, update or delete) from the server

7 Answers 1203 Views
Data Source
This is a migrated thread and some comments may be shown as answers.
jiff
Top achievements
Rank 1
jiff asked on 17 Nov 2011, 03:15 PM
I've managed to get the data through the read method, as already got the otherCRUD operations. However I want to know how to get the result (true or false) of an operation (create, update or delete) coming from my PHP script on the server. Here's the code:

Kendo:

 var JsonDataSource = new kendo.data.DataSource({
                        transport: {
                            read: {
                                url: "alunos_read.php", 
                                dataType: "json"
                            },
                            create: {
                                url: "alunos_add.php", 
                                type: "POST"
                            },
                            update: {
                                url: "alunos_update.php",
                                type: "POST"

      ...

PHP:

        mysql_query("update alunos set aluno = '".$aluno."' where cod_aluno = '".$cod_aluno."'");
$result = array('result' => (mysqli_affected_rows >= 0));
           
echo json_encode($result); // I want to get this overall result and show in an alert () functionHow do I do this?

7 Answers, 1 is accepted

Sort by
0
Petyo
Telerik team
answered on 21 Nov 2011, 11:07 AM
Hi Jose,

 Upon update, the DataSource expects the result (optionally) to contain data with the same structure as the read request one. If such data is present, the models data will be updated with the new server.

However, in your case, it seems like you are trying to validate the data sent to the server - is this so? If this is the case, the proper way to do it is to return the corresponding HTTP code (422 - unprocessable entity) if error is encountered. This would in turn trigger the DataSource error event, which you can process further.

Please let me know if this helps.  

All the best,
Petyo
the Telerik team
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
0
jiff
Top achievements
Rank 1
answered on 22 Nov 2011, 03:51 PM

hi Petyo,  thanks for the reply, but I didn't understand your explanation!

Yes, I'm trying to validate the data sent to the server when I run an UPDATE operation on database. 

I'll try to be clearer. Here's the code in detail:


Kendo Script
------------------

          <script>
                $(document).ready(function() {
                    
 
                    var Item = kendo.data.Model.define({
                        id: "id_student"
                    });
                    
                    var model = null; 


      var JsonDataSource = new kendo.data.DataSource({
                        transport: {
                            read: {
                                url: "students_read.php", 
                                dataType: "JSON"
                            },
                            create: {
                                url: "students_add.php", 
                                type: "POST"
                            },
                            update: {
                                url: "students_update.php",
                                type: "POST"
                            } ,
destroy: {
                                url: "students_delete.php",
                                type: "POST"
                            }
                        },
                        schema:{
                            model: Item
                        }
                    });




                  function onChange() {
                   
    var tr = this.select();
                        var id = tr.data("id");
                        model = this.dataSource.get(id);
                   
                        $("#id").val(model.get("id_student"));         
                        $("#name").val(model.get("name"));
                                   
                    }


                 $("#grid").kendoGrid({
                        autoBind: false,
                        dataSource:JsonDataSource,
                        height: 350,
                        selectable: "row",
                        pageable: false,
                        sortable: true,
                        scrollable: true,
                        change: onChange,
                        columns: [
                                  { title : "Id", field :"id_student"},
                                  { title : "Name", field :"name"}
                                ]
                    });
                    
                    $("#btn_load").click(function() {
                        JsonDataSource.read({name: $('#search').val()});
                    });
                    
                     $("#search").keydown(function(e) {
                        if (e.keyCode === kendo.keys.ENTER) {
                            JsonDataSource.read({name: $('#search').val()});
                        }
                    });
                    
                    $("#btn_add").click(function() {
                        $('#id').val(null);
                        $('#name').val(null);
                    });
                    
                    $("#btn_save").click(function() {
                        if ($('#id').val() == ''){
                            JsonDataSource.add({ aluno: $('#name').val() });
                            JsonDataSource.sync();
                            $('#search').val($('#name').val());
                            JsonDataSource.read({name: $('#search').val()});
                        }else{
                            model.set("aluno", $('#name').val());
                            JsonDataSource.sync();
                        }
                    });
                    
                    $("#btn_delete").click(function() {
                        JsonDataSource.remove(model);
                        JsonDataSource.sync();
                    });
                
                });
            </script>


HTML tags
---------------


       <div id="example" class="k-content">
            <div>
                Search:&nbsp;&nbsp;<input id="search" name="search" />
                <button id="btn_load">Load Data</button>
            </div><br/>
            <div id="grid"></div>
            <dl>
                <dt>Student:</dt><br/>
                <dd>Id:&nbsp;&nbsp;<input id="id" name="id" readonly="readonly"/></dd><br/>
                <dd>Name:&nbsp;&nbsp;<input id="name" name="name" /></dd><br/>
                <dd><button id="btn_add">New</button>&nbsp;&nbsp;&nbsp;<button id="btn_save">Save</button>&nbsp;&nbsp;&nbsp;<button id="btn_delete">Delete</button></dd>
            </dl>
       </div>
            
PHP script (students_update.php)
--------------------------------------------
<?php


$host = "localhost";
$username = "root";
$password = "root";
$db = "school";


$id_student = $_POST["id_student"];
$name = $_POST["name"];
        
    mysql_connect($host,$username,$password);
mysql_selectdb($db);

mysql_query("UPDATE students set name = '".$name."'  WHERE id_student = '".$id_student."'");
$result = array("result" => (mysqli_affected_rows >= 0)); 

echo json_encode($result);
?>


I wonder how to implement the code(Kendo Script) above to show the result of the UPDATE operation (if there was success or failure) via an alert (). example;


if (result == true) {
  alert("Sucess Update");
}else{
  alert("Fault Update");
}


The question is: How do I do this? You could implement the code? The only thing missing to complete the example that full CRUD (Kendo + PHP) and send to the community.

0
YoungJo
Top achievements
Rank 1
answered on 04 Jan 2012, 08:33 AM
who solved this problem? 

I really need. Let me know how. 
0
Phil
Top achievements
Rank 1
answered on 06 Feb 2012, 02:40 PM
<Bump>
This is something I have been battling with as well. I need to parse the response text sent back from the PHP script (I don't want to just send back an HTTP error code thanks). I could do this via jQuery .ajax() using the success() call back method, but this is not available via the Kendo datasource object (I notice it has its own internal success method). Any way round this, or do I need to ditch the datasource CRUD methods and roll my own? Cheers.
0
Brendan
Top achievements
Rank 1
answered on 10 Feb 2012, 07:44 PM
I built on top of the recommendation Petyo posted back in November.  This flow is working for us right now, although it's a bit of a work around because of the server error 422 Kendo is looking for.  Either way, I hope it can help some of you out.

Client Side Javascript:
this.someFunction = function()
{                  
     // Bind a success function to the change event of the DS. 
     //  Using ".one()" means this will bind for one response only (jQuery stuff)
     myDataSource.one("change", myDataSource.successFunction);
 
     // Bind a error function to the error event of the DS.
     //  Using ".one()" means this will bind for one response only
     myDataSource.one("error", myDataSource.errorFunction);
 
     // Sync the datasource to execute the transaction to the server
     myDataSource.sync();
}
             
this.errorFunction = function(error)
{
      // Read the response from the 422 server error.
      //  It will be in the first element under responseText
      var jsonResponse = jQuery.parseJSON(error[0]["responseText"]);
 
      // Display the error in a alert box to show it worked
      alert("Error:" + jsonResponse.statusMessage);
}
 
this.successFunction = function(e)
{
     // No errors, alert a success....or do something practical
     alert("Hellz Yeah, No Errors!!!");
}

Server Side Java Servlet:
try
{
    // some java business logic
}       
catch (Exception e)
{
     logger.error("Failed to do something that I wanted to work.", e);
           
       // Add a status and statusMessage attribute that we can read later in our error422.jsp
     request.setAttribute("status", "FAILURE");
     request.setAttribute("statusMessage", "Failed to do my stuff.");
 
     // Adding this error response is very important
     // Kendo is looking for the 422 error to trigger the error event on the DS
     response.sendError(422);
}

Since our Java servlet is returning a 422 error, I needed to configure a custom error page in my web application to generate a JSON response that I could read within our KendoUI client listening for the error event.

web.xml entry
<web-app>
 
    ****  Normal web.xml stuff goes here ****
  
    <error-page>
        <error-code>422</error-code>
        <location>/error422.jsp</location>
    </error-page>
     
</web-app>

Now for the simple error422.jsp page that will create the JSON response for us.
<%@ page language="java" isErrorPage="true" %>
<%
    String mStatus = (String)request.getAttribute("status");
    String mStatusMessage = (String)request.getAttribute("statusMessage");
%>
{"status":"<%=mStatus%>","statusMessage":"<%=mStatusMessage%>"}

Once again, this works for us at this point.  Hopefully someone can benefit from my research...this was a tricky one to understand.

-Brendan
0
Joshua
Top achievements
Rank 1
answered on 28 Feb 2012, 11:11 PM
This works!
0
KV
Top achievements
Rank 1
answered on 24 Sep 2013, 04:00 PM
You can use the datasource requestEnd function to know the status of the response.

requestEnd: function(e) {
                    var response = e.response;
                    var type = e.type;
                    if (type == "undefined") {
                        showError();
                    }
                    else {
                        showSuccess(type);
                    }
},
Tags
Data Source
Asked by
jiff
Top achievements
Rank 1
Answers by
Petyo
Telerik team
jiff
Top achievements
Rank 1
YoungJo
Top achievements
Rank 1
Phil
Top achievements
Rank 1
Brendan
Top achievements
Rank 1
Joshua
Top achievements
Rank 1
KV
Top achievements
Rank 1
Share this question
or