【问题标题】:How to send information to database without reloading the page如何在不重新加载页面的情况下将信息发送到数据库
【发布时间】:2020-05-31 19:41:15
【问题描述】:

我一直在尝试使用 AJAX 将信息发送到数据库,但没有任何效果,每次单击提交按钮时,都没有任何效果,页面在某种程度上保持静态。所有 JS 文件都被正确引用,所以我不确定我做错了什么。

这是我到目前为止所做的;

控制器:

public function contact_us_ajax() { 
    //form validation rules and file upload config
    $this->form_validation->set_rules('name', 'Name', 'trim|required');
    $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
    $this->form_validation->set_rules('subject', 'Subject', 'trim|required');
    $this->form_validation->set_rules('message', 'Message', 'trim|required');
    $this->form_validation->set_rules('captcha_code', 'Captcha Code', 'trim');
    $this->form_validation->set_rules('c_captcha_code', 'Captcha Code', 'trim|required|matches[captcha_code]',
        array(
            'required' => 'Captcha is required. Reload the page if you cannot see any code.',
            'matches' => 'Invalid captcha code'
        )
    );

    if ($this->form_validation->run()) {
        $this->message_model->contact_us(); //insert the data into database
        $res = ['status' => true, 'msg' => 'Message sent successfully!'];
        echo json_encode($res);
    } else {
        $res = ['status' => false, 'msg' => validation_errors()];
        echo json_encode($res);
    }
}

型号:

public function contact_us() { 
    $name = ucwords($this->input->post('name', TRUE)); 
    $email = $this->input->post('email', TRUE);
    $subject = ucwords($this->input->post('subject', TRUE)); 
    $message = ucfirst($this->input->post('message', TRUE)); 
    $message = nl2br($message); 
    $data = array (
        'name' => $name,
        'email' => $email,
        'subject' => $subject,
        'message' => $message,
    );
    $this->db->insert('contact_messages', $data);

    //email admins
    //$this->notify_admins($name, $email, $subject, $message);
}

查看:

        <?php 
              $form_attributes = array("id" => "contact_us_form");
              echo form_open('home/contact_us_ajax', $form_attributes); ?>
     <!-- Contact Form -->
     <div class="col-md-5">


           <h4>Send Us a Message</h4>
           <div class="form-group">

              <label>Name:</label><input type="text" name="name" class="form-control input-field"  required>                    
              <label>Email:</label><input type="email" name="email" class="form-control input-field" required>           
              <label>Subject:</label><input type="text" name="subject" class="form-control input-field" required>                     
           </div>

           <label>Message:</label>
           <textarea name="message" class="textarea-field form-control" rows="4"  required></textarea>

           <div class="col-md-6">
              <input type="text" name="captcha_code" id="captcha_code" value="<?php echo $captcha_code; ?>" class="form-control" readonly />
           </div>
           <div class="col-md-6">
               <input type="text" name="c_captcha_code" value="<?php echo set_value('c_captcha_code'); ?>" class="form-control" placeholder="Enter captcha code here*" required />
           </div>

           <div id="status_msg"></div>

           <?php echo flash_message_success('status_msg'); ?>
           <?php echo flash_message_danger('status_msg_error'); ?>

           <button class="btn center-block">Send message</button>

     </div>


        <?php echo form_close(); ?>   

AJAX:

//Contact Us
$('#contact_us_form').submit(function(e) {
    e.preventDefault();
    var form_data = $(this).serialize();
    $.ajax({
        url: base_url + 'home/contact_us_ajax', 
        type: 'POST',
        data: form_data, 
        dataType: 'json',
        success: function(res) {
            if (res.status) {
                $( '#status_msg' ).html('<div class="alert alert-success text-center" style="color: #000">'+res.msg+'</div>').fadeIn('fast');
                $('#contact_us_form')[0].reset(); //reset form fields
                $('#captcha_code').val(''); //clear captcha field
                setTimeout(function() { 
                    location.reload();
                }, 5000);   
            } else {
                $( '#status_msg' ).html('<div class="alert alert-danger text-center" style="color: #000">' + res.msg + '</div>').fadeIn('fast').delay( 30000 ).fadeOut( 'slow' );   
            }
        }
    });
});

【问题讨论】:

  • 浏览器控制台中的任何内容?
  • 当发出POST 请求时,路由器是否知道传递给该控制器?使用GET 测试您的 AJAX 以进行检查。
  • 你在JS中定义了base_url吗?打开您的控制台,转到网络并检查您的请求的 URL。
  • 由于您没有做任何事情来将 CSRF 令牌包含在您通过 AJAX 发布的有效负载中,因此有可能(尽管在不知道您的浏览器控制台是否记录错误的情况下很难判断)您的控制器拒绝请求,因为 CSRF 检查未通过。最快(虽然不是最安全)的解决方法是在您的 CSRF 验证中定义一个异常(在application/config/config.php 中,您将找到一个名为$config['csrf_exclude_uris'] 的数组用于此目的)

标签: php ajax database codeigniter


【解决方案1】:

base_url在codeigniter的config.php中定义,例如:

$config['base_url'] =  'http://or.org/';

但是!这并不意味着您可以简单地在 javascript base_url 中命名一个变量并希望得到任何值。

要在你的 ajax 调用中使用它,你需要像这样回显 php 常量:

url: '<?php echo base_url()?>' + 'home/contact_us_ajax'

我通常只使用相对路径

url: '/home/contact_us_ajax'

如果您使用“常规”CI 配置,它也可以正常工作

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-29
    • 1970-01-01
    • 2011-07-15
    • 1970-01-01
    • 2012-11-22
    • 2011-04-07
    • 2020-03-18
    • 1970-01-01
    相关资源
    最近更新 更多