Ajax MVC hide button in a table row - javascript

I have a dropdownlist in table and button that should show if there is a value form the database. In my dropdown I send to a function
onchange = "getInfoid(this)"
The function:
function getInfoid(myvalue) {
var typeid = $(myvalue).val();
$.ajax({
url: '/mycontroller/GetInfoUrl',
contentType: 'application/html; charset=utf-8',
type: 'Get',
data: {
id: typeid
},
dataType: 'html'
})
.success(function (result) {
var tr = $($(myvalue).parents("tr")[0]);
var button = tr.find("button#Details0");
$(button).attr("onclick", "viewOhaInfo('" + result + "')");
$(button).show();
})
.error(function (result) {
var tr = $($(myvalue).parents("tr")[0]);
tr.find("button#Details0").hide();
});
};
The script does not show or hide the button. To test it; I tried the Ajax script to show and hide a div, and tried hiding and showing the button in the table using the same without Ajax, both worked. Do I lose the value of myvalue variable or what else could be the reason.
EDIT
The problem was in my understanding of success and error, I changed my script to:
.success(function (data) {
if (data == null) {
var tr = $($(myvalue).parents("tr")[0]);
tr.find("button#Details0").hide();
} else {
var tr = $($(myvalue).parents("tr")[0]);
var button = tr.find("button#Details0");
$(button).attr("onclick", "viewOhaInfo('" + data + "')");
$(button).show();
}
This solved it. Thank you all for your assistance.

jqXHR.success() and jqXHR.error() are deprecated. Read api docs.
jqXHR.done(function( data, textStatus, jqXHR ) {}); An alternative
construct to the success callback option, the .done() method replaces
the deprecated jqXHR.success() method. Refer to deferred.done() for
implementation details.
jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {}); An
alternative construct to the error callback option, the .fail() method
replaces the deprecated .error() method. Refer to deferred.fail() for
implementation details.
so modify your script to this:
$.ajax({
url: '/mycontroller/GetInfoUrl',
contentType: 'application/html; charset=utf-8',
type: 'Get',
data: {
id: typeid
},
dataType: 'html'
})
.done(function (result) {
var tr = $($(myvalue).parents("tr")[0]);
var button = tr.find("button#Details0");
$(button).attr("onclick", "viewOhaInfo('" + result + "')");
$(button).show();
})
.fail(function (jqXHR, textStatus) {
var tr = $($(myvalue).parents("tr")[0]);
tr.find("button#Details0").hide();
});
Here is how to do it alternatively.

Related

Populate Ajax response with clickable elements that fires another Ajax with correct parameters

So i have a function running an Ajax call that receives data and populate that as a table.
The response contains some rows with data and i now want to add a small fontawsome icon that when clicked fires another function with a parameter.
So i have this:
var latestprecasedata = '';
function getPreCaseData() {
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/GetPreCase",
dataType: "json",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;
data = $.parseJSON(data);
$("#PreCaseTblBody").html("");
for (var i in data) {
$("#PreCaseTblBody").append("<tr><td>" + data[i].pSubject + "</td><td><span class='preplus' id='" + data[i].pID + "'><i class='fa fa-plus'></i></span></td><td>-</td></tr>");
}
if (latestprecasedata !== response.d) {
$("#precasestatus").removeClass("titleupd1").addClass("titleupd2");
latestprecasedata = response.d;
}
else {
$("#precasestatus").removeClass("titleupd2").addClass("titleupd1");
}
}
$("#PreCaseTblBody tr:odd").css('background-color', '#f9f9f9'); //
$("#PreCaseTblBody tr:even").css('background-color', '#f1ffee');
setTimeout(getPreCaseData, 10000);
}
});
}
This works and every 10 seconds data is repopulated. (Maybe not the fastest solution, but it works..)
As you all can se i have a span with class=preplus and id of a unique value coming from my Ajax response. When inspecting the page i can see that every row from my Ajax response have a unique id.
For example two row looks like this:
<tr><td>Cables</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
<tr><td>Skrews</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
So now i have the data populated with span containing a unique id that i want to pass to another function.
I've tried span, div, buttons but the only one time I actually got a event fire was when i placed my second function inside the
for (var i in data) {
... and i know, that's not right at all because all rows contained the last id obviously...
So my other function resides outside my first function and look like this (I've tried many different methods to get the id of my span but for now, I'm here)
$(".preplus").click(function () {
var qID = $(this).attr('id');
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/UpdateQ",
dataType: "json",
data: "{'qid':'" + qID + "','pm':'plus'}",
success: function (data) {
}
});
return false;
});
Please guide me.

how can I delete the row from datatable in UI,though i could successfully delete from server using Ajax call

I have a data table and in each row I have a button Delete.
ON click of Delete i am making an ajax call and deleting the row from server by passing the id.
But on success of ajax call the row is not getting deleted in the table from UI.
Below si the code.
I have rendered the column for Delete
{
"data": "Action","orderable": false, "render": function(data, type, row) {
userSignum=readCookie("userSignum");
var userIDMGroups=readCookie("nfvDBGroups");
var userIDMGroupsArray=userIDMGroups.split(';')
if((jQuery.inArray(userIDMGroups,userIDMGroupsArray ) !== -1)&&(row['signumId'] == userSignum) )
{
return '<button class="btn btn-action deleterecord" id="'+row.id+'">Delete</button>'
}
else
{
return '<button class="btn btn-action deleterecord" id="'+row.id+'" disabled="disabled">Delete</button>'}
}
}
Below si the ajax call
$("#searchTable tbody").on("click", ".deleterecord", function () {
var table = $('#searchTable').DataTable();
var recordId=$(this).attr("id");
// var $row = $(this);
if(recordId!=null){
$.ajax({
type: 'POST',
url: config.vnfURL + 'vnf/delete',
dataType: "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify({"id" : recordId }),
processData: false,
success: function(response, textStatus, jqXHR) {
// table.row( $(this).parents('tr') ).remove().draw();
//$(recordId).remove();
table.row($(this).parents('tr')).remove().draw(false);
alert("record deleted");
if(jqXHR.status == "200"){
className = "alert-success";
msg = "Record has been deleted Successfully.";
} else {
className = "alert-danger";
msg = "Something wrong, please try again after sometime.";
}
$("#infoDiv").addClass(className).show();
$("#infoDiv>center>p").html(msg);
setTimeout(function() {
$("#infoDiv").removeClass(className).hide();
$("#infoDiv>center>p").html("");
// window.location = "/resources/search.html";
}, 7000);
},
please help
The reason is that this within AJAX success callback refers to XHR object, so you may assign const tr = table.row($(this).closest('tr')) outside of success callback and then do tr.remove().draw() upon successful deletion server-side.
p.s. also, note that I have used closest('tr') rather than parents('tr') as it is less error prone, since the latter may return array if your button happen to have multiple <tr> parents
Add this line on success call back of ajax
table.row( $(this).parents('tr') ).remove().draw();

jQuery AJAX function call

I have a problem with jQuery calling an AJAX function, basically everytime a user changes a select box, I want it to call the getSubCategories function, but for some reason, nothing is happening. Any ideas?
If I load the page and add console.log inside the getSubCategories function it logs it, should that even be happening?
function getSubCategories() {
var id = $("#category").prop('selectedIndex');
var selectedCategory = $("#category").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfCategory = convertToSlug(selectedCategory);
id++;
console.log('here');
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_subcategories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#sub_category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#sub_category").append('<option value="' + this.body + '">' + this.body + '</option>'); //add the sub categories to the options
});
$("#category_slug").attr('value', slugOfCategory);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function getCategories() {
var id = $("#type").prop('selectedIndex');
var selectedType = $("#type").val();
//should change this into a response from AJAX and grab the slug from there, this is fine for now.
var slugOfType = convertToSlug(selectedType);
console.log(slugOfType);
//add one to the ID because indexes dont start at 0 as the id on the model
id++;
$.ajax({
method: 'GET', // Type of response and matches what we said in the route
url: '/product/get_categories', // This is the url we gave in the route
data: {
'id': id
}, // a JSON object to send back
success: function(response) { // What to do if we succeed
$("#category option").remove(); //Remove all the subcategory options
$.each(response, function() {
$("#category").append('<option value="' + this.name + '">' + this.name + '</option>'); //add the sub categories to the options
});
$("#type_slug").attr('value', slugOfType);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
}
function convertToSlug(Text) {
return Text
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
}
$(document).ready(function() {
var firstCatgegory = $("#category").val();
var slugOfFirstCategory = convertToSlug(firstCatgegory);
$("#category_slug").attr('value', slugOfFirstCategory);
var firstType = $("#type").val();
var slugOfFirstType = convertToSlug(firstType);
$("#type_slug").attr('value', slugOfFirstType);
$("#type").change(getCategories());
$("#category").change(getSubCategories());
});
Thanks for any help. (Sorry the code is a little messy, i've just been trying to get it to work so far)
This is due to the fact that the ajax call you are trying to make is asynchronous. When you call getSubCategories() it returns undefined which is why your code is not working.
To make this work you need to put your code within the success callback function instead.
<script>
function getSubCategories()
{
var id= $("#category").prop('selectedIndex');
$.ajax({
method: 'GET',
url: '/product/get_subcategories',
data: {'id' : id},
success: function(response){
// DO SOMETHING HERE
},
error: function(jqXHR, textStatus, errorThrown) { }
});
}
$( document ).ready(function() {
// This is also wrong. Currently you're passing
// whatever is returned from getSubCategories
// (which is undefined) as the callback function
// that the "change" event will call. This instead
// should be the reference to the function. Which
// in this case is getSubCategories
$("#category").change(getSubCategories);
});
Please put getCategories() and getSubCategories() Methods inside Change function like this.Sorry for not code formatting.
<script>
$(document).ready(function(){
$("#category").change(function(){
getSubCategories();
});
$("#type").change(function(){
getCategories();
});
});
</script>

Display data in dynamically created div using jquery

I want to display data function name and function description from database and display it in div which will be created dynamically using jquery. How can I display data with dynamic div using jquery...
code for dynamically created div is:
$(document).ready(function () {
$.ajax({
type: "POST",
url: 'FunctionListing.aspx/CountFunction',
data: "{}",
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
//alert(result.d);
for (var i = 1; i <= result.d; i++) {
$('body').append("<div id='div" + i + "' />");
}
},
error: function (result) {
alert(result);
}
});
});
dataType :"json"
Not datatype :"json"
Hope, it'll helps you.

How to ensure that a function is executed completely, before navigating to another page?

I'm removing certain records using a webservice. The jquery ajax request is written in the onclick of a hyperlink. When im executing the script, line by line using firebug, it's getting removed otherwise it's not. Does any one meet any situation like this before? Please help
Code sample:
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
jQuery ajax functions return deferred objects, thus we return $.ajax. Then you should use deferred.done to execute the callback when the AJAX is fully finished. When the AJAX is done, navigate away using JS instead:
var func = function() {
...
return $.ajax({...}); //return our ajax deferred
}
$(".target").click(function() {
var target = this; //preserve "this" since this in the callback may be different
func().done(function(){ //our done callback executed when ajax is done
window.location.href = target.href; //assuming .target is a link
});
return false; //prevent the natural click action
});
You can use the async: false on the ajax call that is wait there to complete the call.
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: false,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
Alternative you can make the submit after the request.
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
return false;
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: true,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
$("#YourFormID").submit();
}
//Event that'll be fired on Success
});
}
Simply move the Event to the "success" handler in your ajax request:
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed");
//Event that'll be fired on Success
}
});
Alternatively use jQuery ajax callback methods.

Categories

Resources