Help with passing form values via ajax (jquery) to codeigniter form validate.

#1
[eluser]dottedquad[/eluser]
The way my form is setup is, I'm not posting the values to the server. Instead, I'm using jquery tools for client side validation and used e.preventDefault(); to prevent any form submit logic. When the client-side validation passes I do:

Code:
var $field_values = "species/" + $fld_species + "/alias/" + $fld_alias + "/parents/" + $fld_parents + "/gender/" + $fld_gender + "/breed/" + $fld_breed + "/birth_date/" + $fld_birth_date + "/location/" + $fld_location + "/comment/" + $fld_comment;
            
                    // submit the data to the server with AJAX
                    $.getJSON("validate_livestock_form/index/" + $field_values, function(json) {

That code works as expected. Now, my question is, with the codeigniter form validation library I think it requires an actual form submit for it to work. Am I correct? If I am, is there a way to fake a post like send a header or something along those lines to get the codeigniter form validation to work with my $.getJSON? It's hard to explain what I'm asking so please let me know if I need to elaborate more.

-Rich

#2
[eluser]dottedquad[/eluser]
controller code:
Code:
class Validate_livestock_form extends Controller
{
    
    function index()
    {
        $array = $this->uri->uri_to_assoc(3);
        $species = $array['species'];
        
        $seg = $this->uri->segment(3);
        echo $seg;
        
        $validated_field = array();
        
        echo 'species: '.$species;
        
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('species', 'Species', 'callback_species_check');
        
        if ($this->form_validation->run() == FALSE)
        {
            echo "Errors Found: " . json_encode($validated_field);
        }
        else
        {
            echo 'No Errors!';
        }
    }
    
    function species_check($str)
    {
        if ($str != '1')
        {
            $validated_field['species'] = "Please select a species!";
        }
        else
        {
            return TRUE;
        }
    }
    
}

I point my browser to: http://localhost/lsms/index.php/validate_livestock_form/index/species/1

species is supposed to represent the get variable and 1 is supposed to represent the value. Since it's not a query string it doesn't seem to work with the codeigniter validation form library. $this->form_validation->set_rules('species', 'Species', 'callback_species_check'); is looking for the species field, but my form isn't submitting traditionally and as i stated in my above post i'm passing the values in the uri and ajaxing them over to the validate_livestock_form.php controller.

With all that said, how do I get this jquery/ajax and codeignite validation library to work in harmony?

-Thanks,
Rich

#3
[eluser]pickupman[/eluser]
Form validation works on input fields and not the query/uri string. Switch it up a little to play nice. Not sure on your form field names, since they were not posted, but this will post all fields in form to your controller.
Code:
$("#your-form").submit(function(){
   return false;

   $.ajax({
      data: $(this).serialize(),
      dataType: 'json',
      url:  'validate_livestock_form/index',
      type: 'POST',
      success: function(data, status){
         //Do something here
         alert(data.species);
      }
   });
});

#4
[eluser]dottedquad[/eluser]
[quote author="pickupman" date="1276156865"]Form validation works on input fields and not the query/uri string. Switch it up a little to play nice. Not sure on your form field names, since they were not posted, but this will post all fields in form to your controller.
Code:
$("#your-form").submit(function(){
   return false;

   $.ajax({
      data: $(this).serialize(),
      dataType: 'json',
      url:  'validate_livestock_form/index',
      type: 'POST',
      success: function(data, status){
         //Do something here
         alert(data.species);
      }
   });
});
[/quote]

That did the trick! One more question. I am brand new to OOP and passing values to arrays from one function to another. First here's an explanation of how the client-side validation error messages work. When I pass the values to the server-side and they get validated, when there are errors, I need to take the field name along with an error msg into a JSON form. Then grab the JSON data during the success section of the ajax jquery call(which is the easy part).

controller code:
Code:
<?php
class Validate_livestock_form extends Controller
{
    
    function index()
    {
        
        $validated_field = array();
        
        //echo 'species: '.$species;
        
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('species', 'Species', 'callback_species_check');
        
        if ($this->form_validation->run() == FALSE)
        {
            echo json_encode($validated_field);
        }
        else
        {
            echo json_encode($validated_field);
        }
    }
    
    function species_check($str)
    {
        if ($str != '1')
        {
            
            $validated_field['species'] = "Please select a species!";
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
    
}
?>

Notice the code: $validated_field = array(); in the index function? Well, I'm trying to pass values as stated above in the species_check function to the $validate_field array in the index function. The issue i'm running into is, the values are not staying. What should I do to keep the values to stay within the $validate_field array?

-Thanks,
Rich

#5
[eluser]pickupman[/eluser]
You can create variables in your controllers construct function.
Code:
class Validate_livestock_form extends Controller
{
   var $validated_fields;
  
   function Validate_livestock_form(){
      $this->validated_fields = 'something';
   }

   function index(){
      //Can access validated_fields
      echo $this->validated_fields;  //echoes 'something'

      //access another method
      echo $this->species_check(1);
   }

    function species_check($str)
    {
        if ($str != '1')
        {
            
            $validated_field['species'] = "Please select a species!";
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
}

#6
[eluser]dottedquad[/eluser]
[quote author="pickupman" date="1276159857"]You can create variables in your controllers construct function.
[/quote]

Controller code:
Code:
<?php
class Validate_livestock_form extends Controller
{
    var $validated_fields;
    
    function Validate_livestock_form(){
        parent::Controller();
        
        $this->$validated_fields = array();
    }
    
    function index()
    {
        //echo 'species: '.$species;
        
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('species', 'Species', 'callback_species_check');
        
        if ($this->form_validation->run() == FALSE)
        {
            echo json_encode($this->$validated_fields);
        }
        else
        {
            echo json_encode($this->$validated_fields);
        }
    }
    
    function species_check($str)
    {
        if ($str != '1')
        {
            
            $this->$validated_fields['species'] = "Please select a species!";
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
    
}
?>

I'm receiving this error:
A PHP Error was encountered

Severity: Notice

Message: Undefined variable: validated_fields

Filename: controllers/validate_livestock_form.php

Line Number: 9

Fatal error: Cannot access empty property in C:\wamp\www\lsms\system\application\controllers\validate_livestock_form.php on line 9

I have var $validated_fields; in the class so there should be an empty variable ready to be manipulated. the notice stated undefined variable... What does it mean by undefined and how do I define it? I'm also a bit confused with the Fatal error: Cannot access empty property message. Of course it's empty, by default there shouldn't be anything assigned to it. The point of the species_check function is to check validation if it's true assign some values to the $validated_fields array which has been stated. What should I do/change to fix this issue?

-Thanks,
Rich

#7
[eluser]dottedquad[/eluser]
Whoops! I placed $ signs in $this->$validated_fields All is working! Thank you very much! now I just have to finish my script with the rest and all is well.

-Rich

#8
[eluser]pickupman[/eluser]
I had used procedural php for so long, I made myself read a book on OOP and that helped quite a bit. OOP can be powerful because you can get/set variables/properties in several different ways.

Glad you got it.

#9
[eluser]dottedquad[/eluser]
[quote author="pickupman" date="1276192980"]I had used procedural php for so long, I made myself read a book on OOP and that helped quite a bit. OOP can be powerful because you can get/set variables/properties in several different ways.

Glad you got it.[/quote]

I've been using php for basic coding but nothing in depth. The current personal project I'm working on now is forcing me to change my coding ways. So far I'm enjoying this.

-Rich


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.