I have the following function:
function validateField(target, field, field_check) {
if(target.val().trim().length > 0) {
$.ajax({
url: '<?php echo $html->url('/fonykers/validate_',true); ?>'+ field + '/' + target.val(),
dataType: 'json',
type: 'POST',
success: function(response) {
if(!response.ok) {
if(target.is('.ok')) {
target.removeClass('ok');
}
target.addClass('error');
error.html(response.msg);
error.fadeIn();
field_check = false;
} else {
if(target.is('.error')) {
target.removeClass('error');
}
target.addClass('ok');
alert('voy a asignar true');
field_check = true;
}
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
field_check = false;
}
});
} else {
error.html('You must specify a ' + field);
error.fadeIn();
target.addClass('error');
field_check = false;
}
}
I use it to validate my form input fields, the target variable es the field itself, for instance: $('#name_field') the 2nd variable es a string specifying the name of the field for instance name as to know what PHP function it’s gonna call. The last is a boolean that I use to know wether or now the field is valid or not for instance name_check which I define at the beginning of the scripta and set to false.
My problem is that field_check gets changed in the local scope properly but it never modifies que external variable that has been passed in, what am I doing wrong?
Primitive variables (int / boolean / etc) are passed to functions by value – that is, when someone passes one of them to a function, the value of the variable is passed to your function, not the variable itself. What you’re modifying is in fact a different variable altogether.
The easiest solution is to just return true or false when you’ve finished validating the field, and use the function’s return value instead of checking
field_check.You can also do a couple different things with globals / properties. For instance…
Note the use of
this.field_checkand the assignment of the function to a variable