locked
How to reload/refresh datatables without loading page. RRS feed

  • Question

  • User932259438 posted

    hello,

    $('#Relacije').DataTable().clear();
    $('#Relacije').DataTable().ajax.reload();
                $("#ShraniRelacijovPotniNalog").click(function () {
                    //   if (localStorage.getItem("IdVoznika") != null && localStorage.getItem("IdAvtomobil") != null && localStorage.getItem("IdOdredil") != null && ($("#datepicker").val().length != 0 && localStorage.getItem("IdNamen") != null)) {
    
                    var datumrelacije = $("#txtDatumRelacije").val();
                    var relacija = $("#RelacijeVnos").val();
                    var kilometrov = $("#kmVnos").val();
                    var kilometrina = $("#kilometrinaVnos").val();
                    var opisnamena = $("#opisNamenaVnos").val();
                    var kilometrinatujina = $('#chkKilometrinaTujina').is(':checked') ? true : false;
    
                    $.ajax({
                        type: "POST",
                        url: "anja.asmx/shraniRelacijovPotniNalog",
                        data: JSON.stringify({ username: $.cookie("user"), password: $.cookie("pass"), IdPodjetja: localStorage.getItem("IdPodjetja"), datumrelacije: datumrelacije, relacija: relacija, kilometrov: kilometrov, kilometrina: kilometrina, opisnamena: opisnamena, kilometrinatujina: kilometrinatujina, ddlVoziloValue: localStorage.getItem("IdAvtomobil"), IDNaloga:localStorage.getItem("IdNaloga") }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
    
                          //   window.location.replace("sluzbenapotovanja.html");
    
                            //var nalogst = data.d;
                            //var stevilkanaloga = nalogst.lastIndexOf(" IdNaloga: ");
                            //nalogst = nalogst.substring(0, stevilkanaloga);
    
                            //var nalogid = data.d;
                            //var result = nalogid.substr(nalogid.indexOf(" ") + 1);
                            //var resultorID = result.substr(result.indexOf(" ") + 1);
    
                            //////$("#StevilkaNaloga").html("Številka naloga: " + nalogst);
                            //////localStorage.setItem("IdNaloga", resultorID)
                            //////// $("#ZacniGPS").show();
                            //////$("#ShraniOsnovnePodatke").hide();
                            //////// $("#text").html("Osnovni podatki s številko potnega naloga: " + nalogst + " so shranjeni.</br>");
                            //////localStorage.setItem("potninalogst", nalogst);
    
                            alert("OK");
                        },
                        failure: function (msg) {
                            alert(msg.d);
                        }
                    });
                });
        /*SHRANI RELACIJO V POTNI NALOG*/
                $("#ShraniRelacijovPotniNalog").click(function () {
                    //   if (localStorage.getItem("IdVoznika") != null && localStorage.getItem("IdAvtomobil") != null && localStorage.getItem("IdOdredil") != null && ($("#datepicker").val().length != 0 && localStorage.getItem("IdNamen") != null)) {
    
                    var datumrelacije = $("#txtDatumRelacije").val();
                    var relacija = $("#RelacijeVnos").val();
                    var kilometrov = $("#kmVnos").val();
                    var kilometrina = $("#kilometrinaVnos").val();
                    var opisnamena = $("#opisNamenaVnos").val();
                    var kilometrinatujina = $('#chkKilometrinaTujina').is(':checked') ? true : false;
    
                    $.ajax({
                        type: "POST",
                        url: "otovanja.asmx/shraniRelacijovPotniNalog",
                        data: JSON.stringify({ username: $.cookie("user"), password: $.cookie("pass"), IdPodjetja: localStorage.getItem("IdPodjetja"), datumrelacije: datumrelacije, relacija: relacija, kilometrov: kilometrov, kilometrina: kilometrina, opisnamena: opisnamena, kilometrinatujina: kilometrinatujina, ddlVoziloValue: localStorage.getItem("IdAvtomobil"), IDNaloga:localStorage.getItem("IdNaloga") }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
    
                          //   window.location.replace("sluzbenapotovanja.html");
    
                            //var nalogst = data.d;
                            //var stevilkanaloga = nalogst.lastIndexOf(" IdNaloga: ");
                            //nalogst = nalogst.substring(0, stevilkanaloga);
    
                            //var nalogid = data.d;
                            //var result = nalogid.substr(nalogid.indexOf(" ") + 1);
                            //var resultorID = result.substr(result.indexOf(" ") + 1);
    
                            //////$("#StevilkaNaloga").html("Številka naloga: " + nalogst);
                            //////localStorage.setItem("IdNaloga", resultorID)
                            //////// $("#ZacniGPS").show();
                            //////$("#ShraniOsnovnePodatke").hide();
                            //////// $("#text").html("Osnovni podatki s številko potnega naloga: " + nalogst + " so shranjeni.</br>");
                            //////localStorage.setItem("potninalogst", nalogst);
    
                            alert("OK");
                        },
                        failure: function (msg) {
                            alert(msg.d);
                        }
                    });
                });
    
                /*RELACIJE*/
                $.ajax({
                    type: "POST",
                    url: "vanja.asmx/PripeteRelacijeKPotnemuNalogu",
                    data: JSON.stringify({ username: $.cookie("user"), password: $.cookie("pass"), IdPodjetja: localStorage.getItem("IdPodjetja"), IDNaloga: localStorage.getItem("IdNaloga") }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        var json = data.d;
                        $('#Relacije').DataTable({
                            "data": JSON.parse(json),
                            "columns": [
                                { "data": "ID" },
                                { "data": "Relacija" }
                            ],
                            "aoColumnDefs": [{ "bVisible": false, "aTargets": [0] }]
                        });
    
                        $('#Relacije tbody').on('click', 'tr', function () {
                            var table = $('#Relacije').DataTable();
                            if ($(this).hasClass('selected')) {
                                $(this).removeClass('selected');
                            }
                            else {
                                table.$('tr.selected').removeClass('selected');
                                $(this).addClass('selected');
                            }
                        })
                    },
                    failure: function (msg) {
                        alert(msg.d);
                    }
                });
      //Shrani relacijo v potni nalog
        [WebMethod]
        public string shraniRelacijovPotniNalog(string username, string password, int IdPodjetja, string datumrelacije, string relacija, decimal kilometrov, decimal kilometrina, string opisnamena, bool kilometrinatujina, int ddlVoziloValue, int IDNaloga)
        {
            if (Membership.ValidateUser(username, password) && IdPodjetja != null)
            {
                //Najdi osebno/službeno vozilo
                var vrstavozila = (from c in db.tbl_avtomobilis
                                   where c.ID == ddlVoziloValue
                                   select c).SingleOrDefault();
    
                //Pridobi najvišji ID
                var QueryMax = (from y in db.tbl_PotniNalogis
                                where y.Idkreiranopodjetje == IdPodjetja
                                select y.ID).Max();
    
    
                //Vozilo, ki je na leasing
                var avtomobilnaleasing = (from p in db.tbl_avtomobilis
                                          where p.ID == ddlVoziloValue
                                          select p).SingleOrDefault();
    
    
                tbl_relacije tbl_relacije = new tbl_relacije()
                {
    
                    //     UserId = UserID,
                    Idkreiranopodjetje = IdPodjetja,
                    IdSifra = QueryMax,
                    DatumRelacije = Convert.ToDateTime(datumrelacije), //txtDatum.SelectedDate.Value,
                    IDRelacija =IDNaloga, //QueryMax,
                    //  UserId = ("string test " ),
                    Relacija = relacija,
                    Kilometrov = kilometrov, //Convert.ToDecimal(txtKm.Text),
                    CenaKm = kilometrina, //Convert.ToDecimal(txtKilometrina.Text),
                    Kilometrina = (vrstavozila.TipVozila == "zasebno" || avtomobilnaleasing.Leasing == true) ? kilometrov * kilometrina : 0, //,
                    OpisNamena = opisnamena,
                    KilometrinaTujina = kilometrinatujina,
    
                };
    
                List<tbl_relacije> ie = new List<tbl_relacije>();
    
    
                ie.Add(tbl_relacije);
                db.tbl_relacijes.InsertAllOnSubmit(ie);
                db.SubmitChanges();
    
                //View relacije
                ////ViewRelacije.DataSource = (from p in db.tbl_relacijes
                ////                           where p.IDRelacija == QueryMax && p.Idkreiranopodjetje == Convert.ToInt32(Session["ID"])
                ////                           orderby p.DatumRelacije
                ////                           select p);
                ////ViewRelacije.DataBind();
    
            }
            return "OK";
        }
    
        string prikazpripetihrelacij;
        //Relacije pripete k potnemu nalogu
        [WebMethod]
        public string PripeteRelacijeKPotnemuNalogu(string username, string password, int IdPodjetja, int IDNaloga)
        {
            if (Membership.ValidateUser(username, password) && IdPodjetja != null)
            {
                //relacije
                var relacije = from p in db.tbl_relacijes
                               where p.IDRelacija == IDNaloga && p.Idkreiranopodjetje == IdPodjetja
                               orderby p.DatumRelacije
                               select new { ID=p.ID, Relacija = p.Relacija };
    
                prikazpripetihrelacij = new JavaScriptSerializer().Serialize(relacije.ToList());
    
            }
            return prikazpripetihrelacij;
        }

    I got:
    DataTables warning: table id=Relacije - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

    Maybe I need to display in different way json format? Or can you help me how to do this?

    Please help.

    Sunday, January 19, 2020 12:03 PM

All replies

  • User283571144 posted

    Hi progy85,

    According to your description, I couldn't understand your requirement clearly. I have also tried your codes on my side it works well. I could get the right json form the PripeteRelacijeKPotnemuNalogu method.

    Could you please tell me when you call the "$('#Relacije').DataTable().ajax.reload();" method? 

    If you could post more details codes and information, It will help us to reproduce your issue and find out the solution.

    Best Regards,

    Brando

    Monday, January 20, 2020 9:46 AM
  • User765422875 posted

    Unrelated to your question, but I recommend you use FirstOrDefault(). With SingleOrDefault() you can get an exception if the result set contains many records.

    Also, FirstOrDefault() is usually much faster as it iterates until it finds the element and only has to iterate the whole enumerable when it doesn't find it. In many cases, there is a high probability to find an item. SingleOrDefault needs to check if there is only one element and therefore always iterates the whole enumerable. To be precise, it iterates until it finds a second element and throws an exception.

    Monday, January 20, 2020 3:31 PM