Mootools code for success, failure and submit - javascript

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)

Related

Unexpected behavior with setTimeout

I have implemented an ajax polling function that I need to call continuously until the polling results come back with my expected results. In order to accomplish this, I am using setTimeout to introduce a delay so that the function doesn't just hammer the server with requests until it gets the results.
Let me preface this by saying that I have already found the way I need to implement the code to get the expected behavior I need. But, my question is in regards to the solution I found. I want to know why the solution worked with the timeout correctly, while the other one did not.
Here is the working code that successfully sets a timeout and polls for the result:
function makeRequest(url, data, requestType, successCallback, errorCallback, doneCallback) {
$.ajax({
url: url,
type: requestType,
data: data != null ? JSON.stringify(data) : '',
contentType: 'application/json; charset=utf-8',
success: function (success) {
if (successCallback) successCallback(success);
},
error: function (error) {
if (errorCallback) errorCallback(error);
},
done: function() {
if (doneCallback) doneCallback();
}
});
}
function pollForResult(Id) {
setTimeout(function () {
makeRequest('/Transaction/TransactionResult/' + Id,
null,
"GET",
function(result) {
//success code here
}, function(error) {
//error callback implementation here
if (error.status === 404) {
pollForResult(Id); //results not ready, poll again.
} else {
alert("stopped polling due to error");
}
}, null);
}, 2000);
}
Here is the code that doesn't properly set a timeout and just continually hits the server with requests:
function pollForResult(Id) {
makeRequest('/Transaction/TransactionResult/' + Id,
null,
"GET",
function(result) {
//success code here
}, function(error) {
//error callback implementation here
if (error.status === 404) {
setTimeout(pollForResult(Id), 2000); //results not ready, poll again.
} else {
alert("stopped polling due to error");
}
}, null);
}
So, my question is this: what is it about the second block of code that makes it continually poll the server for results instead of waiting the 2 seconds to poll again?
I suspect, although I haven't tried, that this would work properly in the second block of code:
setTimeout(function(){ pollForResult(Id); }, 2000); //results not ready, poll again.
setTimeout(pollForResult(transactionId),2000);
This code immediately calls pollForResult and assigns its return value to be the function called when the timeout occurs.
This is desired behaviour, because you might have a function that builds a closure and passes that to the timeout. However it seems to catch out a lot of people...
As you said, function() {pollForResult(transactionId);} will work just fine.

Callback basics using Backbone.js

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

Insert HTML using jQuery

I have two pieces of code, first of all I have my code which toggles open a div with an included close button:
http://jsfiddle.net/spadez/uhEgG/27/
$(document).ready(function () {
$('#country').click(function () {
$("#country_slide").slideToggle();
});
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
});
Then I also have my Ajax code which is designed to fire when the div has been opened:
$(function () {
$('#country_link').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
return false;
});
});
What I am stuck with now is, how do I make the ajax only execute when the div is being opened? Because I am working with a toggle and close button it seems difficult to work out what the click is doing, whether it is opening it or closing it.
I guess my options are to have some kind of flag or alternatively have some "if" code, so if class is equal to .hidden then do not execute. I haven't been able to integrate either of these solutions and I am unsure if either of them is the proper way to achieve this.
Include the check as part of your slide function:
$("#country_slide").slideToggle(function() {
if ($(this).is(":visible")) {
alert("im visible!");
}
});
Demo: http://jsfiddle.net/tymeJV/uhEgG/28/
if($("#country_slide").is(":visible"))
//call ajax
This code adds data to the element, to check if it's already loaded next time you click on it.
Currently I am not able to test it, so it may contain errors.
$(function () {
$('#country_link').on('click', function (e) {
// Prevent from following the link, if there is some sort of error in
// the code before 'return false' it would still follow the link.
e.preventDefault();
// Get $link because 'this' is something else in the ajax request.
var $link = $(this);
// Exit if the data is loaded already
if ($link.data('loaded') === true)
return false;
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
// If successful, bind 'loaded' in the data
$link.data('loaded', true)
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
});
});

add global callback to $.ajaxSetup

I am use $.ajaxSetup to use a global authorization method, and global error handling in my site. I would like to pass a callback function into the global error method so I can call the function whenever I need to in the global error handler. Here is my $.ajaxSetup:
$.ajaxSetup({
global: false,
// type: "POST",
beforeSend: function (xhr) {
//The string needs to be turned into 'this.pasToken'
//if not us, don't include
if(app.cookieAuth)
xhr.setRequestHeader("Authorization", _this.pasToken);
},
statusCode: {
401: function(){
//Redirect to the login window if the user is unauthorized
window.location.href = app.loginUrl;
},
//This is where I need help
403: function(error, callback){
//Show an error message if permission isn't granted
callback(error);
alert(JSON.parse(error.responseText)['Message']);
}
}
});
Note the 403: status code. I am trying to pass in a callback function, but I don't know how to do it from the individual ajax calls. Anyone have an idea?
The easiest solution; define your own property for ajax options.
$.ajaxSetup({
statusCode: {
403: function(error, callback){
this.callback403(error);
}
}
});
$.ajax({
callback403: function () {}
});
Note, if you change the context option of the ajax request, this may not work.
I am not sure if this is what you are looking for:
$.ajax({
statusCode: {
404: function() {
alert("page not found");
}
}
});

Javascript: How to stop multiple jQuery ajax error handlers?

A team member put this into our project
$(function() {
$("body").bind("ajaxError", function(event, XMLHttpRequest, ajaxOptions, thrownError){
alert(thrownError);
});
}
However I want to supress one of my errors (as it would be noise and verification isn't needed)
function blah() {
...
errFunc = function(event, xhr, opts, errThrown) {
//what could I do here?
//event.stopImmediatePropagation()?
}
$.ajax({
url : '/unimportant_background_refresh',
type : 'GET',
data : { },
dataType : 'json',
success : updateBackgroundStuff,
error : errFunc, // Suppresses error message.
});
}
How can I stop the catch all error from happenning please? Can I just do something in the error function such as { event.StopPropogation(); } or must I work out some mechanism for having the catch all selectively ignore things please?
Global events can be disabled, for a particular Ajax request, by passing in the global option, like so:
$.ajax({
url: "test.html",
global: false,
// ...
});
Taken from: http://docs.jquery.com/Ajax_Events
I would just throw a boolean into your code that's defaulted to false. Set it to true the first time the error is thrown and make sure to check for true at the start of the error function.
Something like:
function blah() {
var errorHappened = false;
...
errFunc = function(event, xhr, opts, errThrown) {
if (errorHappened)
return;
errorHappened = true;
// handle the errror.
}
// the rest of your code
}

Categories