I am getting this error and I do not know how to get passed it. I am trying to do an ajax call to populate my data store. The error is:
Parsererror 'function' was not called when I do this :
var customStore = new DevExpress.data.CustomStore({
load: function () {
return $.ajax({
url: 'URL/Service/GetCustomers?callback=?fnsuccesscallback',
crossOrigin: true,
crossDomain: true,
jsonp: true,
type: 'GET',
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
jsonpCallback: 'fnsuccesscallback',
async: false,
success: function (res) {
console.log("success");
res = JSON.parse(res);
console.log("data _" + res);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
}
});
var fnsuccesscallback = function (data) {
alert(data);
};
var gridDataSourceConfiguration = {
store: customStore
};
My Service code for this function is :
Function GetCustomers() As Stream Implements IService.GetCustomers
Try
Dim Cust As List(Of Customers) = New List(Of Customers)
Dim SQLSTR As String = ""
SQLSTR = "Select Code, Name, ID FROM Table"
Dim ErrorMessage As String = ""
ErrorMessage = Obj.OpenConnection(SQLServer, UmbrellaDatabase, UserCode, UserPassword)
If ErrorMessage <> "" Then
System.Diagnostics.EventLog.WriteEntry("APP", ErrorMessage, EventLogEntryType.Error)
WebOperationContext.Current.OutgoingResponse.StatusCode = 501
WebOperationContext.Current.OutgoingResponse.StatusDescription = ErrorMessage
Return Nothing
Else
Dim CustomerDetails As DataSet
CustomerDetails = tObj.GetDataSQL(SQLSTR)
If Not CustomerDetails Is Nothing Then
CustomerDetails.DataSetName = "Companies"
CustomerDetails.Tables(0).TableName = "Companies"
Dim CustomerTable As DataTable
Dim CustomerRow As DataRow
If CustomerDetails.Tables.Count > 0 Then
CustomerTable = CustomerDetails.Tables(0)
If CustomerTable.Rows.Count > 0 Then
Dim i As Integer
For i = 0 To CustomerTable.Rows.Count - 1
CustomerRow = CustomerTable.Rows(i)
Dim CC As New Customers
CC.Code = CustomerRow.Item("Code")
CC.Name = CustomerRow.Item("Name")
CC.InternalID = CustomerRow.Item("InternalID")
Cust.Add(CC)
Next i
' Serialize the results as JSON
Dim serializer As DataContractJsonSerializer = New DataContractJsonSerializer(Cust.GetType())
Dim Stream As MemoryStream = New MemoryStream
serializer.WriteObject(Stream, Cust)
' Return the results serialized as JSON
Dim json As String = Encoding.Default.GetString(Stream.ToArray())
Return New MemoryStream(Encoding.UTF8.GetBytes(json))
Obj.CloseConnection()
WebOperationContext.Current.OutgoingResponse.StatusCode = 200
WebOperationContext.Current.OutgoingResponse.StatusDescription = "OK"
End If
End If
Else
System.Diagnostics.EventLog.WriteEntry("APP", ErrorMessage, EventLogEntryType.Error)
WebOperationContext.Current.OutgoingResponse.StatusCode = 501
WebOperationContext.Current.OutgoingResponse.StatusDescription = ErrorMessage
Cust = Nothing
Return Nothing
End If
End If
Catch ex As Exception
System.Diagnostics.EventLog.WriteEntry("Umbrella Mobile Service", ex.Message, EventLogEntryType.Error)
WebOperationContext.Current.OutgoingResponse.StatusCode = 501
WebOperationContext.Current.OutgoingResponse.StatusDescription = ex.Message
Return Nothing
End Try
Dispose()
End Function
How should my JSON output look like in my service in order to send out the correct callback? What should I do in order for this error not to show?
Related
API Controller Action
[HttpPost]
public string FetchPayeeDetails(string strDetails)
{
try
{
// PayeeDetails is a class
PayeeDetails objDetails = JsonConvert.DeserializeObject<PayeeDetails>(strDetails);
string AccNo = objDetails.AccNo;
string ChequeNo = objDetails.ChequeNo;
string Amount = objDetails.Amount;
// rest of the code
return "something"; // string is returned
}
catch(Exception ex){
return ex.Message;
}
}
Ajax Call Code
var Ac = $('#AccNo').val();
var Ch = $('#ChequeNo').val();
var Am = $('#Amount').val();
var API_URI = "http://IP:Port/api/contollerName"
var objData = {};
objData.AccNo = Ac;
objData.ChequeNo = Ch;
objData.Amount = Am;
$.ajax({
url: API_URI,
type: "POST",
data: {strDetails:JSON.stringify(objData)},
async: false,
contentType: "application/json;",
mode: 'cors',
success: function (Data) {
$('#PayeeName').val(Data);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#PayeeName').val("Error at Ajax!");
}
});
Error at Ajax:
Console: Failed to load resource: the server responded with a status of 400 (Bad Request)
responseJSON: {type: 'https://tools.ietf.org/html/rfc7231#section-6.5.1', title: 'One or more validation errors occurred.', status: 400, traceId: '00-35e7f6bbc2a7d7952564f2644721eaa9-fa7b6123403222bf-00', errors: {…}}
responseText: "{\"type\":\"https://tools.ietf.org/html/rfc7231#section-6.5.1\",\"title\":\"One or more validation errors occurred.\",\"status\":400,\"traceId\":\"00-35e7f6bbc2a7d7952564f2644721eaa9-fa7b6123403222bf-00\",\"errors\":{\"strDetails\":[\"The strDetails field is required.\"]}}"
My application is using Datatable which binds the data and event dynamically. When monitored from Developer tool in internet explorer one can see an increase in the total memory usage after each server successful response (increases approx. 29-35 MB). I tried solutions to free the DOM using jquery remove(), empty(), detach(), and destroy() methods but none stops the memory increase. Even destroying the datatable before request doesn't help. I also tried to delete the variables in the script, set the variables to null, and set the event bind to the datatable off().
The code snippet from the js file is as follows
function LoadData(isReset) {
var viewId = $jq('#ddlCategory').val();
if (viewId == 'undefined' || viewId == null || viewId == '') {
return false;
}
try {
//Clear the variables and remove the datatable
ClearFunction();
dtAjaxCall = $jq.ajax({
type: "POST",
url: "Ajax/WorkListAjax.aspx/GetData",
deferRender: true,
contentType: "application/json; charset=utf-8",
async: true,
dataType: "json",
timeout: 0,
headers: { Connection: 'keep-alive' },
data: JSON.stringify({
"viewId": viewId
}),
success: function (response) {
//Clear the variables and remove the datatable
ClearFunction();
result = response.d;
if (result.IsError) {
CustomConfirm("dialog-confirm", result.Message, "");
}
else if (result.Data != null) {
data01 = result.Data;
result.Data = null; //set the result.Data as null
tableHeaders = ''; //var to store Datatable headers
columns = []; //var to store Datatable columns
excludeFilters = [];//var to exclude the filters.
bulkOperation = data01.BulkOperation; //var to store if bulk operation is required
//Create the table header columns dynamically as configured in database
$jq.each(data01.Columns, function (i, val) {
if (val.HiddenColumn != "Y") {
tableHeaders += "<th>" + val.DisplayName + "</th>";
var col = { 'title': val.DisplayName, 'data': val.DataColumnName.toLowerCase() };
columns.push(col);
}
if (val.FilterColumn >= 0) {
excludeFilters.push(val.FilterColumn);
}
});
data = $jq.parseJSON(data01.Results); //result returned in ajax call
json = $jq.parseJSON(data01.WorkListJQStructure); //datatable configuration returned in ajax call
delete json["bAutoWidth"];
json.data = data;
json.columns = columns;
DisplayExportOptions(json.buttons, 'resultsTable', 'ulExportTo');
//Add checkbox for each row in the data table
dtColumnDefinition = function (data, type, full, meta) {
return '<input type="checkbox" data-id="' + data + '">';
}
json.aoColumnDefs[0].render = dtColumnDefinition;
//Ajax call to save the datatable state state
dtSaveState = function (settings, data) {
$jq.ajax({
type: "POST",
url: "Ajax/WorkListAjax.aspx/SaveState",
contentType: "application/json; charset=utf-8",
async: true,
dataType: "json",
data: JSON.stringify({ "viewId": viewId, json: data }),
"success": function () {
},
error: function (request, status, error) {
CustomConfirm("dialog-confirm", "An error occurred while processing your current request. Please try again", "");
}
});
}
//Try destroying the existing instance
if ($jq.fn.DataTable.isDataTable('#resultsTable')) {
$jq('#resultsTable').DataTable().destroy();
}
//Make the body empty
$jq('#resultsTable tbody').empty();
//Remove the datatable
$jq("#resultsTable").dataTable().remove();
//Datatable save state function call
json.stateSaveCallback = dtSaveState;
//Empty from the parent table of the datatable
$jq("#resultsTable_display").empty();
//Create the datatable header dynamically and add to the parent table
$jq("#resultsTable_display").append('<table id="resultsTable" class="display" style="width:100%;white-space: nowrap;"><thead><tr>' + tableHeaders + '</tr></thead></table>');
//bind the json and data to the datatable
SearchTable = $jq("#resultsTable").DataTable(json).rows().invalidate().draw();
//Set the event off before
$jq("#resultsTable").off();
//Set the event
$jq('#resultsTable').on('length.dt', function (e, settings, len) {
//code to set the height dynamically...
});
$jq("#resultsTable_display .dataTables_scrollHeadInner").css("width", "100%");
$jq("#resultsTable_display .dataTables_scrollHeadInner .dataTable").css("width", "100%");
BulkOpr(bulkOperation, SearchTable);
//reset the columns after binding the data
SearchTable.columns.adjust();
DataTableName = '#resultsTable';
$jq('#resultsTable').on('page.dt', function () {
info = SearchTable.page.info();
customHeight = 0;
customHeight = UserDefinedFields.CustomPageHeight(info, 40);
$jq('#Parent').attr('style', 'min-height:' + customHeight + 'px;');
});
$jq("a").removeClass("dt-button");
}
//set the variables null
json = null;
data01 = null;
data = null;
},
error: function (request, status, error) {
//do nothing...
}
});
return false;
}
finally {
//Clear the variables...
}
}
//----------------------------------------------
//method to clear the variables and datatables
function ClearFunction()
{
//make all variables null
dtAjaxCall = null;
resultSearchTable = null;
DataTableName = null;
info = null;
customHeight = null;
cells = null;
selected = null;
cBox = null;
clist = null;
dtSaveState = null;
result = null;
data01 = null;
tableHeaders = null;
columns = null;
excludeFilters = null;
bulkOperation = null;
data = null;
json = null;
dtColumnDefinition = null;
//clear dom objects
$jq("#resultsTable").dataTable().remove();
$jq("#resultsTable_display").dataTable().empty();
}
Thanks!
We are refreshing a datatable in a polling method, and it seems to lock up the browser. I don't have an answer either.
I want to upload a image on server.I use ajax and webmethod, It works when I run code in local host but when I upload it in server it does not work.
I guess there are some problems in my webmethod but I could not find it.
function savefile(location, files, method_name) {
var data = new FormData();
var webmethod = "../WebService.asmx/" + method-name;
if (files.length > 0) {
data.append("UploadedFile", files[0]);
data.append("location", location);
}
var ajaxRequest = $.ajax({
type: "POST",
url: webmethod,
enctype: 'multipart/form-data',
contentType: false,
processData: false,
data: data
});
}
<WebMethod(EnableSession:=True)> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function savefile() As String
Try
Dim result As String = ""
Dim pdf As String = ""
If HttpContext.Current.Request.Files.AllKeys.Any() Then
Dim httpPostedFile = HttpContext.Current.Request.Files("UploadedFile")
If httpPostedFile IsNot Nothing Then
Dim location = HttpContext.Current.Request("location")
Dim extension As String = System.IO.Path.GetExtension(httpPostedFile.FileName)
Dim filename_widthout_extension As String = httpPostedFile.FileName.Substring(0, httpPostedFile.FileName.Length - extension.Length)
Dim file_name = httpPostedFile.FileName
Dim fileSavePath = System.IO.Path.Combine(Server.MapPath(HttpContext.Current.Request("location").ToString), filename_widthout_extension + postfix + extension)
result = (location + "/" + filename_widthout_extension + extension).ToString.Substring(2)
httpPostedFile.SaveAs(fileSavePath)
location = httpPostedFile.FileName
End If
Return ""
Catch ex As Exception
End Try
End Function
Here is my ajax call function on button click
document.getElementById("btnSubmit").onclick = function ()
{
var txtImageName = $('#txtImageName').val();
var CategoryId = $('#cmbCategory').val();
var ImageURL = $('#txtImageURL').val();
var ImageSource = $('#textEditor').val();
var value = CKEDITOR.instances['textEditor'].getData()
alert
$.ajax({
url: "UrlwebService.asmx/InsertImage",
type: 'POST',
data: { ImageName: txtImageName, ImageUrl3x:ImageURL,ImageSource:value,CategoryId:parseInt(CategoryId) },
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
success: function (Categories) {
// states is your JSON array
alert(Categories);
},
error: function (xhr, err) {
alert("I'm in terror");
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
});
};
I change content type to application/json it will also throwing me error
and here I'm calling this method.....
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public void InsertImage(string ImageName, string ImageUrl3x, string ImageSource, int CategoryId)
{
var result = ImageRepo.InsertImage(ImageName,ImageUrl3x,ImageSource,CategoryId);
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
Context.Response.Write(js.Serialize(result));
}
I have the following $.ajax post call. It would go through the action being called but then it would trigger the "error" block of the function even before the actionresult finishes. Also, it seems to reload the whole page after every pass.
var pnameVal = '<%: this.ModelCodeValueHelper().ModelCode%>';
var eidVal = '<%: ViewBag.EventId %>';
var dataV = $('input[ name = "__RequestVerificationToken"]').val();
var urlVal = '<%: Url.Action("New") %>';
alert('url > ' + urlVal);
alert('pname - ' + pnameVal + ' eid - ' + eidVal + ' dataV = ' + dataV);
$.ajax({
url: urlVal,
//dataType: "JSONP",
//contentType: "application/json; charset=utf-8",
type: "POST",
async: true,
data: { __RequestVerificationToken: dataV, pname: pnameVal, eId: eidVal },
success: function (data) {
alert('successssesss');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert('dammit');
}
})
.done(function (result) {
if (result.Success) {
alert(result.Message);
}
else if (result.Message) {
alert(' alert' + result.Message);
}
alert('done final');
//$('#search-btn').text('SEARCH');
waitOff();
});
This is the action
[HttpPost]
public ActionResult New(string pname, int eid)
{
var response = new ChangeResults { }; // this is a viewmodel class
Mat newMat = new Mat { "some stuff properties" };
Event eve = context.Events.FirstOrDefault(e => e.Id == eid);
List<Mat> mats = new List<Mat>();
try
{
eve.Mats.Add(newMat);
icdb.SaveChanges();
mats = icdb.Mats.Where(m => m.EventId == eid).ToList();
response.Success = true;
response.Message = "YES! Success!";
response.Content = mats; // this is an object type
}
catch (Exception ex)
{
response.Success = false;
response.Message = ex.Message;
response.Content = ex.Message; // this is an object type
}
return Json(response);
}
Btw, on fiddler the raw data would return the following message:
{"Success":true,"Message":"Added new Mat.","Content":[]}
And then it would reload the whole page again. I want to do an ajax call to just show added mats without having to load the whole thing. But it's not happening atm.
Thoughts?
You probably need to add e.preventDefault() in your handler, at the beginning (I am guessing that this ajax call is made on click, which is handled somewhere, that is the handler I am talking about).