简体   繁体   中英

Getting 500 Internal Server Error with jQuery AJAX and CodeIgniter

I'm trying to submit a form (it's a dynamic form with fields added via jQuery) to CodeIgniter for a db insert. Part of it works, the other part doesn't.

Here's the jQuery:

function submitForm() {
    $.ajax({
        type: 'POST',
        url: '/raffle/save/',
        data: $('#raffle').serialize(),
        success: function (response) {
            alert(response);
        },
        error: function() {
            alert('Failed'); // This is what I get unless I comment out the entry insert
        }
    });
}

The CI controller:

class Raffle extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('raffle_model');
        $this->load->library('form_validation');
    }

    public function index() {
        $data['title'] = 'Create a Raffle';
        $this->load->view('header', $data);
        $this->load->view('raffles/create_view', $data);
        $this->load->view('raffles/bottombar_view', $data);
        $this->load->view('footer', $data);
    }

    public function save() {
        foreach($_POST as $k => $v) {
            if($k == 'entrant' || $k == 'tickets') {
                foreach ($v as $i => $vector) {
                    $this->form_validation->set_rules('entrant[' . $i . ']', 'Entrant name', 'trim|required|min_length[1]|max_length[100]|xss_clean');
                    $this->form_validation->set_rules('tickets[' . $i . ']', 'Number of tickets', 'trim|required|max_length[2]|is_natural_no_zero|xss_clean');
                }
            } else {
                $this->form_validation->set_rules('raffle-name', 'Raffle name', 'trim|required|min_length[4]|max_length[100]|xss_clean');
                $this->form_validation->set_rules('winners', 'Number of winners', 'trim|required|max_length[2]|is_natural_no_zero|xss_clean');
            }
        }

        if($this->form_validation->run() == FALSE) {
            echo 'Validation failure!';
        } else {
            if($this->raffle_model->add_raffle()) { // It does pass validation and goes to the model
                echo 'Data added successfully!';
            }
        }
    }
}

And the CI model:

class Raffle_model extends CI_Model {
    public function __construct() {
        parent::__construct();
    }

    public function add_raffle() {
        // This works
        $meta = array(
            'user_id'    => $this->session->userdata('user_id'),
            'name'       => $this->input->post('raffle-name'),
            'winners'    => $this->input->post('winners'),
            'created_ip' => $_SERVER['REMOTE_ADDR']
        );

        // This works and is a multidimensional array for insert_batch()
        $entrants = array(
            array(
                'date'      => date(DATE_ATOM),
                'raffle_id' => '1'
            )
        );

        foreach($_POST['entrant'] as $name => $n) {
            array_push($entrants,
                array(
                    'name'    => $n,
                    'tickets' => $_POST['tickets'][$name]
                )
            );
        }

        $this->db->insert('raffle', $meta);
        $this->db->insert_batch('entry', $entrants); // This one returns error 500

        return true;
    }
}

Here's the problem: Submitting the form, the meta portion does get saved to the raffle table, but the entrants portion does not get saved to the entry table. I have tried using a simple dummy array (sample data, no post data, no loops) to see if it would work, but it still doesn't. Console logs say POST http://rafflegrab.dev/raffle/save/ 500 (Internal Server Error) .

CSRF is off in CI config.

The table is set up as follows:

  1. Table name: entry
  2. InnoDB
  3. id - bigint(12) - UNSIGNED - not_null - AUTO_INCREMENT - PRIMARY
  4. user_id - int(10) - UNSIGNED
  5. name - varchar(100)
  6. tickets - smallint(5) - UNSIGNED
  7. date - datetime
  8. raffle_id - int(10) - UNSIGNED

I'm assuming you're using unsafe input methods to be able to access $_POST ?

What happens if you mock up a noddy form with those fields and post it to the Save action on the controller?

Next question is the usual stuff but what do the server logs say? Have a look in the Event Log (windows) or /var/log/apache2/error_log (SUSE) or the equivalent on your system. It should tell you why it's not working.

If not, make sure your php log level is high enough to output errors.

If you're not in a production environment, consider displaying PHP errors until you've tracked down the problem

Edit: Always better to know the problem than guess but my first thought is that your 2-dimensional array as inconsistent. You seem to have:

array(
    array('date'=>blah, 'raffleId'=>blah),
    array('name'=>blah, 'tickets'=>blah),
    array('name'=>blah, 'tickets'=>blah)
    ...
)

Did you in fact want

array(
    array('date'=>blah, 'raffleId'=>blah, 'name'=>blah, 'tickets'=>blah),
    array('date'=>blah, 'raffleId'=>blah, 'name'=>blah, 'tickets'=>blah),
    array('date'=>blah, 'raffleId'=>blah, 'name'=>blah, 'tickets'=>blah),
    ...
)

? Perhaps something like:

    $entrants = array();
    $recordedDate = date(DATE_ATOM);
    foreach($_POST['entrant'] as $name => $n) {
        array_push($entrants,
            array(
                'date'      => $recordedDate,
                'raffle_id' => '1'
                'name'    => $n,
                'tickets' => $_POST['tickets'][$name]
            )
        );
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM