Hi all
I'm building myself an ajax login and decided to use jQuery for the ajax part.
The part I'm struggling with is the success: function. I am trying to pass a function as a variable to run on success, but I'm having a few issues. It seems to kinda work in FF but Chrome doesn't like it one bit.
Here's what I've got:
Code:
function call_ajax(request_page, params, rewite_div, method, working_message, success_function) {
$.ajaxSetup ({
cache: false
});
$.ajax({
statusCode: {
404: function() {
document.getElementById('alertHeader').innerHTML = '404 Error';
document.getElementById('alertTxt').innerHTML = '<p>The page was not found</p>';
open_error('#alertDiv');
},
401: function() {
document.getElementById('alertHeader').innerHTML = '401 Unauthorized';
document.getElementById('alertTxt').innerHTML = '<p>Authorization required</p>';
open_error('#alertDiv');
}
},
type: method,
url: 'includes/ajax/'+request_page,
data: params,
beforeSend: function () {
// this is where we append a loading image
$(rewite_div).html('<img src="images/spinner.gif" alt="Loading..." /> ');
$(rewite_div).append(working_message);
},
success: function (data) {
// successful request; do something with the data
var obj = jQuery.parseJSON(data);
if(obj.result == 'fail'){
$(rewite_div).empty();
var clean_str = str_replace(obj.reason,"|",'"');
$(rewite_div).html(clean_str);
}else{
success_function; // this is where my problem is
}
},
error: function() {
// failed request; give feedback to user
$(rewite_div).html('Oops, something went wrong...');
}
});
}
Now I'm passing these vars in from my login() function:
Code:
var success_function = function(){locate_to('home.php')};
var params = new Object();
params.username = document.getElementById('username').value;
params.password = $.sha1(document.getElementById('password').value);
call_ajax('login.php',params,'#result_div','POST',' Logging you in...', success_function);
And the function that's actually trying to be called is:
Code:
function locate_to(url){
location.href = url;
}
Now if the user has entered invalid data the json result will be fail, otherwise it's a pass, this part of the 'success' call runs fine, it just doesn't like the success_function var, it just doesn't fire.
I don't get any errors in FireBug, which doesn't help me as I can't see what's going wrong, so I don't think it's a syntax issue.... or I might be wrong.
Does anyone know how to pass a function as a variable to this part of a jQuery ajax call?
Any advise or pointers will be greatfully received as always
EDIT:
I forgot to mention that I would like to keep this call_ajax function as generic as possible so I can reuse this one function for all my ajax requests