Only with a double click does the event occur - javascript

button Uptade
<button type="button" id="custom-icon" onclick="UpdateParents()"">Update</button>
function AJAX
function UpdateParents() {
var ParentsOBJ = { IDkids: $("#IDkids").val(), NameKids: $("#NameKids").val(), LastNameKids: $("#LastNameKids1").val(), NameFather: $("#NameFather").val(), NameMother: $("#NameMother").val(), PhoneMother: $("#PhoneMother").val(), PhoneFather: $("#PhoneFather").val() };
$.ajax({
type: "PUT",
url: "/api/Parents/" + ParentsOBJ.IDkids,
data: JSON.stringify(ParentsOBJ),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
Parents = JSON.parse(data);
$('#custom-icon').on('click',function () {
swal({ title: "update", text: "ok.", icon: "/up.jpg" });
setTimeout(function () {
location.reload();
}, 2000);
});
},
failure: function (errMsg) {
alert(errMsg);
}
});
$('#custom-icon').on('click',function ()
Only when I double-click the button does the operation take place.
I can understand why this is happening (click in click),
But can't solve the problem.
I will be happy to resolve!!!

The problem is that you double bind the $('#custom-icon'), and the 2nd bind takes place inside an ajax success callback, which takes in place only after the ajax request that has been triggered from the first click has been finished.
All you need to do is to remove the 2nd binding, as it's unnecessary because you already bind the click event from the html, your new code will look like this:
function UpdateParents() {
var ParentsOBJ = { IDkids: $("#IDkids").val(), NameKids: $("#NameKids").val(), LastNameKids: $("#LastNameKids1").val(), NameFather: $("#NameFather").val(), NameMother: $("#NameMother").val(), PhoneMother: $("#PhoneMother").val(), PhoneFather: $("#PhoneFather").val() };
$.ajax({
type: "PUT",
url: "/api/Parents/" + ParentsOBJ.IDkids,
data: JSON.stringify(ParentsOBJ),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
Parents = JSON.parse(data);
swal({ title: "update", text: "ok.", icon: "/up.jpg" });
setTimeout(function () {
location.reload();
}, 2000);
},
failure: function (errMsg) {
alert(errMsg);
}
});
A better practice here would be to accept a callback method from the UpdateParents function, and then pass the success as a callback.

Related

How I do initial JavaScript Ajax initialization?

I'm pulling information with ajax. I want it my document.ready function(ajax) starting first because knockout file starting first and my "var initialData" value going null. How my Ajax start first ?
Here is my F12 Source
My script:
<script type="text/javascript">
var initialData;
function functionViewModel() {
$(document).ready(function () {
$.ajax({
type: "POST",
url: "KnockoutGrid2.aspx/GonderUrunler",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg.d);
initialData = msg.d;
}
});
});
var fn = {
friends: ko.observableArray(initialData)
};
fn.removeUser = function (item) {
fn.friends.remove(item);
};
return fn;
};
ko.applyBindings(functionViewModel());
</script>
Update 2
The answer of #user3297291 is better than mine, because is Knockout who handles all the state of this form. Please, don't do the applybindings in the answer of the ajax request.
The user need to know that the data isn't loaded yet, and this can be handled with knockout.
Original answer
Perhaps if you move the initialization of Knockout inside the success function:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "KnockoutGrid2.aspx/GonderUrunler",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg.d);
initialData = msg.d;
// All initialization inside the 'success' function
function functionViewModel(initialData) {
var fn = {
friends: ko.observableArray(initialData)
};
fn.removeUser = function (item) {
fn.friends.remove(item);
};
return fn;
};
ko.applyBindings(functionViewModel(initialData));
}
});
});
</script>
You could show a div with the message: "loading data...".
And when success run, hide this div.
Update 1
After your comment, I don't know why you need the return fn. I propose this solution:
<script type="text/javascript">
// Updating 'functionViewModel()' to add 'self'.
// Move functionViewModel()' outside ajax response
function functionViewModel(initialData) {
var self = this;
self.friends = ko.observableArray(initialData);
self.removeUser = function (item) {
self.friends.remove(item);
};
};
$(document).ready(function () {
$.ajax({
type: "POST",
url: "KnockoutGrid2.aspx/GonderUrunler",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg.d);
initialData = msg.d;
// All initialization inside the 'success' function
ko.applyBindings(functionViewModel(initialData));
}
});
});
</script>
Here I'm using self ( see Managing ‘this’ ) and don't return fn, because Knockout handles its state.
Use async:false in your code
$.ajax({
type: "POST",
url: "KnockoutGrid2.aspx/GonderUrunler",
data: "{}",
async : false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log(msg.d);
initialData = msg.d;
}
});
You do not want to wait with applyBindings until your ajax response is handled... Your document will look ugly if you let knockout wait with applying bindings and your users will have nothing to look at.
What you should do:
Apply bindings as soon as $(document).ready triggers
Make sure your viewmodels use observable properties that allow you to easily inject data later on
Make sure you define some sort of loading state to show your users the data is being downloaded
I.e.:
function functionViewModel() {
var friends = ko.observableArray([]);
var loading = ko.observable(true);
var removeUser = function(user) {
friends.remove(user);
}
// Get the data and write it to an observable property once done
$.ajax({
type: "POST",
url: "KnockoutGrid2.aspx/GonderUrunler",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
friends(JSON.parse(msg.d));
loading(false);
}
});
return {
friends: friends,
loading: loading,
removeUser: removeUser
};
};
$(document).ready(function() {
ko.applyBindings(functionViewModel());
});

ajax jquery message show after the function completed

I think it is simple question. I've tried to search but still not found an answer yet.
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
messageBox(result.d);
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
I want to show message after success() performed.
That means the comment left already then show message.
Thanks anyway!
P/s: I read a topic about jQuery Callback Functions at https://www.w3schools.com/jquery/jquery_callback.asp.
Can we use it in here? If we can, how to use?
You can try like this
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
success();
}
$.when(this).then(setTimeout(function(){ messageBox(result.d)}, 200));
// if you dont want use set timeout then use
// $.when(this).then(messageBox(result.d), 200));
},
error: error
});
},
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events.
Considering your implementation of var success = function() you may try with following approach:
Modify the success() to accept callback function as follows:
var success = function(callback) {
self.removeComment(commentId);
if(parentId)
self.reRenderCommentActionBar(parentId);
if(typeof callback == "function")
callback();
};
var messageBox = function (hasDeleted) {
if (hasDeleted) {
alert("Deleted successfully");
} else {
alert("Error");
}
}
deleteComment: function (commentJson, success, error) {
$.ajax({
type: "POST",
async: false,
url: deleteCommentConfig.url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ commentId: commentJson.CommentId }),
dataType: "json",
success: function (result) {
if (result.d) {
//passing the callback function to success function
success(function(){
messageBox(result.d);
});
}
},
error: error
});
},

jquery $.when.done() is not firing

I'm not sure if I am using the $.when correctly but this is what I am trying to do. I am trying to fire two ajax calls and when they both complete, I need to perform some additional work, however, my .done method never fires. My alert box is never hit, however, both of my Ajax requests are being executed.
The alert "DO NOT HIT HERE" gets triggered. I would like to prevent that from happening. I need it to trigger within the .done only.
function ValidateGeneralTab() {
var isValid = false;
$.when(SetGeneralTabIsValid(isValid), PostErrorMessages()).done(function ()
{
alert("Im here");
return isValid;
});
alert("DO NOT HIT HERE");
}
function SetGeneralTabIsValid(isValid)
{
var request = $.ajax({
type: "POST",
url: "NewIRA.aspx/SetGeneralTabIsValid",
data: "{'isValid': '" + isValid + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
},
error: function () {
}
});
return request;
}
function PostErrorMessages() {
var errorsCollection = ["Saab", "Volvo", "BMW"];
var request = $.ajax({
type: "POST",
url: ErrorMessagesUrl,
data: JSON.stringify(errorsCollection),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
},
error: function () {
}
});
return request;
}

prevent onchange event in jquery

I am using knockout with MVC in my project. when I pass viewModel on dropdown change It's getting continues ajax request to the server. How can I avoid the continues request??? any one can please help me on this???
My View
#ko.Html.DropDownList(m => m.RoomList, new { #class = "full-width", #id = "rmch" }, "Text", "Value").Value(m=>m.NoOfRooms)
Javascript
$(document).ready(function () {
$('#rmch').on("change", function (e) {
//viewModel.NoOfRooms = $(this).val();
$.ajax({
url: '#Url.Action("DropChange", "Home")',
type: 'POST',
data: ko.mapping.toJSON(viewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
//ko.applyBindings(viewModel, document.getElementById("p_scentsFH"));
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
})
});
})
if I remove value part from the dropdownlist in the view It's working .but I need the value for the processing.
The simplest thing I can think of is to set the dropdownlist to readonly before updating it, then when you have finished adding the new items, remove the readonly attribute.
$(document).ready(function () {
$('#rmch').on("change", function (e) {
//viewModel.NoOfRooms = $(this).val();
$.ajax({
url: '#Url.Action("DropChange", "Home")',
type: 'POST',
data: ko.mapping.toJSON(viewModel),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
//this will disable the onchange event
$('#rmch').attr("readonly","readonly");
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
//ko.applyBindings(viewModel, document.getElementById("p_scentsFH"));
ko.mapping.fromJS(data, viewModel);
}
//this will enable the onchange event for the next time you select something.
$('#rmch').removeAttr("readonly");
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
})
});
})

Modal window not showing up

On my page I have two modal windows. They are opened when user clicks buttons on the page. But I also want to be able to open second window when user clicks specific button on the first modal.
Here my JS code:
$(document).ready(function () {
$('.details-btn').on('click', function () {
$.ajax({
url: "/Device/Details",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'html',
data: { id: $(this).attr('id') },
error: function (data) {
alert("wystąpił nieokreślony błąd " + data);
},
success: function (data) {
$('.modal-body').html(data);
$("#DetailsModal").modal('show');
$(".DeviceEdit-btn").on('click', function () {
$('#DetailsModal').modal('hide');
$("edit-btn").trigger('click');
});
}
});
});
$('.edit-btn').on('click', function () {
console.log("triggered");
$.ajax({
url: "/Device/Edit",
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: 'html',
data: { id: $(this).attr('id') },
error: function (data) {
alert("wystąpił nieokreślony błąd " + data);
},
success: function (data) {
$('.modal-body').html(data);
$("#EditModal").modal('show');
}
});
});
});
as you can in .details-btn click event I hide a modal( this works) and trigger click on the button which should show second modal. But second modal doesn't show up.
How modify this code to make this work.
Is a problem connected with this that edit-btn on click event is declared after details-btn where trigger is?
Your are Not placing the dot
$("edit-btn").trigger('click');
change with
$(".edit-btn").trigger('click');

Categories

Resources