CodeIgniter Forums

Full Version: [solved] don't understand javascript variable scope; now talking about validation plugin
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2

El Forum

[eluser]SPeed_FANat1c[/eluser]
Quote: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.

I don't understand this part - how we can validate something that needs to checked in database without using AJAX?

In general I already have done some validation with ajax and it worked, but this time I thought - why make my own functions if I can use something that is doen already - the plugin. And this plugin is actually cool thing, but it is interesting why the async is not made false by default there? Because othervise I don't see the point. Or is this a bug. I guess I need to ask this in jquery forums and see what they tell.

Damn it took quite a bit of time - I am trying to solve this since yesterday mornig Big Grin I would have done my own ajax validation much faster, did not think that it will take so long to solve such simple problem as it looks at the beginning.

Edit:
Quote:Be aware that you should always check the form on the server
I am doing this for admin side, so no need to validate in server, and in case javascrip is off, admin will not be able to submit at all.

Thank you guys for help.

El Forum

[eluser]Fabdrol[/eluser]
Well, that depends. If you actually need to validate the contents of the field agains something in the database, you could use AJAX. But, if it isn't sensible information, you could also load the value it should be at page load, and then check against that. If it ís sensitive information, I wouldn't check it using javascript at all.

Example, what you could do:
1. In your controller loading the form.
Code:
public function edit($page_id) {
    $field_should_be = 'foo';
    $data['form_contents'] = $this->page->id($page_id);
    $data['validations'] = json_encode(array(
        'first_name' => 'required|min(5)|max(10)',
        'last_name' => 'required',
        'email' => 'required|email',
        'other_field' => 'required|should_be('.$field_should_be.')'
    ));
    $this->load->view('form');
}

Then, on the page, you could do something like this:
Code:
var validations = <?=$validations?>; // gets loaded as an json object

$('form').submit(function() {
    var valid = true;
    for(key in validations) {
        var rules = validations[key];
        var field = key;

        if($('input[name="'+field+'"]').validates(rules) !== true) {
            valid = false;
        }
    }

    return valid;
});

In the above case you should implement a jQuery plugin "validates" which handles the rules you supplied via php. It's a bit more work than simple validation, but it'll be worth the effort: you can use it among all your projects and never need to rewrite it!

Fabian

El Forum

[eluser]Fabdrol[/eluser]
Anyway, why the validation plugin is async? I recon because it doesn't clock up the interface during request. I mean, what's the point of AJAX if you have to wait for the request to finish? That defeats the whole purpose: you could do a 'normal' request just as easily, would take the same amount of time and it requires less effort to program.

I think the best solution depends on your specific problem. Some applications actually need to dynamically check the server, and you don't want a reload, you should use an Asynchronous request using javascript. However, everything you want to do with the request should be done at in the callback function for it to work. The last post I posted is a solution I would probably prefer, since it would be DRY. I could implement a Library at the server side which takes the same rules as the jquery plugin doing the checking on the client side. That way, I could port that code to every application I build that needs it.

Downside is the extra work. However, I've come far enough in web development to prefer writing my own libraries above using existing ones for stuff like this. The CI validation library is great, however, I don't really like the syntax and it's not flexible enough. I'd want to be able to dynamically add rule methods. So I'd write my own. But agian, that's my choice ;-)

El Forum

[eluser]SPeed_FANat1c[/eluser]
Quote:
Code:
public function edit($page_id) {
    $field_should_be = 'foo';
    $data['form_contents'] = $this->page->id($page_id);
    $data['validations'] = json_encode(array(
        'first_name' => 'required|min(5)|max(10)',
        'last_name' => 'required',
        'email' => 'required|email',
        'other_field' => 'required|should_be('.$field_should_be.')'
    ));
    $this->load->view('form');
}

$field_should_be - yeah, if there is one, or few words, then ok. Bt what if there is let's say 1000 words. Its not efective and we need to check in database.

And if there is only one word I can easily to that with the same validation plugin - just add a custom method that takes that words from let's say hidden field and cheks if it maches or not.

Quote:Anyway, why the validation plugin is async? I recon because it doesn’t clock up the interface during request. I mean, what’s the point of AJAX if you have to wait for the request to finish? That defeats the whole purpose: you could do a ‘normal’ request just as easily, would take the same amount of time and it requires less effort to program.

I understand, AJAX in general should be asynchroniuos. But when we use "remote" method, I can't think of when it can be asynchroniuos. So I think when we decide to use "remote" it should automatically make asycn:false. This probably should be possible, I haven't writen a plugin ever, so don't know Smile


And I can show one more interesting thing. There is another way to validate with this plugin, but I didn't use it, because it need that button type submit.
Code:
$(".edit").validate({
        
         submitHandler:function(form) {
        
         form.submit();
        
        
        
        
        },
        rules: {
             input_pavadinimas: {
              required: true,
              maxlength: 20,
              remote: {
                url: "http://www.ylakiudarzelis.lt/admin_/info_psl/name_check_ajax",
                type: "post",
                data: {
                  
                    current_name: function(){
                        return $('input[name="name"]').val()
                    }
                  }
                //async:false,
                
                }    
            },
            
            text: {
                required: true
            }
            
        },
    
        
    });

And this validation works even without async:false. As I expect it to work.

So thats the mystery form me why it works diferently when I need submit when I don't have button type submit. Or I just made something different but just don't see. Or.. there is a bug in that plugin. As you can see there is callback, and in it we can put statement to submit form.

However, that does not work when button type is not submit.
Code:
$('input.save').click(function() {
        
        $('form').attr( 'target', '' );
        
        valid = $(".edit").validate({        
         //$(".edit").validate({
            submitHandler:function(form) {    
                
              
               //document.myform.submit();        //this line does not submit
                //form.submit();                //this line also does not submit
                
            //so this callback does not help, we still have to make async:false
              
               },
            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: {
                      
                        current_name: function(){
                            return $('input[name="name"]').val()
                        }
                      },
                     // async:false
                  }
                
                },
                text: {
                    required: true
                }
                
            },
            messages: {
                input_pavadinimas:{
                    required: "Neįvedėte pavadinimo",
                    maxlength: "Maksimalus ilgis - 20 simbolių"
                },    
                
                text: {
                    required: "Neįvedėte teksto"
                }
            }
            
        }
                
        
        ).form();
        
        console.log(valid);     //this is executed before request completes, if async is not false
        //if(valid)                //so we cannot run this line if async is not false, because it will submit even if form is not valid
            //document.myform.submit();
    });

El Forum

[eluser]Fabdrol[/eluser]
I don't think it's a bug, I think it's just the way the plugin was designed/intended by the original author. (that's why I like to write my own plugins, they always do what you want them to do).

The submit function works by binding a method to the submit() method of the form. Now, when you click on the submit button (or call submit() from javascript) that function is executed. In that function you can return true or false, and when you return false, the form isn't submitted.

Thing is, I sort of lost track of what you exactly are validating. Are you validating random content (like the length, or wether it's filled in) or are you checking if the value of a form is a certain value (out of a list of values)? In the last case, ajax validation could make sense, but in the first case, it doesn't. In the last case, what kind of value is it? Is it a user's name, or a city name or whatever?

El Forum

[eluser]SPeed_FANat1c[/eluser]
Just made this code on my test page work:
Code:
$('input.save').click(function() {
        
        $('form').attr( 'target', '' );
      
       valid = $(".edit").validate({        
            submitHandler:function(form) {

            console.log('ok');
//            document.myform.submit(
//            
//                
//                    );
          
            
            
          
               },
            rules: {
                 input_pavadinimas: {
                  required: true,
                  maxlength: 20,
                
                
                    remote: {
                    url: "http://www.ylakiudarzelis.lt/admin_/info_psl/name_check_ajax",
                    type: "post",
                    data: {
                        
                        current_name: function(){
                            return $('input[name="name"]').val()
                        }
                      },
                
                    }    
                }                
            }
        
            
        }
                
        
        ).form();
  
    });


});

It even submits when I uncomment document.myform.submit()

But when I copy paste it in real projenct page, the submit handler is not executed.. Don'k know why. Will have to debug I guess.
Quote:Thing is, I sort of lost track of what you exactly are validating. Are you validating random content (like the length, or wether it’s filled in) or are you checking if the value of a form is a certain value (out of a list of values)?

I am validating menu names. Admin can add add information pages, so also it creates menus. So I need to check if if he does not add the menu with the same name.

Big Grin now just a thought came: why I even use ajax there, there isn't like 10000 menu items, I could just put all menu names in hidden field seperated by ; and check if the admin is not using already taken menu.

El Forum

[eluser]Fabdrol[/eluser]
Even better, you could put the list of menu items in your javascript. Much more easier.

In your controller:
Code:
public function menuEditor() {
    $data['menus'] = json_encode($this->model->menus());
    // ... rest of my code
}

In your view:
Code:
<scr+ipt>
$(document).ready(function() {

var valid = true;
var takenMenus = &lt;?=$menus?&gt;;
// gets loaded as json object, so you can do things like:
for ( i in takenMenus ) {
    var menu = takenMenus[i];
    if(myNewMenu == menu) {
        valid = false;
    }
}

});
</sc+ript>

El Forum

[eluser]SPeed_FANat1c[/eluser]
Thanks, I use this and it works ok.
Pages: 1 2