Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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???
share|improve this question

2 Answers

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.

share|improve this answer
 
thanks, I have 2 questions though: 1. how should I get the result of the validation from the controller? 2. this script you've wrote is only if the validation succeeds, right? in case it fails its going to be the same again, but use error instead?? –  Lykos Jul 17 at 12:19
 
I'm not sure i got it.. In case there's an error the controller will return the errors and a 0 (or false), else the controller will return 1 (or true) if it is success, am I right?? –  Lykos Jul 18 at 7:40
1  
you should write a controller that execute the action you want and returns you with an error message or a success message. You should then call this controller in the ajax url, get the response and recognize with javascript if it is a success or error message. Placing a 1 or 0 before the response text is just a possible way to help javascript do this. –  Saturnix Jul 18 at 11:25
 
I did some changes in my code so you can review, but I'm still having some problems. –  Lykos Jul 18 at 13:03

Use this way i hope this will work for you

<script type='text/javascript'>
var base_url = '<?=base_url()?>';

function ajax_call()
{
   var ids = $("#all_users").val();

   $.ajax({
      type:"POST",
      url: base_url+"expense/home/get_expense",
      data: "userid=" + ids,
      success: function(result){
      $("#your_div_id").html(result);
 }
 });

}
</script>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.