i am using Datatable jquery and i would like to call delete action on every row inside a button ...how can i redirect to action method delete of the controllers User with the right parameter?
var datatableVariable = $('#myTable').DataTable({
....
columns: [
...column definition...{
data: null,
render: function(data, type, row) {
return "<a href='#' class='btn btn-danger' onclick=DeleteData('" + row.id + "'); >Delete</a>";
}
},
],
});
function DeleteData(id) {
if (confirm("Are you sure you want to delete ...?")) {
Delete(id);
} else {
return false;
}
}
function Delete(id) {
var url = '#Url.Content("~/")' + "Users/Delete";
$.post(url, {
ID: id
}, function(data) {
if (data) {
oTable = $('#myTable').DataTable();
oTable.draw();
} else {
alert("Something Went Wrong!");
}
});
}
I assume you just want to call your action method in the controller.
Use Ajax
$.ajax({
type: "POST",
url: "/Users/Delete",
data: { ID: id},
success: {
},
});
Related
I am trying to pass the value of TransactionNumber into the controller but I am getting an undefined result.
here is my code,
function getall()
{
$('#tbl-transaction').dataTable().fnDestroy();
$('#tbl-transaction').DataTable({
"ajax": {
"url": '/Admin/GetAllTransactions',
"type": "get",
"datatype" : "JSON"
},
"columns" :
[
{ data :"TransactionNumber"},
{ data: "PurposeOfVisit" },
{ data: "NameOfHostFromST" },
{ data: "TransactedBy" },
{
data: "id", "render" : function(data)
{
return '<button class= "btn btn-success" onclick = "get_details(' + data+ ')"> Details </button>';
}
}
]
})
}
function get_details(id,TransactionNumber)
{
window.location.href = '/Approver/Details/' + id + '?=' + TransactionNumber;
}
controller side
public ActionResult Details(int Id, string TN)
{
tbl_FSEWeb_Transaction tbl_FSEWeb_Transaction = db.tbl_FSEWeb_Transaction.Find(Id);
//var course = 0;
return View(tbl_FSEWeb_Transaction);
}
I'm using ASP.net mvc and ajax.
The structure of your URL is incorrect. Replace your javascript function with:
window.location.href = '/Approver/Details/?id=' + id + '&tn=' + TransactionNumber;
The initial parameters follow the format:
?<name>=<value>
Multiple parameters are then added with ampersands (&)
I have the below custom button added to my navigation pager, but i want it to look at what i multi selected and send it to the JQGrid's editurl for processing which is a ASHX.CS page
But i can't make sense of the documentation when it comes to custom button
I can get it call a local function with onClickButton: customButtonClicked but it doesn't send the data like the EDIT button does
In the end what i want to do it select multiple rows and press a button on the navbar and approve all the selected records
// add first custom button
$('#jQGrid').navButtonAdd('#jQGridPager',
{
buttonicon: "ui-icon-mail-closed",
title: "Send Mail",
caption: "Send Mail",
position: "last",
editData: {
WrkId: function () {
var sel_id = $('#jQGrid').jqGrid('getGridParam', 'selarrrow');
var value = "";
for (var a = 0; a < sel_id.length; a++) {
value = value + $('#jQGrid').jqGrid('getCell', sel_id[a], 'wrkid') + ',';
}
return value;
},
CurrentUser: function () {
return '<% =System.Web.HttpContext.Current.User.Identity.Name %>';
}
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$("#jQGrid").trigger("reloadGrid", [{ current: true }]);
return [false, response.responseText]
}
else {
$(this).jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid')
return [true, response.responseText]
}
}
}
);
using a few different words (how to manually post data to server json) i was able to find a snippet of an ajax code that made more sense (i'm sure i came across this before but as someone who has no jquery experience i didn't recognize it)
but the below sends to the C# handler page the data in a JSON string that was processable, had to use dynamic to read it in but it worked, couldn't get it to not return an error even though there was no error, so i used the complete: instead of success: and then called the trigger to reload the JQGrid
Final Code:
$('#jQGrid').navButtonAdd('#jQGridPager',
{
buttonicon: "ui-icon-check",
title: "Approve all selected entries",
caption: "Approve",
position: "last",
onClickButton: function () {
var sel_id = $('#jQGrid').jqGrid('getGridParam', 'selarrrow');
var value = "";
for (var a = 0; a < sel_id.length; a++) {
value = value + $('#jQGrid').jqGrid('getCell', sel_id[a], 'wrkid') + ',';
};
$.ajax({
type: "POST",
url: "AdministrationHandler.ashx?oper=approve",
data: JSON.stringify({
WrkId: value,
CurrentUser: "<% =System.Web.HttpContext.Current.User.Identity.Name %>"
}),
dataType: "json",
contentType: "application/json; charsset=utf-8",
complete: function (xhr, x) {
if (xhr.responseText.toUpperCase().indexOf("SUCCESS") >= 0) {
alert('Success!\n' + xhr.responseText);
}
else {
alert('Failed!\n' + xhr.responseText + '\n' + x);
};
$("#jQGrid").jqGrid('setGridParam', { datatype: 'json' }).trigger('reloadGrid');
}
})
}
});
C# Code
try
{
String postData = new System.IO.StreamReader(context.Request.InputStream).ReadToEnd();
var data = JsonConvert.DeserializeObject<dynamic>(postData);
Approve(data.WrkId.ToString(), data.CurrentUser.ToString());
strResponse = "Employee records successfully approved";
}
catch
{
strResponse = "Employee records not approved";
}
context.Response.Write(strResponse);
$(document).ready(function () {
setInterval(function () {
$('#RoomBlock').children('div').each(function () {
ShowRoom($(this).attr('id'));
});
}, 10000);
function ShowRoom(id) {
$.ajax({
type: "POST",
url: "/localhost/GetData/" + id
success: function (response) {
if (response != null) {
$('#' + id).empty();
$('#' + id).append(response);
} else {
alert("null");
}
},
error: function (response) {
alert("error!");
}
});
})
i have 5 table and they always fetch data from server for several time, success times for every table is different, i want to put some loading bar on every table when they make a request. is there any way to do that with javascript ?
the one that make confuse is how to know that the first table is make a request and still while the other one was done.
try something like below
$(document).ready(function () {
setInterval(function () {
$('#RoomBlock').children('div').each(function () {
ShowRoom($(this).attr('id'));
});
}, 10000);
function ShowRoom(id) {
/* Add some loader here (bar or image)*/
var loaderHtml = "<div id='loader_'+id>_____Add your loader code here_____</div>";
$('#' + id).append(loaderHtml);
$.ajax({
type: "POST",
async: false,
url: "/localhost/GetData/" + id
success: function (response) {
if (response != null) {
$('#' + id).empty();
$('#loader_'+ id).remove();
$('#' + id).append(response);
} else {
alert("null");
$('#loader_'+ id).remove();
}
},
error: function (response) {
alert("error!");
}
});
})
Here is my php code
AjaxServer.php
include '../include/connection.php';
//here check the prediction
if(isset($_POST["delete_me"]) && $_POST["delete_me"]=="true"){
$id = $_POST["id"];
$table = $_POST["table"];
$query = "delete from {$table} where id='{".$id."}'";
if(mysql_query($query)){
echo "record has been deleted";
}
}
This is my js file Custom.js
$(document).ready(function() {
$('a.delete').click(function(e) {
if(confirm("Do you realy want to delete this")){
e.preventDefault();
var parent = $(this).parents("tr");
var table = $(this).attr("data-table");
var id = $(this).attr("id");
var data ="id="+id+"&delete_me=true&table="+table;
$.ajax({
type: 'post',
url:'include/ajaxserver.php',
data: data,
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(500,function() {parent.remove();});
}
});
}
else{
return false;
}
});/*end of the cick function*/
});/*end of the ready function*/
you are not sending your data to ajax file correctly replace you ajax code by following:
$.ajax({
type: 'post',
url:'include/ajaxserver.php',
data: {id: id, delete_me: true, table :table},
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(500,function() {parent.remove();});
}
});
Hope this code will help.
I am submitting form data using Ajax and they are successfully saved in the database and I am able to alert the response data. I now want to use the returned data as response to call another function using Ajax and pass them as parameters so that to the called function they can be used to fetch data and and display them on the web page.
The problem is that when the data have been alerted, the function I call using Ajax is not responding even when I use some functions like window.location.href, window.location.replace, window.location.reload they are not executed
Here is the sample code
submitHandler: function(form) {
/*errorHandler.hide(); */
var el = $(div);
el.block({
overlayCSS: {
backgroundColor: '#fff'
},
message: '<i class="fa fa-refresh fa-spin"></i>',
css: {
border: 'none',
color: '#333',
background: 'none'
}
});
/*Set off for database validation */
$('#name1').removeClass('has-error');
$('#name1 .help-block').empty();
$('#date1').removeClass('has-error');
$('#date1 .help-block').empty();
/*end database validation */
/*ajax options */
var options = {
/*target: '#output2', target element(s) to be updated with server response */
success: function(data, textStatus, XMLHttpRequest) {
el.unblock();
if (!data.success) {
/*append error message on the form for each control and database validation*/
console.log(data);
if (data.errors.name1) {
$('#name1').addClass('has-error');
$('#name1 .help-block').html(data.errors.name1);
}
} else {
var business_id = data.business_id;
var bnm_app_id = data.bnm_app_id;
var name = data.name;
var doc = data.doc;
alert(business_id);
alert(bnm_app_id);
alert(name);
alert(doc);
if (window.XMLHttpRequest) {
myObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
myObject = new ActiveXObject('Micrsoft.XMLHTTP');
myObject.overrideMimeType('text/xml');
}
myObject.onreadystatechange = function() {
data = myObject.responseText;
if (myObject.readyState == 4) {
//document.getElementById('step-2').innerHTML = data;
window.location.reload(true);
}
}; //specify name of function that will handle server response........
myObject.open('GET', '<?php echo base_url()."bn_application/register";?>?bnm_app_id=' + bnm_app_id + '&doc=' + doc + '&business_id=' + business_id + '&name=' + name, true);
myObject.send();
}
},
error: function(xhr, textStatus, errorThrown) {
el.unblock();
if (xhr.responseText === undefined) {
$.gritter.add({
/* (string | mandatory) the heading of the notification */
title: 'Connection timed out',
class_name: 'gritter-black'
});
} else {
var myWindow = window.open("Error", "MsgWindow", "width=900, height=400");
myWindow.document.write(xhr.responseText);
}
/*clear controls that do not need to keep its previous info */
},
url: home + 'bn_application/save_clearance_name',
/* override for form's 'action' attribute*/
data: {
name1_percent: name1_percent
},
type: 'post',
/* 'get' or 'post', override for form's 'method' attribute*/
dataType: 'json',
/* 'xml', 'script', or 'json' (expected server response type)*/
beforeSend: function() {
},
uploadProgress: function(event, position, total, percentComplete) {
},
complete: function() {
}
};
/*submit form via ajax */
$('#bn_clearance').ajaxSubmit(options);
}
If i understand you right , you need something like this ?
$.ajax({
type: "GET",
url: baseUrl + 'api/cars',
success: function (firstResponse) {
$.ajax({
type: "GET",
url: baseUrl + 'api/cars/' + firstResponse[0].Id,
success: function (secondResponse) {
window.location.href = secondResponse[0].Make;
}
});
}
});
You can use window.open function
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
window.open("http://www.w3schools.com", "_self");
}});
});
You should put your redirecting url in success function of ajax. (if you are using jQuery). Because javascript runs codes asynchronously and probably your code tries to run before you get response from request.