locked
Issue with Search Record functionality is not working? RRS feed

  • Question

  • User1421057020 posted

    I m a student and I m working with ajax.

    I want to search the record but my ajax call logic is wrong??

    I fetch the record from the database using ajax successfully but search functionality using ajax but I think my ajax call is wrong?

    Database field:

    table name: tblstud

    studid int pk auto increment,

    studname varchar(50),

    studaddress varchar(50),

    procedure for getdatalist:

    ALTER PROCEDURE [dbo].[selectstud]

    AS
    BEGIN
    select * from tblstud;
    END

    Emploee.aspx

    <body>
            <form id="form1" runat="server">
            <div>
                <table>
                    <tr>
                        <td>StudentName:</td>
                        <td>
                            <asp:TextBox ID="txtname" runat="server"></asp:TextBox></td>
                    </tr>
    
                    <tr>
                        <td>StudentAddress:</td>
                        <td>
                            <asp:TextBox ID="txtaddress" runat="server"></asp:TextBox></td>
                    </tr>
    
                    <tr>
                        <td>
                            <input type="button" id="btnsave" value="Submit" onclick="saverecord()" /></td>
                    </tr>
                    <tr>
                        <td>
                            Search Record:   <asp:TextBox ID="txtsearch" runat="server"></asp:TextBox>
                                             <input id="btnsearch" type="button" value="Search" onclick="searchrecord()" />
                        </td>
                    </tr>
                    
                </table>
            </div>
    
            <div class="row">
                <div>
                    <table id="tbl" border="1">
                        <thead>
                            <tr>
                                <th>StudentName</th>
                                <th>StudentAddress</th"><br /><br />
                                <th>Edit</th>
                            </tr>
                        </thead>
                    </table>
                </div>
            </div>
    
            <script type="text/javascript">
    
                $(document).ready(function () {
                    GetData();
                });
    
                function searchrecord(studname) {                       //here is an problem with search record??
    
                    if ($("#btnsearch").val() == "Search") {
                        debugger
                        $.ajax({
                            type: "POST",
                            url: "Emploee.aspx/search",
                            data: "{ studname:'" + $("#txtsearch").val() + "' }",
                            contentType: "application/json",
                            success: function (data) {
                                debugger
                                $("#txtsearch").val(data.d);
                            },
                        });
                    }
                }
    
                //for getdatalist
                function GetData() {
                    $.ajax({
    
                        url: 'Emploee.aspx/GetData',
                        type: 'post',
                        contentType: 'application/json;charset=utf-8',
                        datatype: 'json',
                        success: function (data) {
                            data = JSON.parse(data.d);
                            $.each(data, function (index, element) {
                                $("#tbl").append('<td>' + element.studname + '</td>');
                                $("#tbl").append('<td>' + element.studaddress + '</td>');
                            });
                        },
                        error: function (error) {
                            alert('Not Get Data')
                        },
                    });
                }
    
     </script>
    
     </form>
    
    </body>

    Emploee.aspx.cs

            [WebMethod] //for retrieve the data
            
            public static string GetData()
            {
                cn.Open();
                string data = "";
                SqlCommand cmd = new SqlCommand("selectstud", cn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
    
                if (ds.Tables[0].Rows.Count > 0)
                {
                    data = JsonConvert.SerializeObject(ds.Tables[0]);
                }
                cn.Close();
    
                return data;
    
            }
    
            [WebMethod]
            public static void search(string studname)              
            {
                cn.Open();
    
                SqlCommand cmd = new SqlCommand("SELECT studname FROM tblstud WHERE studname LIKE '%'+@studname+'%'", cn);
    
                cmd.Parameters.AddWithValue("@studname", studname);
    
                SqlDataReader reader = cmd.ExecuteReader();
    
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        Console.WriteLine("{1}",reader.GetString(1));
                    }
                }
                else
                {
                    Console.WriteLine("No rows found.");
                }
    
                reader.Close();
            }

    see my browser log which place I m going to wrong?

    which place I m not correct?plz, help?

    Monday, February 10, 2020 6:16 PM

Answers

  • User1535942433 posted

    Hi raju bhai,

    Accroding to your description,I guess you want to alert message when the search record don't exist in the database.

    I suggest you needn't create a field of flag.You could set data to be null when the record is false.And you could check the data,if the data is null,you will alert message.

    More details,you could refer to below codes:

    ASPX:

     function searchrecord() {
                $('#btnsearch').click(function () {
                    $.ajax({
                        url: "2164021.aspx/search",
                        type: 'POST',
                        contentType: 'application/json;charset=utf-8',
                        datatype: 'json',
                        data: "{ studname:'" + $("#txtsearch").val() + "' }",
                        success: function (data) {
                            if (data.d == "") {
                                alert("it is not proper record");
                            }
                            else
                            {
                             txt = "<tr><td>" + data.d + "</td></tr>";
                                $("#tbl").append(txt);
                            }
                        },
                    });
                });
            }

    Code-behind:

    [WebMethod]
            public static string search(string studname)
            {
                string str = System.Configuration.ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
                SqlConnection cn = new SqlConnection(str);
                string data = "";
                SqlConnection con = new SqlConnection(str);
                SqlCommand cmd = new SqlCommand("SELECT studname FROM tblstud2 WHERE studname LIKE @studname", con);
                con.Open();
                cmd.Parameters.AddWithValue("@studname", "%" + studname + "%");
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        data = reader[0].ToString();
                    }
                }
                else
                {
                    data = "";
                }
                reader.Close();
                return data;
            }

    Result:

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 14, 2020 7:47 AM

All replies

  • User1535942433 posted

    Hi raju bhai,

    Accroding to your description and codes,as far as  I think,you needn't add the parameter.You could get the data in success function.Besides,you should retrun data in the search method.

    More details,you could refer to below article:

    https://stackoverflow.com/questions/19901843/display-json-data-in-html-table

    Best regards,

    Yijing Sun

    Tuesday, February 11, 2020 6:39 AM
  • User1421057020 posted

    can u help more?

    WebForm1.aspx

            function searchrecord() {
    
                    $('#btnsearch').click(function () {
    
                        $.ajax({
                            url: "WebForm1.aspx/search",
                            type: 'post',
                            contentType: 'application/json;charset=utf-8',
                            datatype: 'json',
                            data: "{ studname:'" + $("#txtsearch").val() + "' }",
                            success: function (data) {
    
                                data = JSON.parse(data.d);
                                var len = data.length;
                                var txt = "";
                                if (len > 0) {
                                    for (var i = 0; i < len; i++) {
    
                                        txt = "<tr><td>" + data[i].studname + "</td></tr>";
                                        $("#tbl").append(txt);
                                    }
                                }
                            },
                        });
                    }); 
                }

    WebForm1.aspx

            [WebMethod] //search the data
            public static string search(string studname)
            {
                string data = "";
                SqlConnection con = new SqlConnection(cn);
    
                SqlCommand cmd = new SqlCommand("SELECT studname FROM tblstud WHERE studname LIKE @studname", con);
    
                con.Open();
    
                cmd.Parameters.AddWithValue("@studname", "%" + studname + "%");
    
                SqlDataReader reader = cmd.ExecuteReader(); 
    
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        studname = reader[0].ToString();               
                    }
                }
                else
                {
                    Console.WriteLine("No rows found.");
                }
    
                reader.Close();
                data = studname;
                return data;
            }

    my search method retun the search recorcd console log:

    • Headers : Status Code: 200 RequestPayload { studname:'suraj' }
    • preview: {d: "suraj"} d: "suraj"
    • Response : {"d":"suraj"}

    console error:

    Uncaught SyntaxError: Unexpected token s in JSON at position 0 at JSON.parse ()

    when I search the record then search record not display?

    Image:

    search record did not display when I search the record? 

    I m very near to solve my question?help

    Tuesday, February 11, 2020 4:09 PM
  • User1535942433 posted

    Hi raju bhai,

    Accroding to your description and codes,I suggest your could get data.d directly.The data of your codes in the behind value is studname and display in the table.

    Besides,I suggest you could display all filed intead of only studname.

    More details,you could refer to below codes:

    function searchrecord() {
                 $('#btnsearch').click(function () {
                        $.ajax({
                            url: "2164021.aspx/search",
                            type: 'POST',
                            contentType: 'application/json;charset=utf-8',
                            datatype: 'json',
                            data: "{ studname:'" + $("#txtsearch").val() + "' }",
                            success: function (data) {                 
                                 txt = "<tr><td>" + data.d + "</td></tr>";
                                        $("#tbl").append(txt);
                            },
                        });
                    }); 
             }

    Result:

    Best regards,

    Yijing Sun

    Wednesday, February 12, 2020 9:38 AM
  • User1421057020 posted

    thanks for the help but the issue not solved.

    when I search true record then get the true record and when I search false record then get the false record means whatever I search then get the record. I want the when the user searches true record then gets the true record and when the user searches a false record then display the alert message(enter proper) box?

    see I add the one filed in the table:

    Emploee.aspx

           $('#btnsearch').click(function () {
    
                        $.ajax({
                            url: "Emploee.aspx/search",
                            type: 'post',
                            contentType: 'application/json;charset=utf-8',
                            datatype: 'json',
                            data: "{ studname:'" + $("#txtsearch").val() + "' }",
                            success: function (data) {
    
    //i don't know my logic is write or wrong? if (data == "#txtsearch") //if(search record is true then going inside) //here i write txtsearch is valid or not? { flag = true; txt = "" + data.d + ""; $("#tbl").append(txt); alert("it is proper record"); } else if (data.studname != "#txtsearch") //elseif(search record not found then going inside) { flag = false; alert("it is not proper record"); } }, });

    Emploee.aspx.cs

            [WebMethod] //search the data
            public static string search(string studname)
            {
    
                string data = "";
                SqlConnection con = new SqlConnection(@"Data Source=DEVISSHAHID;Initial Catalog=JqueryCrud;User ID=sa;Password=s123");
    
    //here add the flag variable SqlCommand cmd = new SqlCommand("SELECT studname FROM tblstud WHERE studname LIKE @studname and active=@flagTrueOrFalse ", con); con.Open(); cmd.Parameters.AddWithValue("@studname", "%" + studname + "%"); SqlDataReader reader = cmd.ExecuteReader(); if (reader.HasRows) { while (reader.Read()) { studname = reader[0].ToString(); } } else { Console.WriteLine("No rows found."); } reader.Close(); data = studname; return data; }

    help?

    Thursday, February 13, 2020 3:14 PM
  • User1535942433 posted

    Hi raju bhai,

    Accroding to your description,I guess you want to alert message when the search record don't exist in the database.

    I suggest you needn't create a field of flag.You could set data to be null when the record is false.And you could check the data,if the data is null,you will alert message.

    More details,you could refer to below codes:

    ASPX:

     function searchrecord() {
                $('#btnsearch').click(function () {
                    $.ajax({
                        url: "2164021.aspx/search",
                        type: 'POST',
                        contentType: 'application/json;charset=utf-8',
                        datatype: 'json',
                        data: "{ studname:'" + $("#txtsearch").val() + "' }",
                        success: function (data) {
                            if (data.d == "") {
                                alert("it is not proper record");
                            }
                            else
                            {
                             txt = "<tr><td>" + data.d + "</td></tr>";
                                $("#tbl").append(txt);
                            }
                        },
                    });
                });
            }

    Code-behind:

    [WebMethod]
            public static string search(string studname)
            {
                string str = System.Configuration.ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
                SqlConnection cn = new SqlConnection(str);
                string data = "";
                SqlConnection con = new SqlConnection(str);
                SqlCommand cmd = new SqlCommand("SELECT studname FROM tblstud2 WHERE studname LIKE @studname", con);
                con.Open();
                cmd.Parameters.AddWithValue("@studname", "%" + studname + "%");
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.HasRows)
                {
                    while (reader.Read())
                    {
                        data = reader[0].ToString();
                    }
                }
                else
                {
                    data = "";
                }
                reader.Close();
                return data;
            }

    Result:

    Best regards,

    Yijing Sun

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, February 14, 2020 7:47 AM
  • User1421057020 posted

    Thanks for the help I m trying this issue since last week  thanks for giving your valuable time thanks

    I m trying and trying and trying and trying and trying but issue not solved

    now the issue is solved thanks for your help.

    Friday, February 14, 2020 2:49 PM