-1

I have a problem in updating sql database table with jQuery ajax. here is my scenario. I am working on privileges table to assign a teacher some kind of privilege/rights to perform some required functionality of the website.

1) I call a webmethod and pass teacher's id to retrive all privileges assigned to that particular teacher using jQuery ajax 2) in the success function of step 1 I call another web method using jQuery ajax and bind a click event on checkbox (on/of toggle button -- its input type was checkbox) present against every privilege listed. 3) when I click on that on/off toggle checkbox I want to update a row in sql database table in privileges table if it is on and user turns it off then that particular privilege will be unassigned to that teacher.

here is my code

 public void UpdatePrivileges(string _columnName, byte _value, int _teacherid)
    {
        JavaScriptSerializer objserializer = new JavaScriptSerializer();
        myDatabase.CreateConnection();
        myDatabase.InitializeSQLCommandObject(myDatabase.GetCurrentConnection, "update tbl_privileges set " + _columnName + " = @val where teacher_id = @tid");
        myDatabase.obj_sqlcommand.Parameters.AddWithValue("@tid", _teacherid);
        myDatabase.obj_sqlcommand.Parameters.AddWithValue("@val", Convert.ToByte(_value));
        try
        {
            myDatabase.OpenConnection();
            myDatabase.obj_sqlcommand.ExecuteNonQuery();
        }
        finally
        {
            myDatabase.CloseConnection();
            myDatabase.obj_sqlcommand.Dispose();
        }
        HttpContext.Current.Response.Write(objserializer.Serialize("Updated"));
    }

This code is for retrieving teacher's privileges and show them on webForm.

   function GetTeacherPrivileges() {
        var teacherid = $('#<%=txtTeacherIDToPopulatePrivileges.ClientID%>').val();
        $.ajax({
            url: 'source/WebServices/GetAllTeachers.asmx/GetPrivileges',
            method: 'post',
            data: { _teacherID: teacherid},
            datatype: 'json',
            success: function (data) {
                var obj = JSON.stringify(data);
                var arrayjson = $.parseJSON(obj);
                var actualarray = $.parseJSON(arrayjson);
                $.each(actualarray, function (i, v) {
                    $('#tablebody').append('<tr class="table-row"> <td class="col-3"><span>Events</span></td><td class="col-2"><a href="#">is this teacher eligible to making events?</a></td><td class="col-3"><label class="switch centerbuttion "><input id="check_event" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="No"></span><span class="switch-handle"></span></label></td></tr><tr class="table-row">  <td class="col-3"><span>Attendance</span></td><td class="col-2"><a href="#">Do you want this teacher can mark attendance?</a></td><td class="col-3"><label class="switch centerbuttion "><input id="check_attendance" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="NO"></span><span class="switch-handle"></span></label></td></tr><tr class="table-row"><td class="col-3"><span>Homework</span></td><td class="col-2"><a href="#">Teacher will be able to upload homework with their respective classes.</a></td><td class="col-3"><label class="switch centerbuttion "><input id="check_homework" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="NO"></span><span class="switch-handle"></span></label></td></tr><tr class="table-row"><td class="col-3"><span>Reports</span></td><td class="col-2"><a href="#">Do you want this teacher to generate reports?</a></td><td class="col-3"><label class="switch centerbuttion "><input id="check_reports" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="NO"></span><span class="switch-handle"></span></label></td></tr><tr class="table-row"><td class="col-3"><span>Timetable</span></td><td class="col-2"><a href="#">Can this teacher make time table(s)?</a></td><td class="col-3"><label class="switch centerbuttion "><input id="check_timetable" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="NO"></span><span class="switch-handle"></span></label></td></tr><tr class="table-row"><td class="col-3"><span>Datesheet</span></td><td class="col-2"><a href="#">Can this teacher make Date Sheet(s)?</a></td><td class="col-3"><label class="switch centerbuttion "><input id="check_datesheets" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="NO"></span><span class="switch-handle"></span></label></td></tr>');
                    var event = v.Event;
                    var attendance = v.Attendance;
                    var homework = v.Homework;
                    var reports = v.Reports;
                    var timetable = v.TimeTable;
                    var datesheet = v.DateSheet;
                    if (event == 1) {
                        $('#check_event').trigger('click');
                    }
                    if (attendance == 1) {
                        $('#check_attendence').trigger('click');
                    }
                    if (homework == 1) {
                        $('#check_homework').trigger('click');
                    }
                    if (reports == 1) {
                        $('#check_reports').trigger('click');
                    }
                    if (timetable == 1) {
                        $('#check_timetable').trigger('click');
                    }
                    if (datesheet == 1) {
                        $('#check_datesheets').trigger('click');
                    }
                    $('#check_event').bind({
                        click: function () {
                            var privilegevalue = columnvalue('#check_event');
                            UpdatePrivilege('event', privilegevalue);
                        }
                    });
                });
            },
            error: function (error) {
                alert("Error: " + error);
            }
        });

This is the second AJAX code which I call in the success function of above AJAX for binding the click event.

function UpdatePrivilege(column,value) {
        var teacherid = $('#<%=txtTeacherIDToPopulatePrivileges.ClientID%>').val();
        $.ajax({
            url: 'source/WebServices/GetAllTeachers.asmx/UpdatePrivileges',
            data: { _columnName: "'"+column+"'" , _value: value , _teacherid:teacherid },
            dataType: 'json',
            dataContent: 'application/json; charset=utf-8',
            success: function (data) {
                alert('privilege updated'+data);
            },
            error: function(data) {
                alert('Error in updating privilege' + data);
            }
        });
    }

When I run my aspx page and input teacher's id to GetAllTeachers() function all works good and it binds the click event on checkbox against event privilege but when I click on that it gives me error from AJAX function of UpdatePrivilege() function.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • Can you provide the error message? – Brandon Oct 11 '16 at 22:30
  • Put `console.log(data)` in the error function of ajax UpdatePrivilege function so you can see what the error is and be more specific about the situation you are dealing with. – anima_incognita Oct 11 '16 at 22:31
  • it is returning [object object] with message error in updating privilege – Jahan Ahmed Abbasi Oct 11 '16 at 22:31
  • @JahanAhmedAbbasi yes it is returning [object object] because the "data" returned to you as error are actually an object and can't be shown by the alert. you should use console.log(data) and locate the actual reason why the ajax function fails. – anima_incognita Oct 11 '16 at 22:33
  • yes i did it and this is the error i see in console window request format is unrecognized for url unexpectedly ending in /UpdatePrivilege. – Jahan Ahmed Abbasi Oct 11 '16 at 22:41
  • give a look at this thread, I believe it will help you with your problem: [relevant stackoverflow thread](http://stackoverflow.com/questions/657313/request-format-is-unrecognized-for-url-unexpectedly-ending-in) – anima_incognita Oct 11 '16 at 22:43
  • Whilst I don't know why someone has downvoted this post, it may be because readers don't like posts written in all-lower case, or it may because some readers don't care for txtpk such as `plz` etc. If you can take care with your writing, it does really make downvotes less likely. Hope that helps! – halfer Oct 11 '16 at 22:47
  • and now that I see it... the code you have posted says `url: 'source/WebServices/GetAllTeachers.asmx/UpdatePrivileges'` and the error message says `request format is unrecognized for url unexpectedly ending in /UpdatePrivilege.` are you 100% sure there is not an accidental typographical error in your actual code? I'm talking about the difference in "UpdatePrivileges" and "UpdatePrivilege" – anima_incognita Oct 11 '16 at 22:47

1 Answers1

0

If you are wanting to send json you need to stringify the data yourself. Also you don't need the extra quotes wrapping "'"+column+"'"

Try:

function UpdatePrivilege(column,value) {
    // I assume you are running this within Razor context and not in a javascript file
    var teacherid = $('#<%=txtTeacherIDToPopulatePrivileges.ClientID%>').val();

     // create data object
     var dataObj={ _columnName: column , _value: value , _teacherid:teacherid };
     // stringify it
     var postData = JSON.stringify(dataObj);

     $.ajax({
        url: 'source/WebServices/GetAllTeachers.asmx/UpdatePrivileges',
        data: postData ,// stringified data
        dataType: 'json',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            console.log('privilege updated', data);
        },
        error: function(data) {
            console.log('Error in updating privilege' , data);
        }
    });
}
charlietfl
  • 170,828
  • 13
  • 121
  • 150
  • 1
    *"didn't work"* is quite meaningless. Inspect actual request in browser dev tools network and check status and what is sent/returned. Doesn't appear you are sending json from server but you are requesting it – charlietfl Oct 11 '16 at 22:39
  • i previously done that and on that behalf i said it didn't work. i put the error in console.log() and the error i see in console window is request format is unrecognized for url unexpectedly ending in /UpdatePrivilege – Jahan Ahmed Abbasi Oct 11 '16 at 22:44
  • need to debug server side then. Does data that is sent look as expected in dev tools network? – charlietfl Oct 11 '16 at 22:54
  • i was doing a mistake of datacontent to contentType, this was the issue i retyped the correct word (contentType) and it works fine, thanks for your help i do appreciate it :) thank you very much – Jahan Ahmed Abbasi Oct 11 '16 at 22:55
  • ah yes...I glanced over that and didn't notice it – charlietfl Oct 11 '16 at 22:56