Get database record using AJAX, Knockout and JSON - ajax

I am fairly new to Knockout and Entity Framework and I have a problem where I cannot seem to output any JSON from an MVC 4 controller action via an AJAX call using Knockout onto an html page.
The table includes fields Email and RegsitrationNumber, these are used to validate the user.
If the user exists in the table then their country is displayed on the screen.
The profiler states a Status Code of 200 i.e OK. Can anyone help?
HTML ------
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="./Scripts/jquery-1.8.2.min.js"></script>
</head>
<body>
<div>
<div>
<h2 id="title">Login</h2>
</div>
<div>
<label for="email">Email</label>
<input data-bind="value: $root.Email" type="text" title="Email" />
</div>
<div>
<label for="registrationnumber">Registration Number</label>
<input data-bind="value: $root.RegistrationNumber" type="text" title="RegistrationNumber" />
</div>
<div>
<button data-bind="click: $root.login">Login</button>
</div>
</div>
<table id="products1" data-bind="visible: User().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
<script src="./Scripts/knockout-2.2.0.js"></script>
<script src="./Scripts/knockout-2.2.0.debug.js"></script>
<script src="./Scripts/functions.js"></script>
</body>
</html>
JAVASCRIPT -----
function UserViewModel() {
//Make the self as 'this' reference
var self = this;
//Declare observable which will be bind with UI
self.Name = ko.observable("Robbie");
self.Email = ko.observable("rob#test.com");
self.Occupation = ko.observable("Designer");
self.Country = ko.observable("UK");
self.RegistrationNumber = ko.observable("R009");
self.UserDate = ko.observable("06-04-2014");
var User = {
Name: self.Name,
Email: self.Email,
Occupation: self.Occupation,
Country: self.Country,
RegistrationNumber: self.RegistrationNumber,
UserDate: self.UserDate
};
self.User = ko.observable(); //user
self.Users = ko.observableArray(); // list of users
//Login
self.login = function ()
{
alert("login");
if (User.Email() != "" && User.RegistrationNumber() != "") {
$.ajax({
url: '/Admin/Login',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(User),
success: function (data) {
self.Users.push(data);
$('#title').html(data.Email);
}
}).fail(
function (xhr, textStatus, err) {
console.log('fail');
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
} else {
alert('Please enter an email and registration number');
}
};
}
var viewModel = new UserViewModel();
ko.applyBindings(viewModel);
ACTION -----
public ActionResult Login(string Email, string RegistrationNumber)
{
var user = from s in db.Users
select s;
user = user.Where(s => s.Email.ToUpper().Equals(Email.ToUpper())
&& s.RegistrationNumber.ToUpper().Equals(RegistrationNumber.ToUpper())
);
if (user == null)
{
return HttpNotFound();
}
return Json(user, JsonRequestBehavior.AllowGet);
}

Looks like your binding is incorrect...
<table id="products1" data-bind="visible: Users().length > 0">
<thead>
<tr>
<th>Country</th>
</tr>
</thead>
<tbody data-bind="foreach: Users">
<tr>
<td data-bind="text: Country"></td>
</tr>
</tbody>
</table>
User().length should be Users().length.

Related

How can I refresh my partial view on my parent index after a modal update to add new information?

I am certain this question has been asked before, I don't think there is anything unique about my situation but let me explain. I have my Index View (Parent), on that Index View there is a partial View Dataset Contacts "links" (child), I have an Add Contact button, which pops a Modal and allows me to submit the form data to add to the database, when I return I want to only refresh the partial view of links. Note: the Controller Action Dataset_Contacts below needs to fire in order to refresh the partial view (child). It might go without saying, but I don't see this happening with my current code. Any assistance will be appreciated.
on my Index View index.cshtml I have the following code to render my partial View
<div class="section_container2">
#{ Html.RenderAction("Dataset_Contacts", "Home"); }
</div>
Here is the controller:
[ChildActionOnly]
public ActionResult Dataset_Contacts()
{
// Retrieve contacts in the Dataset (Contact)
//Hosted web API REST Service base url
string Baseurl = "http://localhost:4251/";
var returned = new Dataset_Contact_View();
var dataset = new Dataset();
var contacts = new List<Contact>();
var contact_types = new List<Contact_Type>();
using (var client = new HttpClient())
{
dataset = JsonConvert.DeserializeObject<Dataset>(datasetResponse);
contact_types = JsonConvert.DeserializeObject<List<Contact_Type>>(ContactTypeResponse);
// Set up the UI
var ds_contact = new List<ContactView>();
foreach (Contact c in dataset.Contact)
{
foreach (Contact_Type t in contact_types)
{
if (c.Contact_Type_ID == t.Contact_Type_ID)
{
var cv = new ContactView();
cv.contact_id = c.Contact_ID;
cv.contact_type = t.Description;
returned.Dataset_Contacts.Add(cv);
}
}
}
}
return PartialView(returned);
}
Here is my Partial View Dataset_Contacts.cshtml
#model ResearchDataInventoryWeb.Models.Dataset_Contact_View
<table>
#{
var count = 1;
foreach (var ct in Model.Dataset_Contacts)
{
if (count == 1)
{
#Html.Raw("<tr>")
#Html.Raw("<td>")
<span class="link" style="margin-left:10px;">#ct.contact_type</span>
#Html.Raw("</td>")
count++;
}
else if (count == 2)
{
#Html.Raw("<td>")
<span class="link" style="margin-left:300px;">#ct.contact_type</span>
#Html.Raw("</td>")
#Html.Raw("</tr>")
count = 1;
}
}
}
</table>
Also on my Index.cshtml is my Add Contact button, which pops a modal
<div style="float:right;">
<span class="link" style="padding-right:5px;">Add</span>
</div>
jquery for the Modal:
var AddContact = function () {
var url = "../Home/AddContact"
$("#myModalBody").load(url, function () {
$("#myModal").modal("show");
})
};
Controller action for AddContact
public ActionResult AddContact()
{
return PartialView();
}
Modal for AddContact.cshtml
#model ResearchDataInventoryWeb.Models.Contact
<form id="contactForm1">
<div class="section_header2">Contact</div>
<div style="padding-top:5px;">
<table>
<tr>
<td>
<span class="display-label">UCID/Booth ID</span>
</td>
<td>
#Html.TextBoxFor(model => model.Booth_UCID, new { placeholder = "<Booth/UCID>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Type</span>
</td>
<td>
<select class="input-box" id="contact_type">
<option value="contact_type">Contact Type*</option>
<option value="dataset_admin">Dataset Admin</option>
<option value="dataset_Provider">Dataset Provider</option>
<option value="department">Department</option>
<option value="external_collaborator">External Collaborator</option>
<option value="principal_investigator">Principal Investigator</option>
<option value="research_center">Research Center</option>
<option value="vendor">Vendor</option>
</select>
</td>
</tr>
<tr>
<td>
<span class="display-label">Name</span>
</td>
<td>
#Html.TextBoxFor(model => model.First_Name, new { placeholder = "<First Name>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Last_Name, new { placeholder = "<Last Name>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Email</span>
</td>
<td>
#Html.TextBoxFor(model => model.Email, new { placeholder = "<Email 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Email_2, new { placeholder = "<Email 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Phone</span>
</td>
<td>
#Html.TextBoxFor(model => model.Phone_Number, new { placeholder = "<Phone 1>", #class = "input-box-modal" })
#Html.TextBoxFor(model => model.Phone_Number_2, new { placeholder = "<Phone 2>", #class = "input-box-modal" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Job Title</span>
</td>
<td>
#Html.TextBoxFor(model => model.Title_Role, new { placeholder = "<Job Title>", #class = "input-box" })
</td>
</tr>
<tr>
<td>
<span class="display-label">Organization</span>
</td>
<td>
<input class="input-box" type="text" placeholder="<Organization>" />
</td>
</tr>
</table>
<div style="padding-left:10px; margin-top:10px;">
<textarea rows="3" placeholder="Notes"></textarea>
</div>
</div>
<div class="centerButton" style="margin-top: 30px;">
<div style="margin-left:30px">
<submit id="btnSubmit" class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">SAVE</span></submit>
</div>
<div style="margin-left:30px">
<submit class="btn btn-default btn-sm" style="padding:14px"><span class="smallText_red" style="padding:30px">REMOVE</span></submit>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
var frm = $('#contactForm1').serialize()
$.ajax({
type: "POST",
url: "/Home/AddContact/",
data: frm,
success: function () {
$("#myModal").modal("hide");
}
})
})
})
</script>
and lastly Action for [HttpPost] AddContact(Contact data)
[HttpPost]
public ActionResult AddContact(Contact data)
{
// Update the Database here
return View();
}
My solution:
1. Change ActionResult to JsonResult
{
// Update the Database code
// END
return Json(new
{
dbUpdateResult = "success"
});
}
2. In Ajax:
//Ajax code
...
success: function (ajaxRespond) {
if(ajaxRespond.dbUpdateResult == "success"){
$("#myModal").modal("hide");
reloadTable()
}
}
Then you can use 1:
function reloadTable(){
$('#CONTAINER_ID').load('#Url.Action("Dataset_Contacts", "Home")');
}
Or 2:
function reloadTable(){
let myurl = '#Url.Action("Dataset_Contacts", "Home")';
$.ajax({
type: "GET",
url: myurl,
success: function (data, textStatus, jqXHR) {
$("#CONTAINER_ID").html(data);
},
error: function (requestObject, error, errorThrown) {
console.log(requestObject, error, errorThrown);
alert("Error: can not update table")
}
});
}
So you reload your partial view after successful dbupdate. Please tell me, if I'm wrong...

i want to convert my gridview table into pdf

**when i tried to convert my grid-view data into PDF i got null reference exception grid-view header row but data is available in grid view.please help me to solve this error. i am using asp.net web API in this.. and i tried to on another grid-view to bind data..it shows same error null reference exception but when i tried on direct button click it works fine..only it shows error when i tried on using web API..please help me to solve this
i have attached my programming below data load and bind
public void GetData()
{
string conn = ConfigurationManager.ConnectionStrings["con"].ToString();
SqlConnection con = new SqlConnection(conn);
con.Open();
SqlCommand cmd = new SqlCommand("select * from api", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "api");
//DataTable dta = new DataTable();
//dta = ds.Tables["api"];
//da.Fill(dta);
GridView2.DataSource = ds;
GridView2.DataBind();
}
convert to pdf
public string Button3_Click()
{
PdfPTable pdfTable = new PdfPTable(GridView2.HeaderRow.Cells.Count);
foreach (TableCell headercell in GridView2.HeaderRow.Cells)
{
iTextSharp.text.Font font = new iTextSharp.text.Font();
font.Color = new Basecolor(GridView2.HeaderRow.ForeColor);
PdfPCell pdfcell = new PdfPCell(new Phrase(headercell.Text, font));
pdfcell.BackgroundColor = new Basecolor(GridView2.HeaderStyle.BackColor);
pdfTable.AddCell(pdfcell);
}
foreach (GridViewRow gridviewrow in GridView2.Rows)
{
foreach (TableCell tablecell in gridviewrow.Cells)
{
iTextSharp.text.Font font = new iTextSharp.text.Font();
font.Color = new Basecolor(GridView2.RowStyle.ForeColor);
PdfPCell pdfcell = new PdfPCell(new Phrase(tablecell.Text));
pdfcell.BackgroundColor = new Basecolor(GridView2.RowStyle.BackColor);
pdfTable.AddCell(pdfcell);
}
}
Document pdfdoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
pdfdoc.Open();
pdfdoc.Add(pdfTable);
pdfdoc.Close();
Response.ContentType = "application/pdf";
Response.AppendHeader("content-disposition", "attachment;filename=Employyes.pdf");
Response.Write(pdfdoc);
Response.Flush();
Response.End();
return "success";
}
ajax function call
$(document).ready(function () {
$("#Button2").click(function () {
alert("ajax call");
$.ajax
({
method: "GET",
url: "api/Employees",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("success");
},
error: function (responce) {
alert("error");
},
});
});
});
<asp:Button ID="Button1" runat="server" Style="width: 136px" Text="Export to Excel" Width="175px" />&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
<asp:Button ID="Button2" runat="server" Text="Export to PDF" Width="175px" />
<br />
<br />
<div class="auto-style1" id="NewData">
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="true">
</asp:GridView>
</div>
here is my controller class
public class EmployeesController : ApiController
{
// success s = new success();
BusinessLogicLayer bal = new BusinessLogicLayer();
public string Get(string username, string password)
{
return bal.login(username, password);
}
[System.Web.Mvc.HttpPost]
public string POST(string firstname, string lastname, string username, string password, string email)
{
return bal.Register(firstname, lastname, username, password, email);
}
[System.Web.Http.HttpGet]
public string buttonclick()
{
// MessageBox.Show("come");
return bal.ExportConvert();
}
here is my business logic layer class method
public string ExportConvert()
{
success s = new success();
return s.Button3_Click();
}[enter image description here][1]
here my login page code
**<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
<link href="Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body style="padding-top:20px;">
<div class="col-md-10 col-md-offset-1">
<div class="well">
<table class="table table-bordered">
<thead>
<tr class="success">
<th colspan="2">
Existing User Login
<a class="btn btn-success pull-right" href="Registration.html">Register</a>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>UserName</td>
<td>
<input type="text" id="username" placeholder="username"/>
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" id="password" placeholder="Password" />
</td>
</tr>
<tr class="success">
<td colspan="2">
<input type="button" id="btnlogin" class="btn btn-success" value="login" />
</td>
</tr>
</tbody>
</table>
<div class="modal fade" tabindex="-1" id="successmodel"
data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal">
×
</button>
<h4>Success</h4>
</div>
<div class="modal-body">
<h2>Registraton success</h2>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn btn-success">
Close
</button>
</div>
</div>
</div>
</div>
<div id="divError" class="alert alert-danger collapse">
<a id="linkClose" class="close" href="#" >×</a>
<div id="divErrorText"></div>
</div>
</div>
<script src="Scripts/jquery-1.10.2.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script type="text/javascript" >
$(document).ready(function () {
$('#linkClose').click(function () {
$('divError').hide('fade');
})
});
$('#btnlogin').click(function () {
$.ajax({
url: '/api/Employees/?username=' + $("#username").val() + '&password=' + $("#password").val(),
method: 'Get',
contentType: 'application/json',
data: { id: 1 },
dataType: 'json',
success: function (data) {
console.log(data);
//var data = data.d;
//alert("success " + data);
if (data == 'success') {
window.location = "/success.aspx";
}
else {
alert("Wrong Username and Password");
}
/* if (data != null) {
$.each(data, function (i, obj) {
var c = new WorkflowsEntity(data[i]); //logic
self.WorkflowList.push;
});
alert("success");
//window.location.href = "/success.html";
}*/
},
error: function (jqXHR, textStatus, errorThrown) {
alert(" un correct username password ");
$('#divErrorText').text(jqXHR.responceText);
$('#divError').show('fade');
}
});
});
</script>
</body>
</html>**

insert Using ajax But page refreshing on submit why?

Controller code I have :
<?php
class Ajax_cntrl extends CI_controller{
public function index(){
$this->load->view('ajax_view');
$insert = array(
'name' => $this->input->post('name'),//<-- also not able to get this id from ajax post request
'pass' => $this->input->post('pass'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'address' => $this->input->post('address'),
);
$this->db->insert('form',$insert);//<--insert item into cart
$query;// to insert into database
//redirect('shop');
}
}
?>
view code I have ::
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<title></title>
</head>
<body>
<form action="" method="post">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>Pass</td>
<td><input type="password" name="pass" id="pass"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="mobile" id="mobile"></td>
</tr>
<tr>
<td>Address</td>
<td><input type="text" name="address" id="address"></td>
</tr>
<tr>
<td><input type="submit" name="submit" id="submit"></td>
</tr>
</table>
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var form_data = { //repair
id: id,
name: $('#name_' + id).val(),
pass: $('#pass' + id).val(),
email: $('#email' + id).val(),
mobile: $('#email' + id).val(),
address: $('#email' + id).val()
};
$.ajax({
type:'post',
url:"<?php echo site_url('ajax_cntrl/index'); ?>",
data: form_data, // $(this).serialize(); you can use this too
success: function(msg) {
alert("success..!! ");
}
});
return false;
});
</script>
problem is that when i am submitting the form it refreshing the browser ajax not working where is the fault m not able to understand please help me related in this why ajax call is not working there and is that a gud way to implement ajax with codeigniter ?? if yes then y its not working
Use below code, this will fix your issue.
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var form_data = {//repair
name: $('#name').val(),
pass: $('#pass').val(),
email: $('#email').val(),
mobile: $('#mobile').val(),
address: $('#address').val()
};
$.ajax({
type: 'post',
url: "<?php echo site_url('ajax_cntrl/index'); ?>",
data: form_data,
dataType: 'json',
success: function(msg) {
alert("success..!! ");
}
});
return false;
});
});
</script>
Let me know if it not works for you.

Display Data Got From JSON In Reactjs In Table

Here I wrote A code which fetches data from API http://fcctop100.herokuapp.com/api/fccusers/top/recent and displays Data in Form Of Table Which Looks Like Below In My Case As You Can See is Repeating For Every
But I want To Make It Look Like
Here Is What I Did So Far
var MainBox = React.createClass({
render:function(){
return(
<App/>
);
}
});
var App = React.createClass({
//setting up initial state
getInitialState:function(){
return{
data:[]
};
},
componentDidMount(){
this.getDataFromServer('http://fcctop100.herokuapp.com/api/fccusers/top/recent');
},
//showResult Method
showResult: function(response) {
this.setState({
data: response
});
},
//making ajax call to get data from server
getDataFromServer:function(URL){
$.ajax({
type:"GET",
dataType:"json",
url:URL,
success: function(response) {
this.showResult(response);
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render:function(){
return(
<div>
<Result result={this.state.data}/>
</div>
);
}
});
var Result = React.createClass({
render:function(){
var result = this.props.result.map(function(result,index){
return <ResultItem key={index} user={ result } />
});
return(
<div>
{result}
</div>
);
}
});
var ResultItem = React.createClass({
render:function(){
var camper = this.props.user;
return(
<div className="row">
<div className="col-md-12">
<table className="table table-bordered">
<thead>
<tr>
<th className="col-md-4">UserName</th>
<th >Points In Last 30 Days</th>
<th>Points All Time</th>
</tr>
</thead>
<tbody>
<tr >
<td>{camper.username}</td>
<td>{camper.recent}</td>
<td>{camper.alltime}</td>
</tr>
</tbody>
</table>
</div>
</div>
);
}
});
ReactDOM.render(
<MainBox />,
document.querySelector("#app")
);
<!DOCTYPE html>
<head>
<meta charset="UTF-8" />
<title>React Tutorial</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<div id="app"></div>
<script src="demo.js" type="text/babel"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.7/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.3.2/marked.min.js"></script>
</body>
</html>
The following should list all your items as a single row in your table, and only give you one table. One tip is to not use the index as the key for your map function. It's better to use some natural key or identifier in your result, some kind of id that will enable React better comparison of the components. A blog post describing this and some documentation.
var Result = React.createClass({
render:function(){
var result = this.props.result.map(function(result,index){
return <ResultItem key={index} user={ result } />
});
return(
<div className="row">
<div className="col-md-12">
<table className="table table-bordered">
<thead>
<tr>
<th className="col-md-4">UserName</th>
<th >Points In Last 30 Days</th>
<th>Points All Time</th>
</tr>
</thead>
<tbody>
{result}
</tbody>
</table>
</div>
</div>
);
}
});
var ResultItem = React.createClass({
render:function(){
var camper = this.props.user;
return(
<tr >
<td>{camper.username}</td>
<td>{camper.recent}</td>
<td>{camper.alltime}</td>
</tr>
);
}
});

Ajax call not working on datatables pages,except first page

i am using datatables.And on the table there is button on each row.
When I click on the trash button,ajax works only for the first 10 row.
But when I move on to next pages it does not work anymore.
Here is my table code:
<script type="text/javascript" language="javascript" src="//cdn.datatables.net/plug-ins/725b2a2115b/integration/bootstrap/3/dataTables.bootstrap.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable();
} );
</script>
<table id="example" class="table table-bordered">
<thead>
<tr>
<th class="success">Id</th>
<th class="success">Image</th>
<th class="success">Title</th>
<th class="success">Action</th>
</tr>
</thead>
<tbody>
<?php
$query = mysqli_query($connect,"SELECT * FROM movie");
while ($result = mysqli_fetch_row($query)){
echo'
<tr>
<td>'.$result[0].'</td>
<td><img class="img-responsive" style="max-height:50px;" src="'.$result[5].'"></td>
<td>'.$result[1].'</td>
<td>
<div class="btn-group" data-toggle="buttons">
<label id="remID" class="btn btn-sm btn-default">
<span class="text-danger glyphicon glyphicon-trash"></span>
</label>
<label class="btn btn-sm btn-default">
<span class="text-primary glyphicon glyphicon-edit"></span>
</label>
</div>
</td>
</tr>
';
echo'
<script>
$(document).ready(function(){
$("#remID").click(function(){
$.post("remMovie.php",
{
id:"'.$result[0].'"
},
function(data,status){
alert(status);
});
});
});
</script>
';
}
?>
</tbody>
</table>
Here is my PHP part of ajax action:
<?php
include('adminchk.php');
include('config.php');
$movieID = $_POST['id'];
$query = mysqli_query($connect,"DELETE from movie where id='$movieID'");
if ($query){
echo"movie deleted";
}
else {
echo"ERROR!";
}
?>
I dont know why this is happening.I want the trash button to work for every row of datatable.
To execute any Code after the Data Table has been paginated (basically redrawn), you need to add fnDrawCallback function inside .dataTabale() method. All codes written inside the Callback function will work after the table has been redrawn. Here is an example...
$(document).ready( function() {
$('#example').dataTable({
"fnDrawCallback": function( oSettings ) {
// Write any code (also ajax code that you want to execute)
// that you want to be executed after
// the table has been redrawn
}
});
});
You should try something like fnDrawCallback event.
Here is the doc : http://legacy.datatables.net/usage/callbacks#fnDrawCallback
When the datable change, you bind the buttons with the function you want.
JS :
$(document).ready( function() {
$('#example').dataTable( {
"fnDrawCallback": function( oSettings ) {
alert( 'DataTables has redrawn the table' );
}
} );
} );

Resources