Submission issue internal server error - javascript

I am trying to submit data through form as below which gives error:
echo 'The # here does not begin a comment.'
echo The \# here does not begin a comment.
But it wont give error, if we submit like below:
echo The # here does not begin a comment.
echo The # here does not begin a comment.
That is ,without single quotes and slash ,i am unable to submit data.
Code as below:
function AjaxCallOnClick(userName, email, commentText, blogID, commentHtml, onCommentEmailID) {
var parameters = "{'commentUserName':'" + userName + "','email':'" + email + "','commentText':'" + commentText + "','blogID':'" + blogID + "','commentHtml':'" + commentHtml + "','onCommentEmailID':'" + onCommentEmailID + "'}";
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/BlogService.asmx/GetShareStoryData")%>",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Your Comment was Saved");
var getCommentList = response.d;
var allComments = '';
$('#dvMainAndReplyCommentSection').html('');
$.each(getCommentList, function (index, comments) {
var comment = comments.HtmlComment;
allComments += comment;
});
if (allComments) {
$('#dvMainAndReplyCommentSection').html(allComments);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
failure: function (response) {
alert(response.responseText);
}
});
}
What is the work around for this?

I tried like this format var parameters = JSON.stringify({ commentUserName: userName, email: email, commentText: commentText, blogID: blogID, commentHtml: commentHtml, onCommentEmailID: onCommentEmailID }); and it's working fine for me.

Try it...Removes double quotes when saving object.
function AjaxCallOnClick(userName, email, commentText, blogID, commentHtml, onCommentEmailID) {
var parameters = JSON.stringify({'commentUserName': userName,'email': email,'commentText': commentText,'blogID': blogID,'commentHtml': commentHtml,'onCommentEmailID': onCommentEmailID});
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/BlogService.asmx/GetShareStoryData")%>",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("Your Comment was Saved");
var res=JSON.parse(response);
var getCommentList = res.d;
var allComments = '';
$('#dvMainAndReplyCommentSection').html('');
$.each(getCommentList, function (index, comments) {
var comment = comments.HtmlComment;
allComments += comment;
});
if (allComments) {
$('#dvMainAndReplyCommentSection').html(allComments);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
failure: function (response) {
var res=JSON.parse(response);
alert(res.responseText);
}
});
}

Related

How to avoid repeating the same $.ajax() call

I have two $.ajax() calls in my javascript code.
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'district'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_district = JSON.parse(response);
district = L.geoJSON(json_district, {
onEachFeature: return_district,
});
ctl_layers.addOverlay(district, "district", "Overlays");
ar_district_object_names.sort();
$("#text_district_find_project").autocomplete({
source: ar_district_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'province'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_province = JSON.parse(response);
province = L.geoJSON(json_province, {
onEachFeature: return_province,
});
ctl_layers.addOverlay(province, "province", "Overlays");
ar_province_object_names.sort();
$("#text_province_find_project").autocomplete({
source: ar_province_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
changes on both ajax are as below:
tbl: 'district' -> tbl: 'province'
json_district -> json_province
return_district -> return_province
(district, "district", "Overlays") -> (province, "province", "Overlays")
ar_district_object_names -> ar_province_object_names
$("#text_district_find_project") -> $("#text_province_find_project")
Is there a way I can call this $.ajax() inside a function with one parameter and call the function afterwards. As an example:
function lyr(shpName){
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: `${shpName}`
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_shpName = JSON.parse(response);
shpName = L.geoJSON(json_shpName, {
onEachFeature: return_shpName,
});
ctl_layers.addOverlay(shpName, `${shpName}`, "Overlays");
ar_shpName_object_names.sort();
$("#text_shpName_find_project").autocomplete({
source: ar_shpName_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
}
lyr (district);
Can I use template strings? Can I use that a function inside a function. Any help would be highly appriceated.
Create a function for ajax call.
For eg.:-
function serviceajaxjson(_successfun, _failurefun, _url, _data, _async, _global) {
if (_successfun == null) _successfun = ajax_return_successfun;
if (_failurefun == null) _failurefun = ajax_return_failurefun;
if (_global != false) { _global = true; }
if (_async != false) { _async = true; }
$.ajax({
type: "POST",
url: _url,
data: _data,
global: _global,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
async: _async,
success: _successfun,
error: ajax_return_error,
failure: _failurefun
});
}
function ajax_return_successfun(response) {
console.info("success for " + response.d);
}
function ajax_return_failurefun(response) {
console.error("failuer occoured for " + response);
}
function ajax_return_error(response) {
console.warn("error occoured for " + response);
}
// // // call the above function
function myResponseFn(response){
if(response.data){
// // your code...
}
}
var data = "{'tbl': 'district'}";
serviceajaxjson(myResponseFn,myResponseFn,"http://localhost/webmap201/php/load_data.php",data);
If you're using latest version of popular browser (IE's dead, use Edge instead), then the simplest answer is yes. You might need some tweaking on the parameters and its use, but it should work

How to get All the elements of the Listbox when Button Click event is fired by using ajax call

How to get All the elements of the Listbox when Button Click event is fired by using ajax call
I am using a function and trying to call the function in ajax call my function is working fine it returning all the elements from the List box when I am trying to bind it with the ajax call its not working i need to call the elements in the code behind:
function responseData2() {
debugger;
var oListbox = $("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data);
});
var jobsheet = data;
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': '" + jobsheet + "'}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
My code-behind data:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object Details4(string selectedJobSheet)
{
try
{
string constr = ConfigurationManager.ConnectionStrings["Constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("select customer_id,first_name from jobsheetDetails", con))
{
string _data = "";
cmd.CommandType = CommandType.Text;
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]);
}
return _data;
}
}
}
catch (Exception)
{
throw;
}
}
It seems your variable data was inside the loop. Try to use object method to fix your problem.
function responseData2() {
debugger;
var holder_all_data = [];
var oListbox = $("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data);
holder_all_data.push({
var_name_data : data,
});
});
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': '" + holder_all_data + "'}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
And then next, if you want to get the individual name value which's thrown by AJAX, you should use foreach loop and it should look like this. :D
e.g
foreach( selectedJobSheet as $item ){
var name = $item['var_name_data']; //include the object variable name
console.log(name);
}
Try this:
function responseData2() {
debugger;
var jobsheet = [];
$("#submitlistbox2").each(function () {
var data = $(this).text() + " " + $(this).val();
jobsheet.push(data);
alert("The Names are: " + data);
});
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: { "selectedJobSheet": JSON.stringify(jobsheet) },
dataType: "json",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}
Code Behind:
[WebMethod]
public void Details4(string selectedJobSheet)
{
List<string> selectedJobSheetList = new List<string>();
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic data = serializer.Deserialize(selectedJobSheet, typeof(object));
foreach (var item in data)
{
selectedJobSheetList.Add(item);
}
}
It seems your data variable is overwritten in a loop and that is the issue. Hope below will help you.
function responseData2() {
var data = [];
var oListbox = $("#submitlistbox2").each(function (i) {
var data[i] = $(this).text() + " " + $(this).val()+"\n";
alert("The Names are: " + data[i]);
});
var jobsheet = JSON.stringify(data);
$.ajax({
url: "OnlineBiddingofExtraBoardDaysOff.aspx/Details4",
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
data: "{ 'selectedJobSheet': " + jobsheet + "}",
success: function (data) {
alert(data);
alert("success");
},
error: function (response) {
alert(response);
alert("error");
}
});
}

Class's not supported for deserialization of an array

I have this error(image):
My code:
function CheckLoginData() {
var user = [];
user.Email = $("#tbEmail").val();
user.Password = $("#tbPassword").val();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf=8",
url: "WS.asmx/CheckAccount",
data: "{user:" + JSON.stringify(user) + "}",
dataType: "json",
success: function (data) {
alert(data.d);
},
error: function (request, status, error) {
alert("Erro : " + request.responseText);
}
});
}
Why this error is happening? I've tried to search deeply but without success
You assign an empty array to user
var user = [];
But then you treat it as an object by assigning fields to it, it confuses the serialiser.
You will need to declare user to be an object
var user = { Email: $("#tbEmail").val(), Password: $("#tbPassword").val() };

Overwrite the Knockout object

I need to Overwrite the Knockout Object . But When I try this I got the Following Error. When the Page Load I called loadXMLFiles and It worked without any issue. after pressing a button when I try to overwrite the object I got following Error Uncaught TypeError: Cannot read property 'fromJS' of undefined in downloadFile Function. but in both Cases It's coming same object. Can Any one please help me on this???
var urlPath = window.location.pathname;
//var self = this;
$(function () {
ko.applyBindings(indexVM);
indexVM.loadXMLFiles();
});
var indexVM = {
XMLFiles: ko.observableArray([]),
loadXMLFiles: function () {
var self = this;
$.ajax({
type: "GET",
url: "../HotelBackEndProcess/UpdateDatabase/FillIndex",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.XMLFiles(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
},
DownloadFile: function () {
Id = this.Id;
var self = this;
$.ajax({
type: "GET",
url: "../HotelBackEndProcess/UpdateDatabase/DownloadFile",
contentType: "application/json; charset=utf-8",
data: { Id: Id },
dataType: "json",
success: function (data) {
ko.mapping.fromJS(XMLFiles, self.data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
}
};
You're probably missing the mapping plugin (which has to be downloaded separately):
See ko.mapping in GitHub.

Call $.ajax malfunctioning

I am making a ajax call, but server side code is not hit. Instead control goes to javascript file included in project. Here is my code:
<script type="text/javascript">
function AddEmployee()
{
debugger;
// jQuery.support.cors = true;
$.support.cors = true;
var Product = new Object();
Product.ID = 10;
Product.Name = "kRISH";
Product.Price = "23";
Product.Category = "AS";
// console.log(JSON.stringify({ Name: "kRISH", Price: "23", Category: "AS" }));
var json_text = JSON.stringify(Product,null,2);
**$.ajax**
({
url: 'http://localhost:62310/api/products',
type: 'POST',
data: json_text,
contentType: "application/json;charset=utf-8",
success: function (data) { WriteResponse(data); },
error: function (x, y, z)
{
$('#contentProgress').popup("close");
alert(x.responseText + " " + x.status);
}
});
}
</script>
Is the url correct, why are we not using the relative url here. Can you please try this
$.ajax('http://localhost:62310/api/products', {
type: "post",
data: json_text,
dataType: "json",
cache: false,
contentType: "application/json",
error: function (xhr, textStatus, errorThrown) {
alert(textStatus);
}
});

Categories