How to prevent ajax send multiple request when change input data - javascript

Im using ajax to send a parameter from input field in Modal to Controller,
But when i change the value and close the modal, ajax remember it and when i call it, Ajax request multiple times, with old values and the new of the input.
<!--Add post to seri -->
<div class="modal fade" id="addModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add post to serie</h4>
<button type="button" class="close cleardt" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="row">
<div class="col-9">
<input type="number" required id="IDPost" placeholder="Nhập id bài viết" class="form-control" />
</div>
<div class="col-3">
<button class="btn btn-info" id="btnCheck">Check</button>
</div>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Bài viết gốc:</label>
<p id="postName" class="text-primary bold">ID không hợp lệ</p>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" id="addPostBtn" disabled class="btn btn-success">Thêm</button>
<button type="button" class="btn btn-secondary cleardt" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
My ajax syntax:
var serieid = '#Model.SerieID';
$('#addBtn').click(function () {
var amodal = $('#addModal');
$('#IDPost').val(null);
amodal.modal('show');
$('#addPostBtn').click(function () {
var idpost = $('#IDPost').val();
amodal.modal('hide');
$.ajax({
type: "POST",
url: '/Admin/AddToSerie',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id: idpost, seriid: serieid }),
dataType: "json",
success: function (recData) {
var notify = $.notify('<strong>Successfully
</strong><br/>' + recData.Message + '<br />', {
type: 'pastel-info',
allow_dismiss: false,
timer: 1000,
});
if (recData.reload != false) {
setTimeout(function () {
window.location.reload();
}, 1500);
}
},
error: function () {
var notify = $.notify('<strong>Error</strong><br/>Không thêm được<br />', {
type: 'pastel-warning',
allow_dismiss: false,
});
}
});
});
});
Im finding a way to clear the value queue of input field but it doesnt work

$('#addPostBtn').click add a EventListener to the element.
It is called every time when #addBtn is clicked, so multiple event listeners are attached to addPostBtn. That's why your ajax was called multiple times.
You can fix it by using on and off of jQuery.
...
amodal.modal('show');
$('#addPostBtn').off('click');
$('#addPostBtn').on('click', function () { ... });
Or it can be fixed by moving $('#addPostBtn').click out of $('#addBtn').click function.
$('#addBtn').click(function () {
var amodal = $('#addModal');
$('#IDPost').val(null);
amodal.modal('show');
});
$('#addPostBtn').click(function () { ... });

Try appending a unique bit of text to ajax url every time, eg
var ts = (new Date()).getMilliseconds();
$.ajax({
type: "POST",
url: '/Admin/AddToSerie?ts=' + ts,
contentType: "application/json; charset=utf-8",
......
Change the getMilliseconds to provide a genuinely unique value, say by concatenating all the other portions of the date.

v**separate modal click and ajax click event**ar serieid = '#Model.SerieID';$('#addBtn').click(function () {
var amodal = $('#addModal');
$('#IDPost').val(null);
amodal.modal('show');});$('#addPostBtn').click(function () {
var idpost = $('#IDPost').val();
amodal.modal('hide');
$.ajax({ type: "POST",
url: '/Admin/AddToSerie',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id: idpost, seriid: serieid }),
dataType: "json",
success: function (recData) {
var notify = $.notify('<strong>Successfully</strong><br/>' + recData.Message + '<br />', {
type: 'pastel-info',
allow_dismiss: false,
timer: 1000,
});
if (recData.reload != false) {
setTimeout(function () {
window.location.reload();
}, 1500);
}
}
});});

Related

Add/Remove button Ajax only show one

I have 2 buttons with this ajax and they both show on the page,how can i make it that only Add to favorites button is shown and when i click it the Remove From Favorites button takes it place ?
function Fav(gameId) {
var url = '#Url.Action("AddToCollection", "UserCollection")';
$.ajax({
url: url,
type: 'GET',
data: {
gameId: gameId,
},
});
};
function UnFav(gameId) {
var url = '#Url.Action("RemoveFromCollection", "UserCollection")';
$.ajax({
url: url,
type: 'GET',
data: {
gameId: gameId
},
});
};
<button class="btn-link" onclick="Fav(#Model.Id)"><i class="fa fa-heart"></i>Add To Collection</button>
<button class="btn-link " onclick="UnFav(#Model.Id)"><i class="fa fa-heart-broken"></i>Remove From Collection</button>
Try something like this.
DRY (Don't Repeat Yourself)
const urls = {
"AddToCollection": '#Url.Action("AddToCollection","UserCollection")',
"RemoveFromCollection": '#Url.Action("RemoveFromCollection","UserCollection")'
}
function Fav(gameId, action) {
$.ajax({
url: urls[action],
type: 'GET',
data: {
gameId: gameId,
},
});
};
$(function() {
const whichButton = "AddToCollection"; // set which one to show here using whatever method
$(".btn-link[data-action="+whichButton+"]").show();
$(".btn-link").on("click", function() {
Fav(this.dataset.id, this.dataset.action)
$(this).siblings().hide();
});
});
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="favDiv">
<button class="btn-link hide" data-action="AddToCollection" data-id=""><i class="fa fa-heart"></i>Add To Collection</button>
<button class="btn-link hide" data-action="RemoveFromCollection" data-id=""><i class="fa fa-heart-broken"></i>Remove From Collection</button>
</div>
This is the final result that i was looking for
const urls = {
"AddToCollection": '#Url.Action("AddToCollection","UserCollection",new { gameId = Model.Id })',
"RemoveFromCollection": '#Url.Action("RemoveFromCollection","UserCollection",new { gameId = Model.Id })'
}
function Fav(gameId, action) {
$.ajax({
url: urls[action],
type: 'GET',
data: {
gameId: gameId,
},
});
};
$(function() {
const whichButton = "AddToCollection"; // set which one to show here using whatever method
$(".btn-link[data-action=" + whichButton + "]").show();
$(".btn-link").on("click", function() {
Fav(this.dataset.id, this.dataset.action)
$(this).siblings().hide();
$(this).siblings().show();
$(".btn-link[data-action=" + whichButton + "]").hide();
});
});
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="favDiv">
<button class="btn-link hide" data-action="AddToCollection" data-id=""><i class="fa fa-heart"></i>Add To Collection</button>
<button class="btn-link hide" data-action="RemoveFromCollection" data-id=""><i class="fa fa-heart-broken"></i>Remove From Collection</button>
</div>

AJAX SyntaxError: Invalid character

The logic flow I'm trying to achieve is as following:
Select filters from popup => Generate the main view layout with headers and buttons => clicking button will render datatable inside
div id="#Model.ContainerSafeName-activitytable"
Below are relevant bits:
Main layout:
#model Models.Model
#using Helpers;
#{
Layout = "~/Views/Shared/PartialPrint.cshtml";
}
<div class="card card-block">
<div class='container'>
<div class="card row">
<div class="card-header text-center text-white" role="tab" id="Heading">
<h5>Activities</h5>
</div>
<div>
<button role="button"
data-type="Activity"
type="button"
class="btn btn-outline-primary btn-sm col-sm-12 col-md-12"
data-filters='#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.filters))'
data-url="#Url.Action("Activity_Page_activity", "Activity", new { Area = "Activity" })"
data-containername="#Model.ContainerSafeName-activitytable"
id="btnReport_activity">
Show Data
</button>
</div>
<div id="#Model.ContainerSafeName-activitytable">
</div>
</div>
Javascript bit:
$('#btnReport_activity').click(function () {
var url = $(this).data('url');
var filters = $(this).data('filters');
//var filtersstring = JSON.stringify(filters)
var containername = $(this).data('containername');
debugger
$.ajax({
cache: false,
url: url,
data: filters,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'GET'
})
.done(function (result) {
alert("good");
$("#" + containername).html(result);
$(this).toggle();
})
.fail(function (jqXHR, status, errorThrown) {
alert(errorThrown);
});
});
Ajax fails with Invalid character error. Filters are just a list of values passed to mainLayout from controller. I suspect it returns something bad.
Can anyone please point me where it possibly could go wrong? Please let me know if I need to provide any additional information.
PS: I'm not posting it on a whim, I have done a lot of research prior to that (including json.stringifying data, etc.), literally banging myself against the wall at this point.
I do not need a datatype being a JSON. I had to make corrections as below in order to get a proper response:
$('#btnReport_activity').click(function () {
var url = $(this).data('url');
var filters = $(this).data('filters');
//var filtersstring = JSON.stringify(filters)
var containername = $(this).data('containername');
$.ajax({
cache: false,
url: url,
data: JSON.stringify(filters),
contentType: 'application/json; charset=utf-8',
type: 'POST'
})
.done(function (result) {
alert("good");
$("#" + containername).html(result);
$(this).toggle();
})
.fail(function (jqXHR, status, errorThrown) {
alert(errorThrown);
});
});

How to display CRUD views in a jquery dialog model form, or in a bootstrap popup

<script src="jquery-js">
$("._detailsInfo").click( function () {
var Id = $(this).attr('Id');
$.ajax({
"url": "/Test/Details/"+Id,
"type": "GET",
"dataType": "html",
success: function (response) {
$('#myModal').modal(options);
$('#myModal').modal('show');
},
failure: function (response) {
alert(response.responseText);
}
});
});
</script>
#model BOL3.tbl_Appoiment_Diary
<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-header">
<button type="button" class="close" data-dissmiss="modal" aria-hidden="true">x</button>
<h4 class="modal-title" id="myModalLabel">Details</h4>
<hr />
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
#Html.DisplayFor(model => model.Title)
</dd>
</dl>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
#Html.ActionLink("Back to List", "Index")
</p>
</div>
</div>
<td>
#*#Html.ActionLink("Details", "Details", new { id = item.ID }) |*#
<button class="btn btn-info btn btn-xs _detailsInfo" id=" '+ item.ID +' ">Details</button> |
#Html.Partial("_Details", new BOL3.tbl_Appoiment_Diary())
#*#Html.ActionLink("Details", "_Details", new { #class = "_detailsInfo", id = "'+item.ID+'" }) |*#
</td>
Can anyone help me with this. Please keep in mind that I'm quite new working with Javascript and Jquery so any help is greatly appreciated. I tryied different methods from multiple websites but nothing worked. Here are some of the websites that I tryed:
jquery-dialog-with-aspnet-mvc , jquery-dialog, and many others, but nothing seems to work.
Here is what i tryed until now:
public ActionResult Details(int Id)
{
BOL3.tbl_Appoiment_Diary appd = new BOL3.tbl_Appoiment_Diary();
appd = db.tbl_Appoiment_Diary.Find(Id);
return PartialView("_Details", appd);
}
this is the controller part.
<script src="jquery-js">
//$(function () {
// $("#dialog").dialog({
// autoOpen: false,
// modal: true,
// title: "Details"
// });
// $("#AppoimentDiary .details").click(function () {
// var ID = $(this).closest("tr").find("td").eq(0).html();
// $.ajax({
// type: "POST",
// url: "/Test/Details/",
// data: '{ID: "' + ID + '"}',
// contentType: "application/json; charset=utf-8",
// dataType: "html",
// success: function (response) {
// $('#dialog').html(response);
// $('#dialog').dialog('open');
// },
// failure: function (response) {
// alert(response.responseText);
// },
// error: function (response) {
// alert(response.responseText);
// }
// });
// });
//});
//$(document).ready(function () {
// $("#btnCreate").click(function () {
// InitializeDialog($("#testdialog"));
// $("#testdialog").dialog("open");
// });
// function InitializeDialog($element) {
// $.dialog({
// autoOpen: false,
// width: 400,
// resizable: true,
// draggable: true,
// title: "Appointments",
// model: true,
// show: 'slide',
// closeText: 'x',
// dialogClass: 'alert',
// closeOnEscape: true,
// open: function (event, ui) {
// $element.load('/Test/Add');
// },
// close: function () {
// $(this).dialog('close');
// }
// });
// }
//});
//$.ajaxSetup({ cache: false });
//$(document).ready(function () {
// $(".openPopup").live("click", function (e) {
// e.preventDefault();
// $("<div></div><p>")
// .addClass("dialog")
// .attr("id", $(this)
// .attr("data-dialog-id"))
// .appendTo("body")
// .dialog({
// title: $(this).attr("data-dialog-title"),
// close: function () { $(this).remove(); },
// modal: true,
// height: 250,
// width: 900,
// left: 0
// })
// .load(this.href);
// });
// $(".close").live("click", function (e) {
// e.preventDefault();
// $(this).closest(".dialog").dialog("close");
// });
//});
#*var url = '#Url.Action("Details", "Test")';
$('selector').load(url, { id: 1 });*#
</script>
#Html.ActionLink("Det", "Details", new { id = item.ID, #class = "data-toggle = 'modal' data-target = '#myModal' " }) |
<div id="dialog" style="display: none">
</div>
</div>
#*<div id='myModal' class='modal'>
<div class="modal-dialog">
<div class="modal-content">
<div id="myModalContent"></div>
</div>
</div>
</div>
<script src="jquery-js">
var TeamDetailPostBackURL = '/Test/Details';
$(function () {
$(".anchorDetail").click(function () {
debugger;
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: TeamDetailPostBackURL,
contentType: "application/json; charset=utf-8",
data: { "Id": id },
datatype: "json",
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#myModal').modal(options);
$('#myModal').modal('show');
},
error: function () {
alert("Loading the data is not possible!");
}
});
});
$("#closbtn").click(function () {
$('#myModal').modal('hide');
});
});
</script>*#
#*<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" style="background-color:aqua">
<h4 class="modal-title">Ada New</h4>
</div>
<div class="modal-body">
#Url.Action("/Test/Details")
</div>
<div class="modal-footer" style="background-color:aqua">
<button type="button" class="btn btn-danger" data-dissmiss="modal">Close</button>
<button type="button" data-dismiss="modal" class="btn btn-success">Save</button>
</div>
</div>
</div>
</div>*#
Any help on this topic is greatly appreciated.
Edit:
This is the index button, the script is from your answer:
in the same index view, and here is the partial view:
See, there is no need to call again details method from your modal body.
Create a modal inside partial view, and keep all your partial view HTML inside the modal body. And in top of your partial view, add your modal reference, like bellow,
#model Your_Project_Name.ModalFolderName.tbl_Appoiment_Diary
<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-header">Details Info</div>
<div class="modal-body">
/*Here keep your all HTML to display details data*/
</div>
</div>
</div>
Change or update the above HTML accordingly. And change the reference name with your project name and class name.
Create your Details button in your main view, like this,
<button class="btn btn-info _detailsInfo" id="'+item.ID+'"></Details>
While click this button call a jquery click function like bellow,
$("._detailsInfo").click(function ()
{
var Id = $(this).attr('Id');
$.ajax({
"url": "/Test/Details/"+Id,
"type": "Get",
"dataType": "html",
success: function (response) {
$('#myModal').modal(options);
$('#myModal').modal('show');
},
failure: function (response) {
alert(response.responseText);
}
});
});
Suppose your partial view name is _Details.cshtml. Then just render it inside your main view like this,(basically keep this bellow code before the close tag of body of your main view)
#Html.Partial("_Details", new tbl_Appoiment_Diary())
That's it! Hope it helps you.

save dynamic input form data into database kendo ui

i have populated dynamic input form fields. its populated successfully.i do not have an idea how to save data into database by using put/post api. as i used get api.
html code
<div id="renderform" class="form horizontal-form form-body">
<!-- container UL to host input fields -->
<div class="row" data-template="fieldsTemplate" data-bind="source:fields">
</div>
<!-- button to save changes -->
<button id="save" class="btn btn-circle btn-sm btn-default" type="button">Save</button>
</div>
kendo template
<script id="fieldsTemplate" type="text/x-kendo-template">
<div class="form-group">
<label class="control-label" data-bind="attr: { for: name}, text: ItemLabel"></label>
<div class="">
<input class="form-control-static" type="text" />
</div>
</div>
</script>
ajax function
<script type="text/javascript">
// retrieve the model from an API call
$.ajax({
url: crudServiceBaseUrl + "FormItemsDesign/GetFormItemsDesignList?parentid=" + formdesignid,
//url :"json.txt",
type: "GET",
dataType: "json",
success: function (model) {
// convert the JSON to observable object
var viewModel = kendo.observable(model);
// bind the model to the container
kendo.bind($("#renderform"), viewModel);
}
});
</script>
Post/Put api's will be like
url: crudServiceBaseUrl + "FormItemsDesign
type:Post
type:Put
please help me, how to make/use ajax function to call Post/Put to save/update data by each dynamic field into database. i appreciate your valuable time and effort thanks in advance.
After reading more articles finally I found this solution. Its working for me.
$("#save").on("click", function () {
$("#renderform input").each(function () {
var dataModel = {
parentid: $(this).attr("id"),
ItemOrder: "1",
ItemFieldType: "1",
ColWidth: "100",
RowHeight: "100",
ItemText: $(this).val(),
ItemLabel: $(this).attr("name")
};
$.ajax({
type: 'POST',
url: crudServiceBaseUrl + "FormsItem?firmid=" + firmid + "&createdby=" + clientid,
data: JSON.stringify(dataModel),
contentType: 'application/json; charset=utf-8',
dataType: 'json'
});
});
alert("Data Saved successfully");
});

Using Query string in MVC 3.0

I am having some anchor tags in the page and I have to set them all a value in query string and then
trying to send it in controller can this be possible.Actually I have a hidden field on the page and that hidden field is set to a value
when somebody selects a user from auto complete of jquery. Now my Question is that I am able to set hidden field a value but how can I assign value of hidden
field to query string in an anchor tag. Please help me. I am trying in this way.
<div id="page">
<div class="note-row2">
<div class="form-left">
<input type="text" id="txt_Autocomplete" />
<input type="hidden" id="hdnPkClientId" />
</div>
<div class="form-right">
</div>
<div class="right-row">
<h3><a href="/GoToPage/Index?Client_ID="+"'$('#hdnPkClientId').val()'" >My Page</a></h3>
</div>
</div>
</div>
Here I am setting the value in hidden field
<script>
$("#txt_Autocomplete").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/ClientHome/SearchClientDetail",
data: "{'searchtext':'" + document.getElementById('txt_Autocomplete').value + "'}",
dataType: "json",
success: function (data) {
response($.map(data.Data, function (item) {
return {
label: item.Name,
value: item.id,
data: item
};
}));
},
error: function (xhr)
{ }
});
},
select: function (event, ui) {
var detailArr = ui.item.label.split(',');
$("#txt_Autocomplete").val(detailArr[0]);
$("#hdnPkClientId").val(ui.item.data.Id);
</script>
I
in your html:
<a id="YOUR_A" href="/GoToPage/Index?Client_ID=" >My Page</a>
in your js:
select: function (event, ui) {
var detailArr = ui.item.label.split(',');
$("#txt_Autocomplete").val(detailArr[0]);
$("#hdnPkClientId").val(ui.item.data.Id);
$("#YOUR_A").attr("href", "/GoToPage/Index?Client_ID="+ui.item.data.Id);
}

Categories