How to add jQuery DataTable in this Javascript - c#

Is it possible to add the following jQuery DataTable?
$('#myDataTable').dataTable({
});
to this query?
$(document).on('click', '#PlayStatisticeight', function (e) {
$.ajax({
url: '#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")',
type: 'GET',
success: function (data) {
$("#PartialViewTopPlayedTracksList").empty();
$("#PartialViewTopPlayedTracksList").append(data);
$('#myDataTable').dataTable({
});
$(function () {
$("#PartialViewTopPlayedTracksList").load('#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")');
});
},
error: function (xhr, textStatus, exceptionThrown) {
var json = $.parseJSON(xhr.responseText);
if (json.Authenticated) {
window.location.href = '/UnAuthorizedUser/UnAuthorizedUser';
}
else {
window.location.href = '/UnAuthenticatedUser/UnAuthenticatedUser';
}
}
});
});
I don't know how and if it is possible to do so? any help is highly appreciated :)

Yes, just call it once the new partial has been added to the DOM, in the success callback function.
success: function (data) {
$.ajax({
url: '#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")',
type: 'GET',
success: function (data) {
$("#PartialViewTopPlayedTracksList").empty();
$("#PartialViewTopPlayedTracksList").append(data);
});
},

you can initialize datatable, after the partialview is appended on the view in the ajax call complete function like this:
success: function (data) {
$.ajax({
url: '#Url.Action("_PartialViewTopPlayedTracksList", "ReportStatistic")',
type: 'GET',
success: function (data) {
$("#PartialViewTopPlayedTracksList").empty();
$("#PartialViewTopPlayedTracksList").append(data);
$('#myDataTable').dataTable({ });
});
}

Related

Ajax not hitting controller method

I have the following jquery function which is sending data to a controller:
function bound(e) {
var ele = document.getElementsByClassName("e-grid")[0]
ele.addEventListener('click', function (e) {
if (e.target.classList.contains('e-up')) {
var grid = document.getElementById('FlatGrid').ej2_instances[0]; //Grid Instance
var rowObj = grid.getRowObjectFromUID(ej.base.closest(e.target, '.e-row').getAttribute('data-uid'));
var data = rowObj.data;
//alert(JSON.stringify(data));
var code = data.ClientCode;
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { "ClientCode": code }, //First item has latest ID
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
}
});
}
And my controller method:
[HttpPost]
public ActionResult ShowClient(string ClientCode)
{
if (ClientCode == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
*action*
}
However I am getting a 500 (Internal Server Error) error for this. Any idea what I am missing cause my method is not being hit at all.
And I can see that var code does have the correct string value.
Remove commas from the parameter name "ClientCode" and contentType and will be work
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { ClientCode: code }, //First item has latest ID
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
The comments have provided you with a combination of suggestions that when put together will give you the desired behavior.
First, you can build the URL in teh view using #Url.Action
url: '#(Url.Action("ShowClient","Client"))',
Next, the object model is not being built correctly
data: { ClientCode: code },
Note the last of quotes around the key.
And finally remove the JSON content type.
Which results to portion of code.
$.ajax({
type: "POST",
url: '#(Url.Action("ShowClient","Client"))',
data: { ClientCode: code },
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
Change the url to this:
url: "../Client/ShowClient"

Posting to WebMethod with ajax error

Step1:
I have defined my script as: on home.aspx page:
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
headers: { "Content-Type": "application/json" },
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Step2:
Call to the script function from button: it's on home.aspx page:
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()" />
Step3:
Defined Web method at home.aspx.cs page:
[System.Web.Services.WebMethod]
public static string GetData(string name)
{
return "Welcome";
}
I am getting:
JavaScript runtime error: Unable to get property 'd' of undefined or
null reference
You have to stringify your data:
data: JSON.stringify({ name: "Mobile" })
And use ajax like this:
$.ajax({ ... });
Full script updated:
function ShowCurrentTime() {
$.ajax({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: JSON.stringify({ name: "Mobile" }),
contentType: "application/json",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);
},
failure: function() {
alert("Fail");
}
});
}
Try this and tell me if it work :
<script type = "text/javascript">
function ShowCurrentTime() {
var post = ({
method: "POST",
url: "home.aspx/GetData",
dataType: 'json',
data: { name: "Mobile" },
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("here" + data.d.toString());
alert(data.d);},
failure: function() {
alert("Fail");}
});
}
</script>

autocompletion in jquery not working

I am using json result to populate the textbox and I can see the values are returned to Razor view using alert. But I am unable to bind them to textbox.
in my layout.cshtml i am loading the jquery files.
![This is in the header section of my layout page][1]
#Styles.Render("~/Content/css")
#Styles.Render("~/Content/jquery-ui")
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/bootstrap")
#Scripts.Render("~/bundles/Site")
This is my index file,
$("#usersearch").change(function () {
//$('#SearchVendorId').val(0);
if ($('#usersearch').val() != "") {
$('#usersearch').addClass("errorTextBox");
$('#usersearch').removeClass("successTextBox");
}
else {
$('#usersearch').removeClass("successTextBox");
$('#usersearch').removeClass("errorTextBox");
}
});
$('#usersearch').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetUsers")',
data: { term: request.term },
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
alert(item.value);
return {
label: item.value,
value: item.value
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
any help is greatly appreciated.
$("#usersearch").change(function () {
//$('#SearchVendorId').val(0);
if ($('#usersearch').val() != "") {
$('#usersearch').addClass("errorTextBox");
$('#usersearch').removeClass("successTextBox");
}
else {
$('#usersearch').removeClass("successTextBox");
$('#usersearch').removeClass("errorTextBox");
}
});
$('#usersearch').autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetUsers")',
data: { term: request.term },
dataType: 'json',
type: 'GET',
async : false,
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
alert(item.value);
return {
label: item.value,
value: item.value
};
}));
},
error: function (xhr, status, error) {
alert(error);
}
});
},
minLength: 2
});
try the async:false in ajax
You haven't posted your data response, but if it is an array of strings, the following should do it.
success: function (data) {
response(data);
},
Since you've already provided the data in the format that it needs (a label and a value), you don't have to map the data. Just pass it directly into the response.

Jquery UI AutoComplete not working with asp.net

This is my Jquery:
$("#completeMe").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Main.aspx/GetAutocomplete",
type: "POST",
dataType: "json",
data: Data,
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return { value: item };
}))
}
})
}
});
This is my Main.aspx.cs:
[System.Web.Services.WebMethod]
public static List<string> GetAutocomplete(string cityName)
{
List<string> City = new List<string>() { "hh", "hh1" };
return City;
}
Now this works when i return string instead of List. But when I use it like this with List I get:
Uncaught TypeError: undefined is not a function jquery-ui.min.js:9...
I don't understand, this solution seem to work to many people on web, maybe it has something to do with my jquery/ui versions? I am using jquery 1.7.1.min and jquery-ui latest version.
Change your success function like this
success: function (data) {
response($.map(data.d, function (item) {
return { value: item };
}))
Data is contained in data.d property.

Ajax call to c# function not working

I'm trying to use Ajax to call a C# function but the call is not working.The script shows the hello message but does not show the success/error message.What am i doing wrong
Java script
<script type="text/javascript">
$(document).ready(function () {
$('#btnsave1').click(function () {
alert("hello");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
success: function () {
alert('Successfully Saved');
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
});
});
C# Method
protected void apply()
{
MessageBox.Show("hi");
}
Try this:
[WebMethod]//write [WebMethod]
public static string apply()//method must be "pulic static" if it is in aspx page
{
return "Hi";
}
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
data:'{}',
success: function (result) {
alert(result);
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
Few things you need to fix here. First: there's no MessageBox in webforms. change the apply() method to return string:
protected string apply()
{
return "hi!";
}
Second: Use '#btnsave1' to '#<%= btnsave1.ClientID %>' to get server generated id for button and also catch the string returned by apply() method. Your script should look like:
<script type="text/javascript">
$(document).ready(function () {
$('#<%= btnsave1.ClientID %>').click(function () {
alert("hello");
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "LeaveSurrender.aspx/apply",
dataType: "json",
success: function (data) {
alert(data);
// window.location.href = "ClubCreation.aspx";
},
Error: function () {
alert('error');
}
});
});
});
</script>
Third: Make sure you have referenced jquery in the head of your page:
<head runat="server">
<script src="Scripts/jquery-1.8.2.js"></script>

Categories