I am using codeigniter 2.1.2 and Bootstrap.

I am opening a form in a modal window.

The form is inside a div with id status.

The form has a few input fields and an upload file field.

I am trying to submit the form with ajaxForm.

In my controller I echo "success" if everything is fine.

public function edit($provinceId, $bookId, $id = NULL)
{
    $province = $this->province_m->get($provinceId);
    $book = $this->book_m->get($bookId);

    if($id)
    {
        $this->data['issue'] = $this->issue_m->get($id);
        count($this->data['issue']) || $this->data['errors'][] = 'The issue could not be found.';
    }
    else
    {
        $this->data['issue'] = $this->issue_m->get_new();
    }

    // Set up the form
    $rules = $this->issue_m->rules;
    $this->form_validation->set_rules($rules);

    // Checks if issue save was pressed, otherwise it will show the errors becuase of the post of province and book
    if($this->input->post('issueposted') != '')
    {
        if ($this->form_validation->run() == TRUE)
        {
            $data = $this->issue_m->array_from_post(array('mag_folder'));
            $data['province_id'] = $provinceId;
            $data['book_id'] = $bookId;
            $data['publish_date'] = mdate('%Y-%m-%d', strtotime($this->input->post('publish_date')));

            if($_FILES['image']['error'] === 0)
            {
                      $uploaded = $this->do_upload($province->folder, $book->name);

              if($uploaded)
              {
                $data['image'] = $this->upload->file_name;
                $this->issue_m->save($data, $id);
                echo "success";
              }
            }
            else //No file to upload
            {
                  $this->issue_m->save($data, $id);
              echo "success";
            }
          }
        }

        // Load the view
        $this->data['url'] = site_url('admin/issue/edit') . '/' . $province->id . '/' . $book->id . '/' . $id;
        $this->data['province'] = $province;
        $this->data['book'] = $book;
        $data = $this->load->view('admin/issue/edit', $this->data, TRUE);
        $this->output->set_output($data);
    }
}

The javascript:

$(function() {
var options = { 
        target: '#status',
        success: function(data) { 
            alert(data);
            window.location.replace("http://thinklocal.dev/admin/province");
    }
}; 

// pass options to ajaxForm 
$('#issueform').ajaxForm(options);
});

Everything worked fine besides the fact that the page was not redirecting on success.
When I alert the data I get this: success<div id="status">

I also tried this way, but here when I click the submit button, nothing happens.

$('#issueform').submit( function()
 {
   var bar = $('.bar');
   var percent = $('.percent');
   var status = $('#status');

   $(this).ajaxForm({
     beforeSend: function() {
       status.html();
       var percentVal = '0%';
       bar.width(percentVal)
       percent.html(percentVal);
     },
     uploadProgress: function(event, position, total, percentComplete) {
       var percentVal = percentComplete + '%';
       bar.width(percentVal)
       percent.html(percentVal);
     },
     success: function(xhr) { 
       status.html(xhr.responseText); 
     }
    return false;
   });
 });  

Can someone please help me figure out how do I submit the form and redirect if there are no errors, or go back to the modal window if there are errors?

Member Avatar

LastMitch

Can someone please help me figure out how do I submit the form and redirect if there are no errors, or go back to the modal window if there are errors?

I'm not sure what you wrote here:

$('#issueform').submit( function()
{
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$(this).ajaxForm({
beforeSend: function() {
status.html();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function(xhr) {
status.html(xhr.responseText);
}
return false;
});
}); 

I don't know your form ID so it should look like this:

$('#issueform').on('submit', 'form', function(e){
e.preventDefault();
var bar = $('#bar').val();
var percent = $('#percent').val();
var status = $('#status').val();

$.ajax({
    type: "POST", 
    secureuri: false,
    url: base_url+"file/",   
    data: {
    'bar': $('#bar').val()
    'percent': $('#percent').val()
    'status': $('#status').val()
    },
    success: function(data){
        $('#files').html(data);
    },
    error: function(){alert('error');}
});     
});

<form method="POST" action='#' id='issueform' >
<input type="text" name="bar" id="bar">
<input type="text" name="percent" id="percent">
<input type="text" name="status" id="status">
<input type="submit" value="submit" id='Submit'>
</form>

You can take a look at upload class for CodeIgniter:

http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

and also look at this tutorial regarding about AJAX:

http://net.tutsplus.com/tutorials/javascript-ajax/how-to-upload-files-with-codeigniter-and-ajax/

Thanks, but your way will not work for a form that needs file uploading.

and the tutorial you sent is a bit old and does not work with the jquery version I am using.

My form id is issueform.

Found the solution:

In the jquery I changed to success function:

var options = { 
        target: '#status',
        success: function(data) {
            if(data == 'success')
            {
                $('#status').hide();
                window.location.replace("http://thinklocal.dev/admin/province");
            }
    },
        error: function ajaxError(request, type, errorThrown)
{
    var message = "There was an error with the AJAX request.\n";
    switch (type) {
        case 'timeout':
            message += "The request timed out.";
            break;
        case 'notmodified':
            message += "The request was not modified but was not retrieved from the cache.";
            break;
        case 'parsererror':
            message += "XML/Json format is bad.";
            break;
        default:
            message += "HTTP Error (" + request.status + " " + request.statusText + ").";
    }
    message += "\n";
    alert(message);
} 
}; 

// pass options to ajaxForm 
$('#issueform').ajaxForm(options);

In my controller, if there are no errors in the form I echo success and return true:

echo "success";
return true;
commented: thanks for sharing! +11