Click here to Skip to main content
15,868,016 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I Apologize for my English I'm having a bit of a problem calling an Ajax function to insert new data to SQL database and then return the primary key of the inserted data ... Data is being inserted successfully but no primary is being returned !!!
Code for Web method :
C#
HttpCookie session = HttpContext.Current.Request.Cookies["Login"];
            string userid = session.Values["UserID"].ToString();
            string email = session.Values["Email"].ToString();
            string username = session.Values["Username"].ToString();
            string type = session.Values["Type"].ToString();
            string branchid = session.Values["BranchID"].ToString();
            string branchName = session.Values["BranchName"].ToString();
            string ownerID = session.Values["OwnerID"].ToString();
            string constr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand("select * from Car where car_plate='"+car.CarPlate+ "' and userid='"+userid+"'"))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = con;
                    con.Open();
                    DataTable cars = new DataTable();
                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    sda.Fill(cars);
                    if(cars.Rows.Count>0)
                    {
                        return "false";
                    }
                    else
                    {
                        cmd.Parameters.Clear();
                        cmd.Parameters.AddWithValue("@plate", car.CarPlate);
                        cmd.Parameters.AddWithValue("@company", car.CarCompany);
                        cmd.Parameters.AddWithValue("@type", car.CarType);
                        cmd.Parameters.AddWithValue("@model", car.CarModel);
                        cmd.Parameters.AddWithValue("@number", car.BodyNumber);
                        cmd.Parameters.AddWithValue("@color", car.CarColor);
                        cmd.Parameters.AddWithValue("@notes", car.Notes);
                        cmd.Parameters.AddWithValue("@clientid", car.ClientID);
                        cmd.Parameters.AddWithValue("@username", username);
                        cmd.Parameters.AddWithValue("@userid", userid);
                        cmd.CommandText = "insert into Car (car_plate,car_company,car_type,car_model,body_number,car_color,client_id,notes,Username,userid) OUTPUT INSERTED.car_id " +
                "values(@plate,@company,@type,@model,@number,@color,@clientid,@notes,@username,@userid)";
                        int newId = (Int32)cmd.ExecuteScalar();
                        con.Close();
                        JavaScriptSerializer js = new JavaScriptSerializer();
                        string newcarid = js.Serialize(newId);
                        return newcarid;
                    }
                }
            }

code for Ajax :
JavaScript
$("#btnAddCar").bind("click", function () {
                if ($("#cmb_client").val() == "") {
                    return Swal.fire({
                        icon: 'warning',
                        html: 'Please Choose a client !!!',
                        showConfirmButton: true
                    })
                }
                if ($("#txt_car_plate").val() == "") {
                    return Swal.fire({
                        icon: 'warning',
                        html: 'Please Enter Plate number !!',
                        showConfirmButton: true
                    })
                }
                else {
                    var car = {};
                    var clientaplit = $("#cmb_client").val().split('-');
                    car.CarPlate = $("#txt_car_plate").val();
                    car.CarCompany = $("#ddl_car_company option:selected").val();
                    car.CarType = $("#txt_car_type").val();
                    car.CarModel = $("#txt_car_model").val();
                    car.BodyNumber = $("#txt_body_number").val();
                    car.CarColor = $("#txt_car_color").val();
                    car.Notes = $("#txt_notes").val();
                    car.ClientID = clientaplit[0];
                    $.ajax({
                        type: "POST",
                        url: "Add.aspx/AddCar",
                        data: '{car: ' + JSON.stringify(car) + '}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            if (data.d == "false")
                            {
                                return Swal.fire({
                                    icon: 'warning',
                                    html: 'Plate number used before !!!',
                                    showConfirmButton: true
                                })
                            }
                            else
                            {
                                window.location.href = "vehicle.aspx?carid=" + data.d;
                            } 
                        },
                        error: function (err)
                        {
                            return Swal.fire({
                                icon: 'error',
                                html: 'Error',
                                showConfirmButton: true
                            })
                        } 
                    });
                }
            });

After clicking on btnAddCar button , data is inserted into SQL table successfully, but error message is being raised inserted of success .... Please someone tell me what I'm doing wrong !!!!

What I have tried:

i tried changing ajax method to:
JavaScript
type: "POST",
                        url: "Add.aspx/AddCar",
                        data: '{car: ' + JSON.stringify(car) + '}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
async:false,

but didn't help..
Posted
Updated 13-Oct-22 6:58am
Comments
Richard Deeming 14-Oct-22 10:15am    
new SqlCommand("select * from Car where car_plate='"+car.CarPlate+ "' and userid='"+userid+"'")

Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation/interpolation to build a SQL query. ALWAYS use a parameterized query.
MHD Salim Al-Tarsha 15-Oct-22 7:57am    
Yes you're right friend , Thanks ...

1 solution

In your ajax method remove the line
dataType:"json"
The success function is not called if this is set
 
Share this answer
 
Comments
MHD Salim Al-Tarsha 15-Oct-22 7:56am    
that's weird man because I've been using this line in all other methods and it's been working great !!
I will try it anyway ...
Thanks friend
George Swan 15-Oct-22 8:00am    
I had the same problem and it worked for me. Ajax is a bit flaky in my experience

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900