简体   繁体   中英

Ajax post not working codeigniter

I am using codeigniter 3.1

Ajax post not working and i am getting 403 (Forbidden) in console.

[POST http://localhost/test/post 403 (Forbidden)]

HTML

 <div class="post">
                <input type="text" id="data1" name="data1" value="">
                <input type="text" id="data2" name="data2" value="">
            </div>
    <button id="post">Submit</button>

JAVASCRIPT

$('#post').on('click', function () {

      var value1=$("#data1").val();
      var value2=$("#data2").val();

        $.ajax({
                url: window.location.href+'/post',
                type: "POST",
                data:"{'data1':'"+value1+"','data2':'"+value2+"'}"
            });

CONTROLLERS

public function post() 
    {

        $data1 = $this->common->nohtml($this->input->post("data1", true));
        $data2 = $this->common->nohtml($this->input->post("data2", true));


        $this->data_models->update($this->data->INFO, array(
          "data1" => $data1,
          "data2" => $data2,
            )
          );

  }

If you want CSRF protection on (a good idea) then you must pass the CSRF token when posting form data - via AJAX or not. Consider this approach.

The easiest way to put the token in your form is to use Codeigniter's "Form Helper" ( Documented here ) You can load the function your controller or use autoloading. This view code assumes you have the helper loaded.

HTML

<div class="post">
    <?= form_open('controller_name/post'); //makes form opening HTML tag ?> 
    <input type="text" id="data1" name="data1" value="">
    <input type="text" id="data2" name="data2" value="">
    <?php
    echo form_submit('submit','Submit', ['id'=>'post']); //makes standard "submit" button html
    echo form_close(); // outputs </form>
    ?>
</div>

The form_open() function also automatically adds a hidden field containing the CSRF token to the HTML.

Javascript

$('#post').submit(function( event ) {
    //the next line will capture your form's fields to a format 
    //perfect for posting to the server
  var postingData = $( this ).serializeArray();
  event.preventDefault();

    $.ajax({
    url: window.location.href + '/post',
        type: "POST",
        data: postingData,
        dataType: 'json',
        success: function(data){
            console.log(data);
        }
    });
});

controller

By the time $_POST gets to your controller the CSRF token has been striped away so you don't have to worry about it "polluting" your incoming data.

public function post()
{
    //get all the posted data in one gulp and NO, you do not want to use xss_clean
    $posted = $this->input->post();
    //With the above the var $posted has this value (showing made up values)
    // array("data1" => "whatever was in the field", "data2" => "whatever was in the field");

    //sanitize the field data (?)
    //just stick the clean data back where it came from
    $posted['data1'] = $this->common->nohtml($posted["data1"]);
    $posted['data2'] = $this->common->nohtml($posted["data2"]);

    $this->data_models->update($this->data->INFO, $posted);

    //you must respond to the ajax in some fashion
    //this could be one way to indicate success 
    $response['status'] = 'success';
    echo json_encode($response);
}

You could also send back some other status if, for instance, the model function reported a problem. You then need to react to that status in you javascript. But if you don't respond it will likely result in problems down the road.

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