I'm trying to store some javascript variables to sql server database. But when I'm running the code, an alert is displayed saying Internal server error.
window.onload = function ()
{ codeLatLng(); SaveUserLocation(); return false }
/*===========================================================*/
function SaveUserLocation() {
//Jquery ajax call to server side method
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
//Url is the path of our web method (Page name/function name)
url: "FriendHomePage.aspx/SaveFriendLocation",
//Pass paramenters to the server side function
data: "{'LocationName':'" + userLocationName + "', 'UserID':'" + myUserID + "'}",
success: function (response) {
//Success or failure message e.g. Record saved or not saved successfully
if (response.d == true) {
alert("Record saved successfully");
}
else {
alert("Record could't be saved");
}
},
error: function (xhr, textStatus, error) {
//Show error message(if occured)
alert("Error: " + error);
}
});
}
[WebMethod]
public static bool SaveFriendLocation(string LocationName, int UserID)
{
bool status;
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["FTSCS"].ConnectionString))
{
string sql = "INSERT INTO tblLocation (LocationName,UserID) VALUES (@LocationName,@UserID)";
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@LocationName", LocationName);
cmd.Parameters.AddWithValue("@UserID", UserID);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
Int32 retVal = cmd.ExecuteNonQuery();
if (retVal > 0)
{
status = true;
}
else
{
status = false;
}
return status;
}
}
}
The error is most likely related to the fact you aren't passing up a valid JSON string ie { 'property': 'value' }
.
It's recommended you use JSON.stringify (or equivalent) when serializing JSON
var data = { LocationName: userLocationName, UserID: myUserID };
...
$.ajax({
...
data: JSON.stringify(data)
});
I believe in such situations you should turn on debug mode set break point and find out a real problem. If you can't resolve your real problem you can post a question here. Your question looks ambiguous because of possible errors:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.