Datatables error after ajax call, ASP.Net - c#

I'm using ajax to call a partial view with a table inside a div called "div-GVPrevision". I'm using datatables, but I'm getting an error after the ajax call, and it says:
"DataTables warning: table id=GVPrevision - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3"
This is the ajax code:
<script>
function GVPrevision() {
$('#GVPrevision').DataTable({
"aaSorting": [],
aLengthMenu: [
[4, -1],
[4, "Todo"]
],
responsive: false
});
}
$(document).ready(function () {
GVPrevision();
$('.btnagregar').click(function (event) {
event.preventDefault();
var data = {
"codmov": $("#codmovf").val(),
"fechainicio": $("#fechainiciof").val(),
"fechatermino": $("#fechaterminof").val(),
"rutentidad": $("#rutentidadf").val(),
"motivo": $("#motivof").val()
};
$.ajax({
url: "/Ficha/AgregarfooterPrevision",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$("#div-GVPrevision").load('#Url.Content("~/Ficha/GVPrevision")');
GVPrevision();
}
else
window.location.href = "#Url.Action("Prevision", "Ficha")";
},
error: function () {
console.log('Login Fail!!!');
}
});
});
});
</script>

as i believe the Database is initialized more then once since you are not showing the whole code i can only provide you this simple but not at all recommended soln is to destroy the data table and then call the GCPervision
AGAIN its not at all recommended soln but is a soln , Just use Distroy function
function GVPrevision() {
$('#GVPrevision').DataTable({
"aaSorting": [],
aLengthMenu: [
[4, -1],
[4, "Todo"]
],
responsive: false
});
}
$(document).ready(function () {
GVPrevision();
$('.btnagregar').click(function (event) {
event.preventDefault();
var data = {
"codmov": $("#codmovf").val(),
"fechainicio": $("#fechainiciof").val(),
"fechatermino": $("#fechaterminof").val(),
"rutentidad": $("#rutentidadf").val(),
"motivo": $("#motivof").val()
};
$.ajax({
url: "/Ficha/AgregarfooterPrevision",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$('#GVPrevision').DataTable().destroy();
$("#div-
GVPrevision").load('#Url.Content("~/Ficha/GVPrevision")');
GVPrevision();
}
else
window.location.href = "#Url.Action("Prevision", "Ficha")";
},
error: function () {
console.log('Login Fail!!!');
}
});
});
});
</script>

You have called the DataTable method 2 times here, one after the document.ready method & another in AJAX success method:
$(document).ready(function () {
GVPrevision(); // first call
$('.btnagregar').click(function (event) {
// data insertion here
$.ajax({
// other ajax options here
success: function (response) {
if (response.Success) {
$("#div-GVPrevision").load('#Url.Content("~/Ficha/GVPrevision")');
GVPrevision(); // second call - this will fail
}
else
window.location.href = "#Url.Action("Prevision", "Ficha")";
},
error: function () {
console.log('Login Fail!!!');
}
});
});
});
To solve this issue, you have 2 choices:
Remove one of the GVPrevision call either after document.ready or AJAX POST success part,
Use destroy method before creating another DataTable, together with bDestroy (sometimes the destroy method called fnDestroy, pick up which is the proper one for your DataTable version):
function GVPrevision() {
$('#GVPrevision').DataTable({
"aaSorting": [],
aLengthMenu: [
[4, -1],
[4, "Todo"]
],
responsive: false,
"bDestroy": true
}).destroy(); // or fnDestroy()
}
If you have DataTable version 1.10 or more, you can add destroy: true:
function GVPrevision() {
$('#GVPrevision').DataTable({
destroy: true // add this line
"aaSorting": [],
aLengthMenu: [
[4, -1],
[4, "Todo"]
],
responsive: false,
});
}
Reference:
Warning: Cannot reinitialise DataTable (DataTables Documentation)
Datatables warning(table id = 'example'): cannot reinitialise data table

I fixed the problem by replacing the code with the jquery $.post() method:
if (response.Success) {
$.post("/Ficha/GVPrevision", function (datos) {
$("#div-GVPrevision").html(datos);
GVPrevision();
})
}

Related

Call the REST API url using asp.net / JQuery Ajax

I have to call a REST url for example : https://{baseurl}/employees/taxvalidation/. The Request type is JSON, but I'am always get the error Alert. I can't figure out what is the wrong in my code. I am using JQuery
The Supported HTTP Method is : PUT (HTTP PUT with correct request needs to be made) and also i need to pass a API key: XXXXX-XXXXX-XXXXX-XXXXX as request Header.
I have just have two mandatory fields in web page Employee name and Employee Tax.
I have tried the below using JQuery Ajax call.
Request Body Sample:
"name": "Company XYZ", /* mandatory */
"TAX": "*********", /* mandatory */
"taxType": "U", /* Could be E, S, or U */
"address": "2501 Boilermaker road", /* optional */
"citystatezip":"Lapalma ca 76567", /* optional */
"country": "US", //optional
"checks" : "DT",`enter code here`
"details": "DT"`enter code here` //optional
$(function() {
$("#btnSubmit").click(function() {
alert("Hi JQuery");
var URL = "https://api.dev.amx-city.com/tesmdm/dev/tesmdm/empcatalog/partners/taxvalidation/";
$.ajax({
url: URL,
headers : {
'AMX-API-KEY': '487b9474-27a6-4d21-8eda-c3a2a14e4ebe'
},
type: 'POST',
data: {
name: 'Employeename',
tin: '79847324987',
tinType: 'U'
},
dataType: 'json',
success: function(result) {
alert(result);
},
error: function (restul) {
alert(result);
}
});
});
});
when i try to hit the button the debugging is stopped till Alert, after that i don't see the URL is hitting. Let me know if i am doing any wrong?
I am able to get the response now. Below is the working script
$.ajax({
url: URL,
type: "PUT",
headers: {
'AXT-API-KEY': '48776474-26a6-4d21-8eda-c3a2a14e4ebe'
},
data: JSON.stringify({"name": "SupplierName, LLC","tin": "522323454","tinType": "U","checks": "DT"
}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr);
alert(thrownError);
}
});
It worked when i use the key in beforeSend function. But i am not sure the difference.
beforeSend: function (xhr) {
xhr.setRequestHeader("AXT-API-KEY': '48776474-26a6-4d21-8eda-c3a2a14e4ebe");

ASP.net MVC unable to get value back from Controller

in my ASP.net MVC application, I have a button that call a controller action which takes longer (>60 mins) to complete. To keep my session alive I am using setInterval function.
reference: http://www.dotnetcurry.com/ShowArticle.aspx?ID=453&AspxAutoDetectCookieSupport=1
view looks like:
#Html.DevExpress().Button(settings =>
{
settings.Name = "LoadData";
settings.Text = "Load Data";
settings.ClientSideEvents.Click = string.Format("function(s, e) {{ OnButtonClick(s, e, '{0}', '{1}'); }}", Url.Action("Start", "ImportData", null), Url.Action("alive", "ImportData", null));
settings.UseSubmitBehavior = false;
}).GetHtml()
my OnButtonClick Function looks:
function OnButtonClick(s, e, startUrl, progressUrl) {
//debugger;
StartActionOnServer(startUrl);
setInterval(keepalive, 600000); //every 10 minutes.
}
Keep Alive looks like:
function keepalive()
{
console.log("I am alive");
$.ajax({
type: 'POST',
url: '/ImportData/alive',
dataType: "text",
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (msg) {
debugger;
console.log("pinging");
},
Error: function (xhr) {
debugger;
alert(xhr)
},
});
}
my issue is that code is not hitting my Controller function, as result I never get result back in my success block.
success: function (msg) {
debugger;
console.log("pinging");
},
Controller action function:
[HttpPost]
public ActionResult alive()
{
var result = "Still Alive";
return Content(result);
}
Instead of me hardcoding: console.log("I am alive"); I would like Controller to return this.
my console.log looks like attached screeshot
Any idea how to get value from Controller ?What am I doing wrong here.
Thanks.
This solved my issue:
function keepalive()
{
console.log("I am alive");
$.ajax({
type: 'POST',
url: '/ImportData/alive',
dataType: "text",
contentType: "text",
success: function (msg) {
console.log(msg);
},
Error: function (xhr) {
alert(xhr)
},
});
}

Autocomplete with Ajax returns No HTTP resource was found that matches the request URI

I am trying to implement an autocomplete on my textbox with data that comes from a web method. The webmethod works on the browser like:
http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?SearchString=e
and these are the results:
[{"IssuerID":1,"Name":"test tester","ChequeAccountNumber":"12345678","CurrencyCode":"EUR"}]
Now, I am trying to add on the textbox the Name data from the response but I'm getting an error in the function below:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers?{ 'SearchString': 'e'}'.","MessageDetail":"No action was found on the controller 'ModuleTask' that matches the request."}
Below, my AJAX call seems to fail for a reason, which I believe comes from passing wrongly the parameters. I do not have experience with ajax so far, so your input will be great.
<script type="text/javascript">
$(function () {
$("[id$=TextBox1]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>',
data: "{ 'SearchString': '" + request.term + "'}",
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfIssuerID]").val(i.item.val);
},
minLength: 1
});
});
</script>
My web method:
public class ModuleTaskController : DnnApiController
{
[AllowAnonymous()]
[HttpGet()]
public HttpResponseMessage GetIssuers(string SearchString)
{
try {
List<Issuers> listIssuers = new List<Issuers>();
IssuersController ic = new IssuersController();
listIssuers = ic.GetIssuers(10, SearchString);
return Request.CreateResponse(HttpStatusCode.OK, listIssuers.ToJson);
} catch (Exception exc) {
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc);
}
}
}
Any ideas?
EDIT:
$(function () {
$("[id$=TextBox1]").autocomplete({
source: function (request, response) {
var qstring = '?' + jQuery.param({ 'SearchString': request.term });
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>' + qstring,
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("[id$=hfIssuerID]").val(i.item.val);
},
minLength: 1
});
});
Your web method is a GET and accepts a querystring yet your Ajax call is trying to pass a JSON object, which is getting appended to the end of your url. You can see this by reading what the URL actually is, in the error message
There are a bunch of different things you can do. This is just one.
// turn your search object into querystring
var qstring = '?'+ jQuery.param({ 'SearchString': request.term});
// append this querystring to the end of your url
$.ajax({
url: '<%=ResolveUrl("http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers")%>' + qstring ,
// remove data and datatype
type: "GET",
//... etc
Also in this case, it doesn't look like you need the ResolveUrl.
Perhaps try your URL as:
url:'http://localhost/psa/DesktopModules/PsaMain/API/ModuleTask/GetIssuers' + qstring;

Passing arguments in jQuery post to a method in controller

In ASP.NET MVC I was using this script to call a method in controller:
<script>
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: "2",
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});
</script>
and this is the method I call:
public async Task getBookedByUser(string id)
{
BenchesService benchService = new BenchesService();
List<Bench> obj = await benchService.getLastBenchByUser(id);
userBench = obj.ElementAt(0);
}
My problem is that id in my controller method is null. It doesn't assume the value "2" as I intend.
Any idea why?
You're almost there. You need to setup the JSON to include your id property:
$.ajax({
url: '#Url.Action("getBookedByUser", "Home")',
data: { id: '2' },
dataType: "html",
success: function (data) {
$('#someElement').html(data); // add the returned html to the DOM
console.log(data);
},
});

my jquery showing this error?

I am trying to get list of user data from a web service file which is called via AJAX. Here is my code :
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
var param;
var resultarr;
$(document).ready(function () {
param = document.getElementById('MainCT_dtvJobVac_PIC').value;
// Load countries then initialize plugin:
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: '{keyword:' + JSON.stringify(param) + '}',
dataType: 'json',
url: 'SvcADUser.asmx/GetADUserList',
success: function (result) {
//alert(result.d)
resultarr = result.d;
}
})
// Initialize autocomplete with local lookup:
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
});
</script>
resultarr will output an array with this values :
[ "Administrator", "Guest", "krbtgt", "phendy" , "Genin" , "Hendra" , "andri" ]
It throws this:
TypeError: this.source is not a function [Break On This Error]
this.source( { term: value }, this._response() );
What do I need to fix here? I am struggling on this for 2 days, some help would be appreciated.
Move the autocomplete initialization inside the ajax success callback:
success: function (result) {
//alert(result.d)
resultarr = result.d;
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
}
Ajax calls are asynchronous. Lets examine your code:
$.ajax({ .... } ); // (1)
$('#MainCT_dtvJobVac_PIC').autocomplete({ ... } ) // (2)
The autocomplete initialization (2) occurs after calling the service (1), but it is unclear if the AJAX request has succeeded and returned the response. There is a great chance that you are initializing the autocomplete with empty or undefined data - when the connection is slow, or it fails for some reason, the success callback might not get executed at the point of setting the autocomplete (2). The correct way to do this is to initialize the autocomplete in the AJAX callback, because then the response data is guaranteed to be present:
$.ajax({
type: 'POST',
contentType: 'application/json;',
data: '{keyword:' + JSON.stringify(param) + '}',
dataType: 'json',
url: 'SvcADUser.asmx/GetADUserList',
success: function (result) {
resultarr = result.d;
$('#MainCT_dtvJobVac_PIC').autocomplete({
source: resultarr
});
}
})

Categories

Resources