This question already has an answer here:
Model save backbone
(1 answer)
Closed 8 years ago.
I have a modal view which has a form. When I try to save the model, a REST call is made and I need to close the modal view after that..
self.myModel.url = "api/myClass/";
self.myModel.save({
success: function() {
self.trigger("afterSave");
self.removeModal();
}
}).fail(function() {
$('#save', self.el).button('reset');
});
Now my REST API code is executed fine...I have debugged on the last return statement from REST resource..
But my JS code does not go inside the success callback function.
Am I doing something wrong with the JS syntax?
So here is your problem:
self.myModel.save({
success: function() {
self.trigger("afterSave");
self.removeModal();
}
})
.save() method expects the first parameter to be the data. And the second object should contain options.
If you don't have any data to pass, you should modify the above call to this:
self.myModel.save({},{
success: function() {
self.trigger("afterSave");
self.removeModal();
}
});
You should be all set this way! Suggest you to check the documentation : Backbone Docs
the first param for save() should be the model data and the second is the callbacks
self.myModel.url = "api/myClass/";
self.myModel.save({
"name":"Bob"
},{
success: function() {
self.trigger("afterSave");
self.removeModal();
}
}).fail(function() {
$('#save', self.el).button('reset');
});
Related
This question already has answers here:
How to call a C# function from JavaScript?
(7 answers)
How to Call Controller Actions using JQuery in ASP.NET MVC
(5 answers)
Closed 4 years ago.
I have an ASP.Net Entity Framework view where I have multiple drop-down lists. Once a user changes an item in this list, I need to call a c# method which is passed the values in all of the dropdown lists to check whether their values overlap.
Currently I have:
#Html.DropDownListFor(model => model.Periods[i].StartTime, new SelectList(Model.DateTimeList, Model.Periods[i].StartTime), new {#class = "form-control", onchange = "dropdownChange()" })
which called a method called dropdownChange():
<script>
function dropdownChange() {
#{
var overlapping = PeriodController.ConfigureViewModel.IsOverLapping(Model);
}
console.log("here");
}
</script>
This method is found by the view but doesn't go into my c# code as I have tested by putting in javascript code and it is run. e.g. the console.log appears but doesnt call the c# code.
Either a solution to this or a more sophisticated way to call a c# method every time a dropdownlist is changed.
Added Ajax Method:
$.ajax({
type: "POST",
data: { 'Model': Model },
success: function(isOverLapping) {
overLappping = isOverLapping;
console.log(1);
},
error: function() {
console.log(2);
}
});
One line answer: MVC doesn't work like that.
Longer answer: You can't access the server-side code directly from the browser like that. The most common solution is to use something called AJAX to call the C# function on the server. You then need to write code in the View to handle the response from the server. Have a look at this question and this answer: https://stackoverflow.com/a/16186212/5173105
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have never been very good at understanding JS callbacks, promises and all of these. Now I stumbled on one of these scenarios.
I have a text element. When clicked, it is made editable. When pressing enter, an AJAX request is made with the input value and then (here is my issue) the original text should be updated with the input.
$('#text-element').click(function() {
edit($(this), url, paramName);
});
function edit($element, url, paramName) {
// show the input, set up some UI events...
$input.keypress(function(key) {
// check if it is the correct key to submit the data
if (submit) {
var data = {};
data[paramName] = $input.val();
$.ajax({
url: url,
method: 'post',
data: data,
success: function(response) {
// ???
}
});
}
});
}
You could say: simple, just take the data from the response and replace the original text with the updated one. I can't/don't want to do that because I want the edit function to stay generic so it can be used in other scenarios, as you might have guessed by the use of the different arguments.
Also, in the context of the edit function we don't really know the shape of the response object, so we cannot handle it at that stage.
The right place where the response should be handled is the part where we click the text element, here we do know the context and we know the expected composition of the response.
So essentially, I would want to return (or whatever you do when dealing with promises, callbacks, async operations...) the response from the ajax success function, fetch that response in the click handler funtion and deal with it accordingly:
$('#text-element').click(function() {
edit($(this), url, paramName); // <--- this should "return" the response
var response = ...; // how do I fetch this response from the edit function
$(this).html(response.content); // the response we expect in this case would be a JSON response with a key "content"
});
I hope I could make myself understand. If I don't, please let me know so I can clarify the question.
Simply make a callback function:
$('#text-element').click(function() {
edit($(this), url, paramName,function(response){
this.html(response.content);
}.bind($(this)));//bind to keep the #text-element as this
});
function edit($element, url, paramName,callback) {
// show the input, set up some UI events...
$input.keypress(function(key) {
// check if it is the correct key to submit the data
if (submit) {
var data = {};
data[paramName] = $input.val();
$.ajax({
url: url,
method: 'post',
data: data,
success: function(response) {
callback(response);//whats your problem with callbacks? they are so easy...
}
});
}
});
}
By the way, if the user clicks twice, there are two keypress handlers registered, making the whole code a mess. So you may prevent that in a way...
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have a few functions that grab data using ajax and I can then get the result data from outside the function when needed.
Here is one example:
function myfunction() {
jQuery.ajax({
url: someurl
method: 'GET',
async: false,
success: function(result) {
myresult = result;
}
});
return myresult;
};
And this from outside I get the data like this:
myvar = myfunction();
Doing it this way I am able to get the data outside the function.
I have searched google and stackoverflow and I still can't understand it so I thought adding a function that I'm already using might help me understand better how to do this.
How can I convert this code so that when I set async to true I'm able to get the data from outside the function?
How can I convert this code so that when I set async to true I'm able to get the data from outside the function?
Simple answer, don't. You're approaching the problem in the wrong way.
Instead of trying to get data available outside the function, you could provide a callback function which the data should be passed to:
function myfunction(callback) {
$.ajax({
url: someurl
method: 'GET',
success: callback
});
};
myfunction(function(data) {
// work with the data retrieved from the async request here...
console.log(data);
});
Note: this pattern is a little redundant in this example as you could just give the anonymous function directly to the success property. In a real scenario you'd probably want to execute some actual generic logic in the success handler before calling the provided callback function.
Alternatively you could return the deferred object from the jQuery AJAX request and then use a done() handler to be executed when the object is resolved:
function myfunction() {
return $.ajax({
url: someurl
method: 'GET'
});
};
myfunction().done(function(data) {
// work with the data retrieved from the async request here...
console.log(data);
});
In either case the logic to follow is that the data from the request should be provided to the required function instead of being made globally available.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
Sorry, but I am new to jQuery so this may seem like a dumb question.
I have a generic function that will call a $.get to retrieve some data from a URL and I then want to assign to a variable, not a control.
Here's my function, it has been simplified to clear out the "noise"...
function LoadFromURL(url) {
var response = "";
$("textarea#dump").val("url=" + url); // Shows the URL, no problem
$.get(url, "", function (data) {
response = data;
$("textarea#dump").val(response); // Shows the data, no problem
});
$("textarea#dump").val(response); // Shows NOTHING!
return (response);
}
The problem is that the response value quite happily assigns inside the callback function, but when it gets to the return (response) then the variable is empty.
The Shows NOTHING line is fired too soon to be useful. You must start from the callback function and go from there. You could call a method from the callback.
Call it like this:
var cb = function(data) {
$("textarea#dump").val(data);
}
LoadFromUrl("someUrl", cb);
or inline like this:
LoadFromUrl("someUrl", function(data) {
$("textarea#dump").val(data);
});
Change your method like this:
function LoadFromURL(url, cb) {
$("textarea#dump").val("url=" + url); // Shows the URL, no problem
$.get(url, "", function (data) {
cb(data); //<-- call the CallBack method
});
}
This is more the behavior of javascript than jQuery, callbacks are a way of life in js.
I try to manipulate a variable inside a function. But it seems to forget the values once I exit the function, eventhough the variable is declared outside the function.
The essential code:
var posts = {};
// Perform a data request
// skjutsgruppens-page
$.oajax({
url: "https://graph.facebook.com/197214710347172/feed?limit=500",
*SNIP*
success: function(data) {
$.extend(posts, data);
}
});
// Gruppen
$.oajax({
url: "https://graph.facebook.com/2388163605/feed?limit=500",
*snip*
success: function(data) {
$.extend(posts, data);
}
});
The oajax retrievies data from facebook. I want to make a variable that contains the data from both oajax methods.
The actual code: http://eco.nolgren.se/demo/resihop/#
The issue is likely that the success function executes at an arbitrary time in the future--unless you specifically access posts after you know the success function has executed, you will receive undefined results, completely dependent on function and access timing.
The best approach is to handle this correctly by doing necessary work inside in the success function, or use something like jQuery's .when function.