locked
json ajax call in not firing RRS feed

  • Question

  • User81789783 posted

    i have below code but its not calling mention action method when i put break point

     [HttpPost]
            public ActionResult subscribe(string values)
            {
                DataSet  ds = new DataSet ();
                ds = ts.SelectQueryDS ("select * from [TBL_USER] where username="+"'"+   Session["user"] + "'");
    
                int id= Convert.ToInt32(ds.Tables[0].Rows[0][0]);
    
                string[] valuesdb = values.Split(',');
                for (int i = 0; i < valuesdb.Length; i++)
                {
                    valuesdb[i] = valuesdb[i].Trim();
                    ts.IUD("insert into tbl_usergroup (userid,gid)values( " + id + "," + valuesdb[i] + ")");
                }
              
                DataSet ds1 = new DataSet();
             
                ds1 = ts.SelectQueryDS("select * from [TBL_USER] where username=" + "'" + Session["user"] + "'");
    
                int id2 = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                ds1 = ts.SelectQueryDS("select *   FROM [GroupChatSignalR].[dbo].[tbl_usergroup]  as [usergroup]  inner join tbl_group grp  on [usergroup].gid = grp.gid    where [usergroup].[Userid] =" + id2);
                  return Json(ds1.Tables[0], JsonRequestBehavior.AllowGet);
             
                   
            }
     $.ajax({
                                url: '/Home/subscribe',
                                type: "POST",
                                data: { values: valueArray.toString() },
                                cache: false,
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function (data) { alert(data); },
                                failure: function (errMsg) {
                                    alert(errMsg);
                                }
                            });

    Thursday, May 23, 2019 5:39 AM

All replies

  • User475983607 posted

    You must serialize the data when using contentType: "application/json; charset=utf-8". 

    data: JSON.stringify({ values: valueArray.toString() }),

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

    erum

    i have below code but its not calling mention action method when i put break point

    Usually there is an error message in the browser console (F12).  What is the error?

    Thursday, May 23, 2019 10:41 AM
  • User81789783 posted

    here is error

    jquery-3.1.1.min.js:4 POST http://localhost:2181/Home/subscribe 500 (Internal Server Error)
    send @ jquery-3.1.1.min.js:4
    ajax @ jquery-3.1.1.min.js:4
    (anonymous) @ RegisterGroup:65
    dispatch @ jquery-3.1.1.min.js:3
    q.handle @ jquery-3.1.1.min.js:3

    Thursday, May 23, 2019 12:45 PM
  • User81789783 posted

    though by writing this lines below one,it goes to break point . but it should return back to ajax on sucess ,but its not

    data: JSON.stringify({ values: valueArray.toString() }),
    Thursday, May 23, 2019 12:59 PM
  • User475983607 posted

    here is error

    jquery-3.1.1.min.js:4 POST http://localhost:2181/Home/subscribe 500 (Internal Server Error)
    send @ jquery-3.1.1.min.js:4
    ajax @ jquery-3.1.1.min.js:4
    (anonymous) @ RegisterGroup:65
    dispatch @ jquery-3.1.1.min.js:3
    q.handle @ jquery-3.1.1.min.js:3

    Did you fix the AJAX function?

    Below is a working example.

    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    <input id="Button1" type="button" value="button" />
    <hr />
    
    
    
    @section scripts {
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
        <script>
            $('#Button1').click(function (e) {
                e.preventDefault();
                $.ajax({
                    url: '/ajax/subscribe',
                    type: "POST",
                    data: JSON.stringify( { values: "Hello, World" }),
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                    },
                    failure: function (errMsg) {
                        console.log(errMsg);
                    }
                });
            });
        </script>
    }
        public class AjaxController : Controller
        {
            // GET: Ajax
            [HttpGet]
            public ActionResult Index()
            {           
                return View();
            }
    
            [HttpPost]
            public ActionResult subscribe(string values)
            {
                string[] results = values.Split(',');
                return Json(results);
            }

    IMO, passing a comma separated list is not a good design approach.  I recommend passing standard types, an array in the case, rather than making up your own protocol.  Doing so simplifies the code base and reduces errors.

    For example...

    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    <input id="Button1" type="button" value="button" />
    <hr />
    
    
    
    @section scripts {
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script>
        <script>
            $('#Button1').click(function (e) {
    
                var myArray = [];
                myArray.push("Hello");
                myArray.push("World");
                myArray.push("Foo");
                myArray.push("Bar");
    
                e.preventDefault();
                $.ajax({
                    url: '/ajax/subscribe',
                    type: "POST",
                    data: JSON.stringify(myArray),
                    cache: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        console.log(data);
                    },
                    failure: function (errMsg) {
                        console.log(errMsg);
                    }
                });
            });
        </script>
    }
        public class AjaxController : Controller
        {
            // GET: Ajax
            [HttpGet]
            public ActionResult Index()
            {           
                return View();
            }
    
            [HttpPost]
            public ActionResult subscribe(string[] values)
            {
                return Json(values);
            }

    Run your code through the Visual Studio debugger if you are still receiving 500 errors.

    Thursday, May 23, 2019 1:07 PM
  • User475983607 posted

    though by writing this lines below one,it goes to break point . but it should return back to ajax on sucess ,but its not

    data: JSON.stringify({ values: valueArray.toString() }),

    I'm guessing you have bug elsewhere in the code.  

    Thursday, May 23, 2019 1:09 PM
  • User81789783 posted

    you know , I need to return dataset row like below

    Json(ds1.Tables[0], JsonRequestBehavior.AllowGet);

    where ds1.Tables[0], can  hold multiple rows , I have doubt over there ,let me update certain piece of code again

     [HttpPost]
            public ActionResult subscribe(string values)
            {
                DataSet  ds = new DataSet ();
                ds = ts.SelectQueryDS ("select * from [TBL_USER] where username="+"'"+   Session["user"] + "'");
    
                int id= Convert.ToInt32(ds.Tables[0].Rows[0][0]);
    
                string[] valuesdb = values.Split(',');
                for (int i = 0; i < valuesdb.Length; i++)
                {
                    valuesdb[i] = valuesdb[i].Trim();
                    ts.IUD("insert into tbl_usergroup (userid,gid)values( " + id + "," + valuesdb[i] + ")");
                }
              
                DataSet ds1 = new DataSet();
             
                ds1 = ts.SelectQueryDS("select * from [TBL_USER] where username=" + "'" + Session["user"] + "'");
    
                int id2 = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                ds1 = ts.SelectQueryDS("select *   FROM [GroupChatSignalR].[dbo].[tbl_usergroup]  as [usergroup]  inner join tbl_group grp  on [usergroup].gid = grp.gid    where [usergroup].[Userid] =" + id2);
    
               
    
                  return Json(ds1.Tables[0], JsonRequestBehavior.AllowGet);
             
                   
            }
    
                  $.ajax({
                                url: '/Home/subscribe',
                                type: "POST",
                                //data: { values: valueArray.toString() },
                                data: JSON.stringify({ values: valueArray.toString() }),
                                cache: false,
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function (response) {
                                    alert(response);
                                },
                                failure: function (response) {
                                    alert(response.responseText);
                                },
                                error: function (response) {
                                    alert(response.responseText);
                                }
                            });

    Thursday, May 23, 2019 1:16 PM
  • User475983607 posted

    you know , I need to return dataset row like below

    Json(ds1.Tables[0], JsonRequestBehavior.AllowGet);

    where ds1.Tables[0], can  hold multiple rows , I have doubt over there ,let me update certain piece of code again

    Have you verified the "subscribe" action is invoked?  Have you set a break point in the "subscribe" action and stepped through the code?

    Thursday, May 23, 2019 1:29 PM
  • User81789783 posted

    I solve  issue like this

    [HttpPost]
            public ActionResult subscribe(string values)
            {
                DataSet  ds = new DataSet ();
                ds = ts.SelectQueryDS ("select * from [TBL_USER] where username="+"'"+   Session["user"] + "'");
    
                int id= Convert.ToInt32(ds.Tables[0].Rows[0][0]);
    
                string[] valuesdb = values.Split(',');
                for (int i = 0; i < valuesdb.Length; i++)
                {
                    valuesdb[i] = valuesdb[i].Trim();
                    ts.IUD("insert into tbl_usergroup (userid,gid)values( " + id + "," + valuesdb[i] + ")");
                }
              
                DataSet ds1 = new DataSet();
             
                ds1 = ts.SelectQueryDS("select * from [TBL_USER] where username=" + "'" + Session["user"] + "'");
    
                int id2 = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                ds1 = ts.SelectQueryDS("select *   FROM [GroupChatSignalR].[dbo].[tbl_usergroup]  as [usergroup]  inner join tbl_group grp  on [usergroup].gid = grp.gid    where [usergroup].[Userid] =" + id2);
    
                string s = DataTableToJSONWithStringBuilder(ds1.Tables[0]);
    
                return Json(s, JsonRequestBehavior.AllowGet);
             
                   
            }
     public string DataTableToJSONWithStringBuilder(DataTable table)
     {
         var JSONString = new StringBuilder();
         if (table.Rows.Count > 0)
         {
             JSONString.Append("[");
             for (int i = 0; i < table.Rows.Count; i++)
             {
                 JSONString.Append("{");
                 for (int j = 0; j < table.Columns.Count; j++)
                 {
                     if (j < table.Columns.Count - 1)
                     {
                         JSONString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\",");
                     }
                     else if (j == table.Columns.Count - 1)
                     {
                         JSONString.Append("\"" + table.Columns[j].ColumnName.ToString() + "\":" + "\"" + table.Rows[i][j].ToString() + "\"");
                     }
                 }
                 if (i == table.Rows.Count - 1)
                 {
                     JSONString.Append("}");
                 }
                 else
                 {
                     JSONString.Append("},");
                 }
             }
             JSONString.Append("]");
         }
         return JSONString.ToString();
     }   
        $.ajax({
                                url: '/Home/subscribe',
                                type: "POST",
                                //data: { values: valueArray.toString() },
                                data: JSON.stringify({ values: valueArray.toString() }),
                                cache: false,
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function (response) {
                                    
                                  //  alert(response);
                                   // success: function (data) {
                                    alert("Your groups # is: " + response)
                                 
                               
                                    },
                                    failure: function (response) {
                                        alert(response.responseText);
                                    },
                                    error: function (response) {
                                        alert(response.responseText);
                                    }
                                });
                            // console.debug(obj); // Write it to the console
                        });

    now i need to pass success response to another action method

    like URLAction (................)..

    looking around how to do this ,REST IS OK

    Thursday, May 23, 2019 1:35 PM
  • User475983607 posted

    now i need to pass success response to another action method

    like URLAction (................)..

    looking around how to do this ,REST IS OK

    Invoke the next URL in the AJAX success callback.

    Thursday, May 23, 2019 1:50 PM
  • User81789783 posted

    unable to call , urlACtion("","")

    Thursday, May 23, 2019 3:43 PM
  • User81789783 posted
      $.ajax({
                                url: '/Home/subscribe',
                                type: "POST",
                                //data: { values: valueArray.toString() },
                                data: JSON.stringify({ values: valueArray.toString() }),
                                cache: false,
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function (response) {
                                    
                                  //  alert(response);
                                   // success: function (data) {
                                    alert("Your groups # is: " + response)
                                  // window.location = newurl;
                               
                                    },
                                    failure: function (response) {
                                        alert(response.responseText);
                                    },
                                    error: function (response) {
                                        alert(response.responseText);
                                    }
                                });

    this i need to send

    alert("Your groups # is: " + response)

    i need  to send  response to another action method

    Thursday, May 23, 2019 3:48 PM
  • User475983607 posted

    this i need to send

    alert("Your groups # is: " + response)

    i need  to send  response to another action method

    Again, call the second URL from the success handler of the first AJAX function.

    Thursday, May 23, 2019 5:05 PM
  • User1520731567 posted

    Hi erum,

    this i need to send

    alert("Your groups # is: " + response)

    i need  to send  response to another action method

    You just change your format of your return Json,like:

    [HttpPost]
            public ActionResult subscribe(string values)
            {
                DataSet  ds = new DataSet ();
                ds = ts.SelectQueryDS ("select * from [TBL_USER] where username="+"'"+   Session["user"] + "'");
    
                int id= Convert.ToInt32(ds.Tables[0].Rows[0][0]);
    
                string[] valuesdb = values.Split(',');
                for (int i = 0; i < valuesdb.Length; i++)
                {
                    valuesdb[i] = valuesdb[i].Trim();
                    ts.IUD("insert into tbl_usergroup (userid,gid)values( " + id + "," + valuesdb[i] + ")");
                }
              
                DataSet ds1 = new DataSet();
             
                ds1 = ts.SelectQueryDS("select * from [TBL_USER] where username=" + "'" + Session["user"] + "'");
    
                int id2 = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
                ds1 = ts.SelectQueryDS("select *   FROM [GroupChatSignalR].[dbo].[tbl_usergroup]  as [usergroup]  inner join tbl_group grp  on [usergroup].gid = grp.gid    where [usergroup].[Userid] =" + id2);
    
                string s = DataTableToJSONWithStringBuilder(ds1.Tables[0]);
    

    ... //return Json(s, JsonRequestBehavior.AllowGet); return Json(new { flag = "success", s }, JsonRequestBehavior.AllowGet);

    }

    and then ajax receive json in success callback:

     $.ajax({
                                url: '/Home/subscribe',
                                type: "POST",
                                //data: { values: valueArray.toString() },
                                data: JSON.stringify({ values: valueArray.toString() }),
                                cache: false,
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function (response) {
                                    
                                   alert(response.s); //show s
                                   // success: function (data) {
                                    alert("Your groups # is: " + response.flag)//show flag: Your groups # is:success
                                  // window.location = newurl;
                               
                                    },
                                    failure: function (response) {
                                        alert(response.responseText);
                                    },
                                    error: function (response) {
                                        alert(response.responseText);
                                    }
                                });

    Best Regards.

    Yuki Tao

    Friday, May 24, 2019 3:20 AM
  • User-2054057000 posted

    I think you need to change return type from ActionResult to JsonResult.

    Friday, May 24, 2019 3:50 AM