This is my first time using Jquery datatable.
I don't know what's wrong with my code, but the data won't load into the datatable.
Here's the script:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "TestDPRDetail.aspx/GetdtbScenario",
contentType: "application/json;charset=utf-8",
datatype: "json",
success: function (data) {
$('#grvScenario').dataTable({
data: data,
columns:
[
{ "data": "SCENARIO_ID" }
]
});
},
});
});
The url: TestDPRDetail.aspx/GetdtbScenario returns a datatable json serialized object
<System.Web.Script.Services.ScriptMethod()> _
<WebMethod()> _
Public Shared Function GetdtbScenario() As Object
Dim dtbScenarioTemp As New DataTable
Dim strDPR_ID As String
Dim clsScenarioBusiness As New ScenarioBusiness
Dim json As Newtonsoft.Json.JsonConvert
strDPR_ID = "DPR-201807-00001"
dtbScenarioTemp = clsScenarioBusiness.GetdtbScenario(strDPR_ID) 'getting data from sql
Return json.SerializeObject(dtbScenarioTemp)
End Function
I checked with a normal method (using array object) to load the datatable, it works fine:
var dataTemp = [{ "SCENARIO_ID": "SCN-201807-00008", "SCENARIO #": "B", "SCENARIO NAME": "Test Inquiry", "CONDITION": "Negative" }]
$('#grvScenario').dataTable({
data: dataTemp,
columns: [
{"data":"SCENARIO_ID"}
]
});
Here's the HTML:
<body>
<form id="form1" runat="server">
<div>
<table id="grvScenario">
<thead>
<tr>
<th>Scenario ID</th>
</tr>
</thead>
</table>
</div>
</form>
</body>
Is there something i missed from the ajax or datatable?
Try to initialize datatables first:
$(document).ready(function () {
$('#grvScenario').dataTable({
ajax: "TestDPRDetail.aspx/GetdtbScenario",
columns: [
{ "data": "SCENARIO_ID" }
]
})
});
After some trial and error, i've got my answer
It seems that TestDPRDetail.aspx/GetdtbScenario was returning a different json object after ajax call.
The return variable (data) needs to be parsed again in javascript. So it will look like this:
$.ajax({
type: "POST",
url: "TestDPRDetail.aspx/GetdtbScenario",
contentType: "application/json;charset=utf-8",
datatype: "json",
success: function (data) {
$('#grvScenario').dataTable({
data: JSON.parse(data.d),
columns:
[
{ "data": "SCENARIO_ID" }
]
});
},
});
Hope it will help anyone having the same issue
Related
I can add the data to the database correctly, but Ajax success function is not working. I always get the error function :
View:
<div id="dvform">
<!-- some data-->
<input type="submit" value="submit" id="btnsubmit" />
</div>
<script>
$(document).ready(function () {
$("#btnsubmit").click(function () {
addAppointment();
});
});
function addAppointment (){
$.ajax({
type: 'POST',
url: '/FuelerAppointments/Create',
contentType: 'application/json; charset=utf-8',
dataType: "html",
data: $("dvform").val(),
success: function (data) {
swal("Done!", "The appointment was saved successfully!", "success");
},
error: function (data) {
swal("Error deleting!", "Please try again", "error");
},
});
}
Controller :
[HttpPost]
public ActionResult Create(FuelerAppointment fuelerAppointment)
{
return Json(fuelerAppointment, JsonRequestBehavior.AllowGet);
}
First you should change dataType: "html", to dataType: "json",
and create FuelerAppointment object before the $.ajax():
var fuelerAppointment = {};
fuelerAppointment.Name = $("#Name").val();
and then the data in ajax method
data: '{fuelerAppointment: ' + JSON.stringify(fuelerAppointment) + '}',
For more information check this link Using AJAX In ASP.NET MVC
change dataType: "html" to dataType: "json"
and in data properties should you write like this
var model = {
prop1: prop1Value,
prop2: prop2Value,
...
};
data: {fuelerAppointment: model}
Or
data: JSON.stringify({
fuelerAppointment: {
prop1: prop1Value,
prop2: prop2Value,
...
}
})
Notes: the fuelerAppointment object should behave a sem proprieties in C# class
I want to access to my button inside datatable which is inside of my modal, but when I want to access it wont load any alert , ajax url or whatever thing even If I change id or class of "a" tag. how can I fix it? this ajax I know it wont load and error in console, but it also show it..
ajax
$(function(event) {
URL_GET_VIEW_SEARCH_PRODUCT = BASE_URL + 'sale/sales/getViewSearch';
URL_GET_DATATABLE = BASE_URL + 'sale/sales/datatable';
URL_SEARCH_PRODUCT = BASE_URL + 'sale/sales/search_product';
$('#btn-search').click(function (e) {
BootstrapDialog.show({
title: 'Search Product',
message: function(dialog) {
var $message = $('<div></div>');
var pageToLoad = dialog.getData('pageToLoad');
$message.load(pageToLoad);
return $message;
},
data: {
pageToLoad: URL_GET_VIEW_SEARCH_PRODUCT
},
onshown: function(dialog){
$('#example').DataTable({
lengthChange: false,
responsive: true,
ajax: {
url: URL_GET_DATATABLE,
type: 'POST',
},
columnDefs: [{
targets: 4,
data: null,
defaultContent: "<a href='#'><span class='glyphicon glyphicon-plus'></span></a>"
}],
});
}
});
});
$('#search').typeahead({
source: function (query,process) {
$.ajax({
url: URL_SEARCH_PRODUCT,
type: 'POST',
data: {query: query},
dataType: 'json',
async: true,
success: function (data) {
console.log(data);
process(data);
}
});
}
});
$('#example tbody').on('click', 'a', function(event) {
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
});
});
table view
<table id="example" class="table table-bordered table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th>Code</th>
<th>Description</th>
<th>Stock</th>
<th>Price</th>
<th></th>
</tr>
</thead>
</table>
Been plenty of questions about this but I never found one that worked for me. I have a plain and simple HTML table whos body is being filled with rows from an AJAX call.
Then I want to update the table with DataTable plugin but it does not work.
I have a HTML table that looks like this:
<table id="myTable">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
In my jQuery pageload
$(document).ready(function(){
var oTable = $('#myTable').dataTable({
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
And finally my on dropdownlist change function
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
var oTable = $('#myTable').dataTable(); // Nothing happens
var oTable = $('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
The append and so on has been modified to shorten it down, etc so do not focus too much on it.
Basically the question is how to update the table, I can do my AJAX and add new data to the table fine, but the datatable plugin does not update with it.
I've tried other things like
.fnDraw(false);
But it does nothing
While I get an JSON error from
fnReloadAjax()
Any clues on just how to refresh the table?
Try this
Initially you initialized the table so first clear that table
$('#myTable').dataTable().fnDestroy();
Then initialize again after ajax success
$('#myTable').dataTable();
Like this
$("#dropdownlist").on("change", function () {
$("tbody").empty();
$.ajax({
type: "POST",
url: "#Url.Action("ActionHere", "Controller")",
dataType: "json",
success: function (data) {
$.each(data, function (key, item) {
$("tbody").append("<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>");
});
}
})
$('#myTable').dataTable().fnDestroy();
$('#myTable').dataTable({ // Cannot initialize it again error
"aoColumns": [
{ "bSortable": false },
null, null, null, null
]
});
});
DEMO
I Know this is an old post, but I've just investigated about the problem and I find the easiest way to solve it in DataTable man pages: https://datatables.net/reference/api/ajax.reload%28%29
All you need to call table.ajax.reload();
var table = $('#product_table').DataTable({
"bProcessing": true,
"serverSide": true,
responsive: true,
"ajax": {
url: get_base_url + "product_table", // json datasource
type: "post", // type of method ,GET/POST/DELETE
error: function () {
$("#employee_grid_processing").css("display", "none");
}
}
});
//call this funtion
$(document).on('click', '#view_product', function () {
table.ajax.reload();
});
I had done something that relates to this... Below is a sample javascript with what you need. There is a demo on this here: http://codersfolder.com/2016/07/crud-with-php-mysqli-bootstrap-datatables-jquery-plugin/
//global the manage member table
var manageMemberTable;
function updateMember(id = null) {
if(id) {
// click on update button
$("#updatebutton").unbind('click').bind('click', function() {
$.ajax({
url: 'webdesign_action/update.php',
type: 'post',
data: {member_id : id},
dataType: 'json',
success:function(response) {
if(response.success == true) {
$(".removeMessages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
} else {
$(".removeMessages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>'+
'<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
'</div>');
// refresh the table
manageMemberTable.ajax.reload();
// close the modal
$("#updateModal").modal('hide');
}
}
});
}); // click remove btn
} else {
alert('Error: Refresh the page again');
}
}
From version 1.10.0 onwards you can use ajax.reload() api.
var table = $('#myTable').DataTable();
table.ajax.reload();
Keep in mind to use $('#myTable').DataTable() and not
$('#myTable').dataTable()
I have a view
#using staffInfoDetails.Models
#model staffInfo
<link href="../../Content/myOwn.css" rel="stylesheet" type="text/css" />
#{staffInfo stf = Model;
}
<div id="education1">
#using (Html.BeginForm("addNewEdu","Home",FormMethod.Post))
{
#Html.HiddenFor(x=>x.StaffId)
<table>
<tr>
<th>Country</th>
<th>Board</th>
<th>Level</th>
<th>PassedYear</th>
<th>Division</th>
</tr>
<tr>
#Html.EditorFor(x => x.eduList)
</tr>
<tr>
#*<td><input type="submit" value="create Another" id="addedu"/> </td>*#
#*<td>#Html.ActionLink("Add New", "addNewEdu", new { Model })</td>*#
</tr>
</table>
}
<button id="addedu">Add Another</button>
</div>
I want to pass the model staffInfo to controller using jquery as below
<script type="text/javascript">
$(document).ready(function () {
$("#addedu").live('click', function (e) {
// e.preventDefault();
$.ajax({
url: "Home/addNewEdu",
type: "Post",
data: { model: stf },//pass model
success: function (fk) {
// alert("value passed");
$("#education").html(fk);
}
});
});
});
</script>
the jquery seems to pass only elements not whole model so how can I pass model from the view to the controller so that I don't have to write the whole parameters list in jquery
u can give ID to the form by using this
#using (Html.BeginForm("addNewEdu", "Home", FormMethod.Post, new { id = "addNewEduForm" }))
{
}
Then in the script
<script type="text/javascript">
$('#addedu').click(function(e) {
e.preventDefault();
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: $("#addNewEduForm").serialize(),
success: function(data) {
}
});
}
});
</script>
As I can see you trying to submit form with AJAX? Look at serialize function.
$('#addedu').click(function(e) {
e.preventDefault();
var form = $('form');
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(r) {
}
});
}
});
You can get your values with getElementById then send your action:
$(document).ready(function () {
var select = document.getElementById('...');
$.ajax({
type: "get",
url: "get_street_name",
data: { a: select },
success: function (data) {
$('#result').html(data);
}
});
}
I have a site i'm working on and i'm trying to make an ajax request to a controller (codeigniter framework). I see in firebug that my controller is receiving my post value just fine but for some reason it is not sending back a response. I've set it up to be VERY simple without a database call at this point just for testing and its still not working. Any ideas?
Here is my form in my view:
<div class="purchaseState">
<input type="text" name="city" id="city" class="grayGrad"/>
</div>
<div>
<ul id="cityResults">
<!-- AJAX results here -->
</ul>
</div>
Here is my controller returning the value:
function citySearch() {
echo '<li>test</li>';
}
Here is my Jquery ajax
//New City Search
$('#city').keyup( function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
}).done(function( data ) {
$('ul#cityResults').append(data);
});
});
you should use ajax success callback:
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});
Please change the url in the AJAX function in the following way.
$('#city').keyup(function() {
var city = $('#city').val();
$.ajax({
type: "POST",
url: "<?php echo base_url; ?>page/citySearch",
data: { city: city },
success: function(data) {
$('ul#cityResults').append(data);
}
});
});