Welcome Guest, Not a member yet? Register   Sign In
Continuous Loop in form validation
#1

[eluser]yorvik[/eluser]
Hello I have this litte code where I update value of the database with jquery AJAX.
Code:
class Art_controller extends Controller {

    function input() {
        $this->load->helper('form');
        $this->load->helper('html');
        $this->load->model('art_model');

        $query = $this->art_model->get_records($this->uri->segment(3));

        if ($query) {
            $data['records'] = $query;

            $data['main_content'] = 'editwork_form';
            $this->load->view('includes/template', $data);
            
        }
    }

    function submit()
    {
        //load form validation
        $this->load->library('form_validation');
        $this->load->model('art_model');
        //set form rules
        $this->form_validation->set_rules('kunstwerk', 'Kunstwerk', 'trim|required|min_length[5]');
        

        //run form validation
        $success = $this->form_validation->run();

        //if the validation was a success
        if ((IS_AJAX && $success) || (!IS_AJAX && $success)) {
            echo "Congradulations, your form was accepted!";
            $data = array(
                        'schilderijNaam' => $this->input->post('kunstwerk'),
                        'kunstenaarId' => $this->input->post('kunstenaarID')
                    );
            $this->art_model->edit_record($this->uri->segment(3), $data);
        }
        //if validation failed
        else {
            echo strip_tags(validation_errors());
        }
    }
}

Now i load this view: (but when I typ $artwork less than 5 caracters I get in an continous loop) I want my errors to be showed but that is not the case. Can someone help?

Code:
<h1>Edit artwork!</h1>
<fieldset>
    <legend>Art information</legend>
    &lt;?php
    $attributes = array('id' => 'myForm');
    echo form_open('art_controller/submit/' . $this->uri->segment(3), $attributes);

    if (isset($records)) : foreach ($records as $row) :
    ?&gt;
    &lt;?php
            echo '<label for="kunstwerk">Kunstwerk: </label>' . form_input('kunstwerk', set_value('kunstwerk', $row->schilderijNaam));
            echo '<label for="kunstenaarId">Kunstenaar: </label>' . form_input('kunstenaarId', set_value('kunstenaarId', $row->kunstenaarId));
            echo '<label for="categorieId">Categorie: </label>' . form_input('categorieId', set_value('categorieId', $row->categorieId));

            echo '<label for="oplage">Oplage: </label>' . form_input('oplage', set_value('oplage', $row->oplage));

            echo '<label for="afmetingen">Afmetingen: </label>' . form_input('afmetingen', set_value('afmetingen', $row->afmetingen));
            echo '<label for="prijs">Prijs: </label>' . form_input('prijs', set_value('prijs', $row->prijs));

            $dataTextarea = array(
                'name' => 'infoNL',
                'id' => 'infoNL',
                'value' => set_value('infoNL', $row->infoNL),
                'rows' => '5',
                'cols' => '32'
            );

            echo '<label for="infoNL">Info NL: </label>' . form_textarea($dataTextarea);


            $dataTextarea = array(
                'name' => 'infoNL',
                'id' => 'infoNL',
                'value' => set_value('infoEN', $row->infoEN),
                'rows' => '5',
                'cols' => '32'
            );
            echo '<label for="infoEN">Info EN: </label>' . form_textarea($dataTextarea);

            echo '<label for="datum">Date: </label>' . form_input('datum', $row->datum);

            echo form_submit('submit', 'Edit Work', 'id="submit"');
            echo form_close();
    ?&gt;
        
    &lt;?php endforeach; ?&gt;
    &lt;?php else : ?&gt;
            
                <h2>No records were returned</h2>            
            
    &lt;?php endif; ?&gt;
                <div id="error"></div>            
            </fieldset>            
            
            [removed]            
                $(document).ready(function() {            
                    $("form").submit(function(e) {            
                        e.preventDefault();            
                        v_kunstwerk = $('input[name="kunstwerk"]').val();            
                        v_kunstenaarID = $('input[name="kunstenaarId"]').val();            
                        v_categorieID = $('input[name="categorieId"]').val();            
                        v_oplage = $('input[name="oplage"]').val();            
                        v_prijs = $('input[name="prijs"]').val();            
                        v_date = $('input[name="datum"]').val();            
                                  
                        if (v_kunstwerk != null) {            
                            $.ajax({            
                                url: 'http://localhost/codeIgniter/index.php/art_controller/submit/&lt;?php echo$this->uri->segment(3); ?&gt;',
                    type: 'POST',
                    data: {
                        kunstwerk: v_kunstwerk,
                        kunstenaarID: v_kunstenaarID,
                        categorieID: v_categorieID,
                        oplage: v_oplage,
                        prijs: v_prijs
                    },
                    success: function(data) {
                        alert(data);
                        
                        $('#error').text(data);
                    }
                });
            }
            
        });

    });

[removed]

Edit: I fixed the problem with the following code.
#2

[eluser]Nick_MyShuitings[/eluser]
I don't have to much time to read or test all of that... but you have an error here:

Code:
if ($kunstwerk = $this->input->post('kunstwerk'))

You would want this I think:

Code:
if ($kunstwerk == $this->input->post('kunstwerk'))
#3

[eluser]yorvik[/eluser]
I edited the error, but it's not that what's causing trouble, my function index() keeps getting viewed in an continues loop.
#4

[eluser]Nick_MyShuitings[/eluser]
this is the other section that seems odd:

Code:
if($this->form_validation->run() == FALSE)
                {
                  $this->input();
                }

What is the functionality of $this->input(); ?
#5

[eluser]cideveloper[/eluser]
I always have a hard time explaining form validation but I will attempt to help and kinda figure out what is going on here.

Code:
$this->form_validation->run() == FALSE

runs initially when the form has not been submitted to be validated or when validation fails.
So when you say

Code:
$artwork= $this->form_validation->set_rules('kunstwerk', 'Kunstwerk', 'trim|required|min_length[5]');
               if($this->form_validation->run() == FALSE)
                {
                  $this->input();
                }

and $artwork is <5 then you will just rerun the input function. Since you are not redirecting or anything else like that

Code:
$kunstwerk == $this->input->post('kunstwerk')

will be true again, and validation will fail again and you will go back to input function. voila infinite loop.

what I dont understand is why you are setting the variables

Code:
$artwork= $this->form_validation->set_rules('kunstwerk', 'Kunstwerk', 'trim|required|min_length[5]');

$kunstwerk == $this->input->post('kunstwerk')

why wouldnt you just do this

Code:
$this->form_validation->set_rules('kunstwerk', 'Kunstwerk', 'trim|required|min_length[5]');

$this->input->post('kunstwerk')

also in your ajax call

Code:
url: [removed]

I assume you are sending a 3rd segment in the uri?
#6

[eluser]Twisted1919[/eluser]
[quote author="Nick_MyShuitings" date="1294381432"]I don't have to much time to read or test all of that... but you have an error here:

Code:
if ($kunstwerk = $this->input->post('kunstwerk'))

You would want this I think:

Code:
if ($kunstwerk == $this->input->post('kunstwerk'))
[/quote]

Code:
if ($kunstwerk = $this->input->post('kunstwerk'))
This is correct, however, the post() method return false if the $_POST key is not set, so it is better to do something like :
Code:
$kunstwerk = $this->input->post('kunstwerk');
if(!empty($kunstwerk))
{
//because $kunstwerk may be set but also it can be empty, and you don't want this.
[...]
}

Just as a sidenote
Code:
if ($kunstwerk == $this->input->post('kunstwerk'))
always validates to true, so be careful.
#7

[eluser]yorvik[/eluser]
Ok I edited the suggestions, now I am using
Code:
if($this->form_validation->run() == FALSE)
{
redirect('/art_controller/index/', 'refresh');
}

This works but I am still not able the show the message errors on my view. Is there any way I could realise this

My ajax url is:
url: ...art_controller/input/22
My 3rd segment is the ID of the Current record I am updating in the database.
#8

[eluser]Twisted1919[/eluser]
[quote author="yorvik" date="1294419677"]Ok I edited the suggestions, now I am using
Code:
if($this->form_validation->run() == FALSE)
{
redirect('/art_controller/index/', 'refresh');
}

This works but I am still not able the show the message errors on my view. Is there any way I could realise this

My ajax url is:
url: ...art_controller/input/22
My 3rd segment is the ID of the Current record I am updating in the database.[/quote]

As you are doing, you won't get the errors because you refresh the webpage. You can, however, do something like this:
[code]
if($this->form_validation->run() == FALSE)
{
$this->session->set_flashdata('form_error',validation_errors());//set here before redirect
redirect('art_controller/index', 'refresh');
}
// AND in your views, simply do a :
echo $this->session->flashdata('form_error');
[code]

This will work for sure. Your initial idea was the bad one, because you were refreshing the page therefore resetting everything .
#9

[eluser]yorvik[/eluser]
I found a good tutorial on CI , form_validation and AJAX. I rebuild my code and now it's working. You can view my sollution in the first post. I think this problem is solved or could my code be more best practice?
#10

[eluser]cideveloper[/eluser]
A couple things I would change.

1) your javascript

Code:
$('#myForm').submit(function(e){
    e.preventDefault();
    v_kunstwerk = $('input[name="kunstwerk"]').val();
    if (v_kunstwerk != null) {
        $.post($(this).attr('action'),$(this).serialize(),function(data){
            $('#error').text(data);
        }, 'text');
    }
});


This way you can take this file out of your views and put it into an external js where it belongs.


Also in your code if Javascript is disabled and the form is submitted the user will be sent to art_controller/submit/22 and if validation fails they will just see the error message and NOT be sent back to the form with the error.

Not good in my opinion

I will update soon with a controller I think will be better




Theme © iAndrew 2016 - Forum software by © MyBB