Welcome Guest, Not a member yet? Register   Sign In
[solved] don't understand javascript variable scope; now talking about validation plugin
#1

[eluser]SPeed_FANat1c[/eluser]
Code:
function name_free(value, element){    //validation rule
    var result;
    if($('input[name="name"]').val() != value)
    {
        //console.log($('input[name="name"]').val());
        $.post(CI.base_url + "admin_/info_psl/name_check_ajax", { pavadinimas: value}, function(data){    
            //console.log(data);
            if(data == 'true')
                result = true;
            else result = false;
         });
    }
    else result = true;    //jei vienodi tai viskas ok
    console.log(result);
    return result;
}

when
Code:
if($('input[name="name"]').val() != value)
is true

result is not set, it is undefined. It is outside the callback funciton, so why it is not set? How do I set it?
#2

[eluser]Victor Michnowicz[/eluser]
The problem is that you are using AJAX. This means that your $.post is asynchronous. So your "return result;" is being run way before you AJAX request has even finished. You can make your $.post synchronous like so:

Code:
$.ajaxSetup({async:false});

However, I would guess that there is probably a better way to accomplish what you are trying to do.
#3

[eluser]danmontgomery[/eluser]
move the result declaration outside of the function.

Code:
var result = false;
function name_free(value, element) {
    if(something) {
        $.post('something', { foo: bar }, function(data) {
            if(data == 'true') result = true;
        }
    }
    console.log(result);
    return result;
}
#4

[eluser]SPeed_FANat1c[/eluser]
I made in other way, using remote rule:
Code:
$('input.save').click(function() {
        
        $('form').attr( 'target', '' );
        
        valid = $(".edit").validate({        
            
            rules: {
                 input_pavadinimas: {
                  required: true,
                  maxlength: 20,
                  //name_free: true    //custom metodas
                  remote: {
                      url: CI.base_url + "admin_/info_psl/name_check_ajax",
                      type: "post",
                      data: {
                        pavadinimas: function() {
                          return $("input[name='input_pavadinimas'").val();
                        },
                        current_name: function(){
                            return $('input[name="name"]').val()
                        }
                      }
                  }
                },
                text: {
                    required: true
                }
                
            },
            messages: {
                input_pavadinimas:{
                    required: "Neįvedėte pavadinimo",
                    maxlength: "Maksimalus ilgis - 20 simbolių"
                },    
                
                text: {
                    required: "Neįvedėte teksto"
                }
            }
            
        }
                
        
        ).form();
        //alert('');
        if(valid)
            alert('valid');
        else alert('not valid');
   //         document.myform.submit();
    });

But the problem is: sometimes I get alert "valid", when I enter invalid data, but also it shows an error near the field. Have you idea how can that be?
#5

[eluser]Fabdrol[/eluser]
[quote author="noctrum" date="1295986631"]move the result declaration outside of the function.

Code:
var result = false;
function name_free(value, element) {
    if(something) {
        $.post('something', { foo: bar }, function(data) {
            if(data == 'true') result = true;
        }
    }
    console.log(result);
    return result;
}
[/quote]

That way false is returned every time, since return result; will be called before result can be set to true by $.post.

You should move whatever you want to do with result to within the callback function!
#6

[eluser]Fabdrol[/eluser]
[quote author="SPeed_FANat1c" date="1295987437"]I made in other way, using remote rule:
Code:
$('input.save').click(function() {
        
        $('form').attr( 'target', '' );
        
        valid = $(".edit").validate({        
            
            rules: {
                 input_pavadinimas: {
                  required: true,
                  maxlength: 20,
                  //name_free: true    //custom metodas
                  remote: {
                      url: CI.base_url + "admin_/info_psl/name_check_ajax",
                      type: "post",
                      data: {
                        pavadinimas: function() {
                          return $("input[name='input_pavadinimas'").val();
                        },
                        current_name: function(){
                            return $('input[name="name"]').val()
                        }
                      }
                  }
                },
                text: {
                    required: true
                }
                
            },
            messages: {
                input_pavadinimas:{
                    required: "Neįvedėte pavadinimo",
                    maxlength: "Maksimalus ilgis - 20 simbolių"
                },    
                
                text: {
                    required: "Neįvedėte teksto"
                }
            }
            
        }
                
        
        ).form();
        //alert('');
        if(valid)
            alert('valid');
        else alert('not valid');
   //         document.myform.submit();
    });

But the problem is: sometimes I get alert "valid", when I enter invalid data, but also it shows an error near the field. Have you idea how can that be?[/quote]

What plugin are you using?
#7

[eluser]SPeed_FANat1c[/eluser]
I am using form validation plugin.

Edit: made a short version:
Code:
<scri+pt src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js" type="text/javascript"></scri+pt>
<s+cript  src="http://www.ylakiudarzelis.lt/js/jquery.validate.js" type="text/javascript"></s+cript>
<scr+ipt>
$(function(){
$('input.save').click(function() {
        
        $('form').attr( 'target', '' );
        
        valid = $(".edit").validate({        
            
            rules: {
                 input_pavadinimas: {
                  required: true,
                  maxlength: 20,
                
                remote:  "http://www.ylakiudarzelis.lt/admin_/info_psl/name_check_ajax"
                }                
            }
        
            
        }
                
        
        ).form();
        //alert('');
        if(valid)
            alert('valid');
        else alert('not valid');
            //document.myform.submit();
    });

    
});

</scr+ipt>

&lt;form action="http://www.ylakiudarzelis.lt/test/valid" method="post" class="wide edit" name="myform"&gt;
    
    
        <br /><label for="label">Puslapio pavadinimas:*</label>
&lt;input type="hidden" name="name" value="asdasd" /&gt;
&lt;input type="text" name="input_pavadinimas" value="asdasd" maxlength="20" size="10" style="width:20%"  /&gt;&lt;br /><br />        
         <br>
        
        &lt;input class = "save" type="button" value="Išsaugoti" /&gt;
    
    
&lt;/form&gt;

php validation always echoes false
Code:
function name_check_ajax()
    {
        echo 'false';
    }


When I run this code, I get an alert "valid" and after alert the message appeards near input field - "Please fix this field."

What do I need to change there so the variable "valid" could be set to false?
#8

[eluser]Fabdrol[/eluser]
where's the "invalid" message (next to the field) set? does that happen inside the form plugin?
I'm not sure about this, since I don't know that plugin, but I think it works like this:

1. Checks remote source if the form field is valid
2. In the callback of the ajax method (inside the plugin) it attaches the warning to the field
3. The variable "valid" doesn't get populated with false, but either with true, undefined or the original object, if chaining is enabled.

You can check it as this:
Code:
window.console.log(valid) // check the contents of valid in Firebug
if(valid === true) // make sure valid doesn't just exist, it's also actually true
    alert('foo');

Now, if you can post the result of console.log here, I think I can give you a definite answer.
#9

[eluser]SPeed_FANat1c[/eluser]
[quote author="Fabdrol" date="1296066516"]where's the "invalid" message (next to the field) set? does that happen inside the form plugin?
I'm not sure about this, since I don't know that plugin, but I think it works like this:

1. Checks remote source if the form field is valid
2. In the callback of the ajax method (inside the plugin) it attaches the warning to the field
3. The variable "valid" doesn't get populated with false, but either with true, undefined or the original object, if chaining is enabled.

You can check it as this:
Code:
window.console.log(valid) // check the contents of valid in Firebug
if(valid === true) // make sure valid doesn't just exist, it's also actually true
    alert('foo');

Now, if you can post the result of console.log here, I think I can give you a definite answer.[/quote]

Plugin generates the message:

<label for="input_pavadinimas" generated="true" class="error">Please fix this field.</label>

and puts it right after the input field.

In the console I get:

true
XHR finished loading: "http://www.ylakiudarzelis.lt/admin_/info_psl/name_check_ajax?input_pavadinimas=asdasd".

and the foo is alerted.

But I gues I see the problem - it is with that asynchronious thing again. It first returns true, but requst is not finished yet.

Still don't understand then what is the point of the remote validation if it is asyncronoius? It should always wait till request is fishished and then assign value.
#10

[eluser]Fabdrol[/eluser]
Well, that's why there are callbacks. You don't do anything until the callback has returned.
That's why you should put anything you want to do with the returned data in the call back, or set it to run synchronously.

Example (from one of my apps, which features dynamic form creation, so it's a bit more complex. However, you'll get the general idea)
Code:
var has_been_validated = false;

$('#form').submit(function() {
    if(has_been_validated === true) return true;
    else return false;
});

$('#form_submit').click(function() {
    var form_guid     = $('input.form_guid').val(); // hidden input with the form guid.
    var fields = {
        first_name    : $('input[name="first_name"]').val(),
        last_name     : $('input[name="last_name"]').val(),
        email        : $('input[name="email"]').val(),
        message     : $('input[name="message"]').val()
    };
    
    $.post('form/validate', {
        guid: form_guid,
        fields: JSON.stringify(fields)
    }, function(response) {
        var json = JSON.parse(response);
        var errors = 0;
        
        if(typeof json.error !== 'undefined') {
            $.each(json.error, function(i, error) {
                errors++;
                $('.error .' + error.field_name).html(error.message).show();
            });
            
            $('.total_errors').html(errors + ' errors were found. Please correct them.').show();
        } else {
            has_been_validated = true;
            $('#form').submit();
        }
    });
});

Note: the example sends a json-encoded hash and a guid of the form to the back end, which then checks the database for the validation rules for each field in the hash and runs them (based on the guid). Then, the system returns a json object with either an array of errors, or not, and displays each error in the form.

When there are no error's, form.submit() is called. For some extra security, a simple check is added to make sure that the form has been validated.

Be aware that you should always check the form on the server - since any handy script kiddy could set has_been_validated to true using the console, and then run $('#form').submit(). In my actual server code, the form has no classes and the name and id are form_{guid}, so it's harder to guess. However, it also checks the data on the server since javascript doesn't garantuee anything.

On the server, it rejects the form if the GUID doesn't exist, or is tampered with. It also rejects the form if one of the rules isn't met.

There's another way to do this, which doesn't involve AJAX. When the page load, you pass an json object with all validation rules for the form to the page. Then you implement a custom validation class in Javascript (modelled after the one you use on the serverside) and do all the checking in javascript itself. No server involvement, that is, of course, until you actually sent the data.

Fabian




Theme © iAndrew 2016 - Forum software by © MyBB