Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
719 views
in Technique[技术] by (71.8m points)

php - codeigniter ajax form validation

Hi I’m quite new to jquery -ajax and I’d like some help please to join it with CI.

I have followed this tutorial on Submitting a Form with AJAX and I’d like to add this functionality to my CodeIgniter site. What I’d like to do is when the user submits the form, if there are any validation errors to show the individually on each input field (as in native ci process), or if this is not possible via validation_errors() function. If no errors occured to display a success message above the form.

Here's my code so far:

my view

 // If validation succeeds then show a message like this, else show errors individually or in validation_errors() in a list
<div class="alert alert-success">Success!</div>
<?php echo validation_errors(); //show all errors that ajax returns here if not individualy  ?>

<?php echo form_open('admin/product/add, array('class' => 'ajax-form')); ?>
<p>
    <label for="product_name">Product *</label>
    <input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
    <?php echo form_error('product_name'); ?>
</p>
<p>
    <label for="brand">Brand</label>
    <input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
    <?php echo form_error('brand'); ?>
</p>
...  

my controller

 public function add($id){
           // set validation rules in CI native
           $rules = $this->product_model->rules;
           $this->form_validation->set_rules($rules);

           if ($this->form_validation->run() === true) {
                       // get post data and store them in db
          $data = $this->input_posts(array('product_name', 'brand', 'category_id', 'description'));
          $this->product_model->save($data, $id);
    // no errors - data stored - inform the user with display success-div
     } else {
    // validation failed - inform the user by showing the errors
     }
//load the view
$this->load->view('admin/products/add', $data);
}  

and here’s the js script

 $(document).ready(function () {
 $('form.ajax-form').on('submit', function() {
  var obj = $(this), // (*) references the current object/form each time
   url = obj.attr('action'),
   method = obj.attr('method'),
   data = {};

  obj.find('[name]').each(function(index, value) {
   // console.log(value);
   var obj = $(this),
    name = obj.attr('name'),
    value = obj.val();

   data[name] = value;
  });

  $.ajax({
   // see the (*)
   url: url,
   type: method,
   data: data,
   success: function(response) {
    console.log(response); // how to output success or the errors instead??
   }
  });
  return false; //disable refresh
 });
});  

How should I pass my validation results (either success or the post errors) throught the ajax request and display them on my view?? From some little research I did I've found that you can use a single controller, that holds both the native proccess and the ajax request (instead of using 2 controllers), but my main difficulty is, I don't understand how the results of the validation will pass through the js script and display them on my view?? Please note that I don't want to display anything on an alert box, instead show the results on a div or the errors individualy(if possible).

EDIT I did some changes to my application, here's the code so far:

the controller

public function manage($id = NULL){
    $this->load->library('form_validation');

    $data['categ'] = $this->category_model->with_parents();

    //fetch a single product or create(initialize inputs empty) a new one
    if (isset($id) === true) {
        $data['prod'] = $this->product_model->get($id);
        $data['attr'] = $this->attribute_model->get_by('product_id', $id, null, true);
    } else {
        $data['prod'] = $this->product_model->make_new();
        $data['attr'] = $this->attribute_model_model->make_new();
    }

    if (isset($_POST['general_settings'])) {
        if ($this->form_validation->run('product_rules') === true) {
            // get post inputs and store them in database
            $data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description'));
            $this->product_model->save($data, $id);

            $status = true;
        } else {
            // validation failed
            $status = validation_errors();
        }
        if ( $this->input->is_ajax_request() ) {
            echo json_encode($status);
            exit;
        }
        redirect('admin/product');
    }
    //if (isset($_POST['attributes_settings'])) { the same thing here  }                

    // load the view
    $this->load->view('admin/products/manage', $data);
}

and the js

success: function(response) {
    //console.log(response);
    if (data.status === true) {
        $('#ajaxResults').addClass('alert alert-success').html(response);
    } else {
        $('#ajaxResults').addClass('alert alert-error').html(response);
    };

}

But I'm having some issues

  1. Although I get the error messages from validation_errors() as an alert-error when there are no errors I get the true in an alert-error too, insted of alert-success.

2.how should I return the success message too? eg. a message saying "Saves were done!".

  1. Althought in a non-ajax-request the data are stored in the database, in case fo ajax the don't store. Any ideas What may be wrong???
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

HTML:

<div id="ajaxResults"></div>

Javascript ajax:

 success: function(response) {
    $('#ajaxResults').text(response);
   }

this script you've wrote is only if the validation succeeds, right?

Wrong. The code in "success" gets executed any time you get a response back from the server (assuming the HTTP header is 200). Does your javascript knows if the server has any error for you? No.

You need your JavaScript to recognize if the validation failed or succeeded. You have many ways to do that. One of these could be sending the message to display followed by a 0 or 1.

So your PHP will looks like:

return "0 " . $errorMessage;

and

return "1 " . $successMessage;

and your javascript should then recognize, with if statement and substring, if the message starts with 0 or with 1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...