prevent onchange event in jquery - javascript

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);
},
})
});
})

Related

Only with a double click does the event occur

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.

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());
});

Web service receiving null with jQuery post JSON

The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}

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;
}

Delete Track not deleting in soundcloud account

I am trying to use the delete function to delete a track from the user's soundcloud account while also deleting the track from my database. It is successfully deleting the information from my database, but is not deleting from the soundcloud's database and I really cannot understand why! No errors show up until the end, but just does not delete the track from soundcloud.
This is my code I am using:
$(".deleteTrack").live("click", function () {
if (SC.isConnected) {
var scTid = $(this).attr('id');
var path = "/tracks/" + scTid;
var con = confirm("Are you sure you want to delete this track?");
if (con) {
$.ajax({
type: "POST",
contentType: "application/json",
url: "JamWithInI.aspx/GetTrackInfo",
data: "{'scTid':'" + scTid + "'}",
dataType: "json",
success: function(str){
inst = str.d["1"];
SC.delete(path, function(){
$.ajax({
type: "POST",
contentType: "application/json",
url: "JamWithInI.aspx/DeleteTrack",
data: "{'scTid':'" + scTid + "'}",
dataType: "json",
success: function(){
alert("Your track has been deleted");
$("#openInstruments").trigger('click').trigger('click');
$(".instrument").trigger('click').bind('click').trigger('click');
inst = null;
},
error: function () {
alert("Track did not delete succesfully");
}
});
});
},
error: function () {
alert("An error occurred");
}
});
}
}
});
The SC.delete() method calls your callback with a response object and error (if any). Add something like the following to find out if things are working properly:
SC.delete(path, function(response, error) {
alert(response.status);
if (error) {
alert(error);
}
});
If your delete request was successful, you should get a single alert with the text '200 - OK'. If not, the error message will be informative.

Categories

Resources