0

I'm trying to submit a music uploading form, where I get the data for the input fields from another page. I just want to do a simple thing: if I delete one of those required fields, I want the console to show the form errors.

This is the view (upload.php):

<?php echo form_open_multipart('uploads/verify', array('id' => 'upload_form')); ?>
    <section id="upload">
      <h2><strong><?= $title; ?></strong></h2>
      <div class="col-lg-6" id="col1">
        <div class="form-group">
          <label>Title <label class="star">*</label></label>
          <input class="form-control" type="text" name="title" value="<?php echo $music_tags['title']; ?>">
        </div>
        <div class="form-group">
          <label>Artist name <label class="star">*</label></label>
          <input class="form-control" type="text" name="artist" value="<?php echo $music_tags['artist']; ?>">
        </div>
        <div class="form-group">
          <label>Album name <label class="star">*</label></label>
          <input class="form-control" type="text" name="album" value="<?php echo $music_tags['album']; ?>">
        </div>
        <div class="form-group">
          <label>Year of the release <label class="star">*</label></label>
          <input class="form-control" type="number" name="rel_year" value="<?php echo $music_tags['year']; ?>">
        </div>
      </div>
      <div class="col-lg-6" id="col2">
        <div class="form-group">
          <label>Genre</label>
          <select class="form-control" name="genre" size="6">
            <option value="alt-rock" selected>Alternative rock</option>
            <option value="breakbeat">Breakbeat</option>
            <option value="downtempo">Downtempo</option>
            <option value="garage-rock">Garage rock</option>
            <option value="jungle">Jungle</option>
            <option value="hardcore">Hardcore</option>
            <option value="house">House</option>
            <option value="metal">Metal</option>
            <option value="new-wave">New wave</option>
            <option value="post-punk">Post-punk</option>
            <option value="prog-rock">Progressive rock</option>
            <option value="shoegaze">Shoegaze</option>
            <option value="techno">Techno</option>
            <option value="trance">Trance</option>
          </select>
        </div>
        <div class="form-group">
          <label>Upload a cover (click on the icon)</label><br>
          <div class="upload-cover-button" id="upload_pic">
            <label class="btn btn-default well well-sm">
              <i class="fa fa-upload" aria-hidden="true"></i>
              <input type="file" id="cover" name="cover" accept="image/jpeg,image/png,image/jpg">
            </label>
          </div>
          <div id="pic_thumbnail"></div>
        </div>
      </div>
      <div class="col-lg-12" id="col3">
        <div class="form-group">
          <label>Description</label>
          <textarea class="form-control" name="description" rows="8"></textarea>
        </div>
        <div style="text-align: center;">
          <button type="submit" name="submit">Submit</button>
        </div>
      </div>
    </section>
  <?php echo form_close(); ?>

This is the controller method, called verify:

public function verify() {
  $config = array(
    array(
      'field' => 'title',
      'label' => 'title',
      'rules' => 'required|trim|xss_clean'
    ),
    array(
      'field' => 'artist',
      'label' => 'artist',
      'rules' => 'required|trim|xss_clean'
    ),
    array(
      'field' => 'album',
      'label' => 'album',
      'rules' => 'required|trim|xss_clean'
    ),
    array(
      'field' => 'rel_year',
      'label' => 'release year',
      'rules' => 'required|trim|xss_clean'
    )
  );

  $this->form_validation->set_rules($config);

  if($this->form_validation->run() == FALSE) {
    $result['image'] = 'not set';
    $result['status'] = 'error';
    $result['message'] = $this->form_validation->error_array();
  }
  else {
    // cover upload, not necessary
    if($_FILES['cover']['error'] !== 4) {
      // if we uploaded a cover
      $result['image'] = 'true';
    }
    else {
      // if we didn't upload a cover
      $result['image'] = 'false';
    }
    $result['status'] = 'success';
    $result['message'] = 'Successful uploading.';
  }

  echo json_encode($result);
}

And this is the AJAX function (wrapped around with $(document).ready(function() {}) of course):

$('#upload_form').on('submit', function() {
  $.ajax({
    url: '<?php echo base_url('uploads/verify'); ?>',
    type: 'POST',
    dataType: 'json',
    success: function(response) {
      console.log(response);
      console.log(response.message);
    }
  });
});

If I hit "Submit", after the automatic page reloading I get all the correct data on the blank page, e.g. if I clear out the "title" field, I get the following response:

{"image":"not set","status":"error","message":{"title":"The title field is required."}}

Or if I leave the fields alone and I upload an image:

{"image":"true","status":"success","message":"Successful uploading."}

But the problem is that doesn't matter what I do, I always get the same rows in console, which is a problem, because I want to handle those error messages later.

On console.log(response):

Object {image: "not set", status: "error", message: Object}

And on console.log(response.message):

Object {title: "The title field is required.", artist: "The artist field is required.", album: "The album field is required.", rel_year: "The release year field is required."}

which are basically all the possible form errors I could get if I delete all the input fields. Looks like the verify function is stucked inside the $this->form_validation->run() == FALSE part, ignoring all the filled fields. But in the meanwhile, the JSON object in the blank page and "Chrome Dev Tools -> Network -> Preview or Response" shows the correct response.


I tried to do the following methods to somehow fix the problem:

Modifying the way of getting form errors

Besides the method I used above, I tried two other ways:

$result['message'] = array(
  'title' => form_error('title'),
  'artist' => form_error('artist'),
  'album' => form_error('album'),
  'rel_year' => form_error('rel_year'),
);

And also:

$result['message'] = validation_errors();

None of these worked, everything stays the same.


Modifying AJAX function

I only added data attribute to the function to see if anything changes. Tried two ways here as well:

data: $('#upload_form').serialize()

And:

data: new FormData($(this)[0])

No success as well...


I've been sitting here wondering what the heck could be the problem, it just drives me crazy not knowing the solution :( Any suggestions?

  • check this solution https://stackoverflow.com/questions/17572429/codeigniter-and-ajax-form-submit – Abanoub Makram Jul 19 '17 at 12:23
  • also check this https://code.tutsplus.com/tutorials/how-to-upload-files-with-codeigniter-and-ajax--net-21684 – Abanoub Makram Jul 19 '17 at 12:25
  • AJAX can't work that way. As soon as you click Submit button, request is sent. You can disable default form behavior putting preventDefault() method to event in your JS code. Similar to [this](https://api.jquery.com/event.preventdefault/). – Tpojka Jul 19 '17 at 12:36
  • I know it can't work, but even using `preventDefault()` gives me the same error. I'm just testing if I get the correct form errors. – borrowedtime Jul 19 '17 at 12:42
  • I tried the first solution BTW, and it gave me an `Undefined index: cover` error, while I clearly added a `name` attribute with the value of `cover` to that. – borrowedtime Jul 19 '17 at 12:44
  • Because `else` block never executes. Probably because form failed. – Tpojka Jul 19 '17 at 12:49
  • Btw, I can't see you are sending data with `AJAX`. That's why form fails. Check [here](https://stackoverflow.com/questions/21044798/how-to-use-formdata-for-ajax-file-upload) how to send data with `FormData` object. – Tpojka Jul 19 '17 at 12:52
  • If it never executes, then why is it that without `preventDefault()`, it prints to the blank page the correct response and not the wrong? Sorry, I think I'm just a noob haha :D – borrowedtime Jul 19 '17 at 13:05

0 Answers0