通过ajax将null值传递给控制器

时间:2017-11-13 18:31:00

标签: javascript php ajax codeigniter

我正在尝试修改我的保存例程,以便将null值传递给id_cellcarrier到codeigniter中的控制器上。以下是我尝试过的,它不起作用。为了简洁起见,我在这里没有发布这些代码的很多部分。我希望你能够了解我的目标。我是否必须在控制器端执行某些操作才能理解null?

使用Javascript:

     /**
     * Event: Save Add/Edit Customer Operation "Click"
     */
    $('#save-customer').click(function() {
        var customer = {
            if ($('#cell-carrier').val()== ''){
                JSON.stringify({id_cellcarrier: null}),
            }else{
                id_cellcarrier: $('#cell-carrier').val(),
            }
            wp_id: $('#wp-id').val(), 
            notifications: $('#client-notifications').val(), 
            first_name: $('#first-name').val(),
            last_name: $('#last-name').val(),
            email: $('#email').val(),
            phone_number: $('#phone-number').val(),
            address: $('#address').val(),
            city: $('#city').val(),
            zip_code: $('#zip-code').val(),
            notes: $('#notes').val()
        };

        if ($('#customer-id').val() != '') {
            customer.id = $('#customer-id').val();
        }

        if (!instance.validate(customer)) return;

        instance.save(customer);
    });


/**
 * Save a customer record to the database (via ajax post).
 *
 * @param {Object} customer Contains the customer data.
 */
CustomersHelper.prototype.save = function(customer) {
    var postUrl = GlobalVariables.baseUrl + '/index.php/backend_api/ajax_save_customer';
    var postData = {
        csrfToken: GlobalVariables.csrfToken,
        customer: JSON.stringify(customer)
    };

    $.post(postUrl, postData, function(response) {
        if (!GeneralFunctions.handleAjaxExceptions(response)) {
            return;
        }

        Backend.displayNotification(EALang['customer_saved']);
        this.resetForm();
        $('#filter-customers .key').val('');
        this.filter('', response.id, true);
    }.bind(this), 'json').fail(GeneralFunctions.ajaxFailureHandler);
};          

控制器:

/**
 * [AJAX] Save (insert or update) a customer record.
 *
 * @param array $_POST['customer'] JSON encoded array that contains the customer's data.
 */
public function ajax_save_customer() {
    try {
        $this->load->model('customers_model');
        $customer = json_decode($_POST['customer'], true);

        $REQUIRED_PRIV = (!isset($customer['id']))
                ? $this->privileges[PRIV_CUSTOMERS]['add']
                : $this->privileges[PRIV_CUSTOMERS]['edit'];
        if ($REQUIRED_PRIV == FALSE) {
            throw new Exception('You do not have the required privileges for this task.');
        }

        $customer_id = $this->customers_model->add($customer);
        echo json_encode(array(
            'status' => AJAX_SUCCESS,
            'id' => $customer_id
        ));
    } catch(Exception $exc) {
        echo json_encode(array(
            'exceptions' => array(exceptionToJavaScript($exc))
        ));
    }
}

从模型中

public function add($customer) {
    // Validate the customer data before doing anything.
    $this->validate($customer);

    // :: CHECK IF CUSTOMER ALREADY EXIST (FROM EMAIL).
    if ($this->exists($customer) && !isset($customer['id'])) {
        // Find the customer id from the database.
        $customer['id'] = $this->find_record_id($customer);
    }

    // :: INSERT OR UPDATE CUSTOMER RECORD
    if (!isset($customer['id'])) {
        $customer['id'] = $this->_insert($customer);
    } else {
        $this->_update($customer);
    }

    return $customer['id'];
}


protected function _update($customer) {
    // Do not update empty string values.
    foreach ($customer as $key => $value) {
        if ($value === '')
            unset($customer[$key]);
    }

    $this->db->where('id', $customer['id']);
    if (!$this->db->update('ea_users', $customer)) {
        throw new Exception('Could not update customer to the database.');
    }

    return intval($customer['id']);
}

1 个答案:

答案 0 :(得分:0)

乍一看,您的代码中的这一部分似乎必须是拼写错误:

id_cellcarrier: $('#cell-carrier').val() === ''? null: $('#cell-carrier').val(),

,但如果它不是拼写错误,那应该是这样的:

{{1}}
相关问题