Callback basics using Backbone.js - javascript

I'm using backbone to post a login form to my server. After it queries the database it will flip a boolean value allowing me to retrieve GET responses from the server. The problem is that it tries to fetch (i think) before my login is validated. Given this code:
App.Login.add(newContact);
var out = newContact.save();
App.Contacts.fetch();
How do i write a callback to have it first finish newContact.save() before fetching Contacts?
This is what I have so far, but it never succeeds:
login: function(event) {
App.Browser.navigate('contacts');
event.preventDefault();
var $form = this.$('.login form');
var newContact = new App.Models.Login({
userName: $('input.userName', $form).val(),
passWord: $('input.passWord', $form).val(),
});
App.Login.add(newContact);
newContact.save({userName:"Frank"},{
wait: true,
success: function(model, response){
console.log('success');
},
error: function(){
console.log('error');
}
});

Model.save() accept callback to handle success or failure . which the code like:
App.Login.add(newContact);
var out=newContact.save(attributes,{
wait: true,// wait for the sever response finish
success:function(model, response,options){
App.Contacts.fetch();
},
error:function(model, xhr, options){
app.error(model);//custom handle for error
}
});

Related

Catch 500 code on submit form

I have submit function on form
Here is code of function
export function submit(): void {
$("#sequence").val(Number($("#sequence").val()) + 1);
$("#search_results").addClass("overlay");
$("#filter_form").submit();
}
this function called in onUpdated method
Here is code
// This is what triggers when we anything has been changed.
function onUpdated(): void {
if (!skipSubmit) {
submit();
}
}
I sometimes have 500 code request from back-end and need to show for example alert on it.
I need to catch 500 status from request.
I wonder how I can do this in this code, because I have only $("#filter_form").submit();?
Thank's for help
you can do something like this:
$('#filter_form').submit(function(event) {
//serialize the data in the form in JSON
var formData = $("#filter_form").serializeObject();
$.ajax({
type : 'POST',
url : //your url
data : formData,
dataType : 'json',
encode : true
}).done(function(data) {
//here it comes if there are no error in the server
}).fail(function(data){
//when it fails (so error 500)
//handle your error
)};
event.preventDefault();
}
You are posting your form synchronously. The browser always show the response for synchronous requests. you have 2 option to show user friendly error messages:
1- The server generates a user friendly html page and returns it to the client (you should handle the error at the server and generate the error page)
2- send request asynchronously (Ajax) and catch the error at the client and show a proper message to the user:
$.ajax(“/url-to-post”, {
data: $("#filter_form").serialize(), // serialize form data
success: function(){
//...
},
error: function(jqXHR, textStatus, error){
//...
},
});

Return alert message when fail validatemodel in web api

I have a validation model attribute for asp.net web api, and I use jquery ajax call to perform the web api call. However, when my ajax call fail, the ajax error does not return any message in success or fail.
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid) {
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, modelState);
}
}
}
$.ajax({
...,
success: function() {
alert('success');
},
error: function() {
alert('fail');
}
});
To get the response into your done and fail methods, simply do this:
$.ajax( "your ajax object" )
.done(function(data) {
alert(data);
})
.fail(function(error) {
alert(error);
});
When you pass a parameter into the callbacks (done, fail), you are capturing the response. So, if you hit an API to get an array of strings, and it was successful, the array would be inside data.

Callback does not work when i use fetch() method on backbone

Trying to make work the example of backbonetutorials. I am not able to throw a callback when the method fetch().
$(document).ready(function() {
var Timer = Backbone.Model.extend({
urlRoot : 'timeserver/',
defaults: {
name: '',
email: ''
}
});
var timer = new Timer({id:1});
timer.fetch({
success: function(data) {
alert('success')
},
fail: function(model, response) {
alert('fail');
},
sync: function(data) {
alert('sync')
}
});
});
The ajax request it has been threw. But does not work at all. Because any alert its dispatched.
sync and fail aren't valid callbacks. fetch uses the standard jQuery XHR object's options; there's success, error, and complete.
Here's a demo:
http://jsfiddle.net/ccamarat/sGJy4/

Mootools code for success, failure and submit

Does Mootools validation have a similar process for
Success, Failure and ajaxSubmitFile?
$("#rems").validationEngine({
ajaxSubmit: true,
ajaxSubmitFile: "database/agentpanel/reminder/makerem.php",
success : function() {
$.get("database/agentpanel/reminder/loadrem.php", function(html) {
$("#rem-scroll").html(html);
alert("Reminder Set");
$('#rems').find("input[type=text], textarea").val("");
$('#rem_confirm').attr('checked', false);
});
},
failure : function() { alert("Fill in all the fields with Red Marks"); }
});
I would like to be able to send the form without going to the next page, and also run an script on success and on failure.
You can add event functions to Mootools Form Request.
Try this:
new Form.Request(myForm, myResult, {
onSend: function () { // function to run on send
alert('Will send now!');
},
onFailure: function (){//function to run if failure (fires after onComplete)
alert('oops...!');
},
onComplete: function () {//function to run on send complete
alert('Submited!');
},
onSuccess: function () {//function to run on success
alert('Success!');
},
requestOptions: { //etc...
Demo here
Worth to read:
Mootools blog on form request
Mootools docs (Form.Request)

How do you find the error generated by a backbone fetch

I'm new to backbone but I've written a basic model and when trying to fetch data for my model. I know the server is returning the data but fetch is calling the error callback.
That's fine but I don't know how I can find what error is being generated.
Here's the relevant code:
mUser = Backbone.Model.extend({
urlRoot: CURRENT_URL+'user',
defaults: {
name: '',
age: 22,
email: ''
},
initialize: function(){
}
});
user = new mUser({'id':1});
var x = user.fetch({
error: function(model, xhr, options){
alert('Error on fetch')
console.log(xhr.responseText);
},
success: function(model, response, options) {
alert(user.toJSON());
}
})
console.log('x email',x.email)
As I mentioned, the responseText does have the data I expect to see from the server, which is:
{'id':'1','name':'joe','age':'25','email':'joe#example.com'}
Maybe I should mention that I'm, doing this as part of a PhoneGap android app. I don't think it's significant to the problem I'm having but it does limit my debugging options.
You are probably getting a parsererror when jQuery tries to parse the JSON response from your server. To check if you're getting a parsererror, add a complete callback and check the textStatus parameter. e.g.
user.fetch({
complete: function(xhr, textStatus) {
console.log(textStatus);
}
});

Categories