简体   繁体   中英

'Bad Request' with ajax and codeigniter

Windows 10, Codeigniter 3, Wamp3.

Ajax post throws a Bad Request error. This is an old chestnut but online research shows the problem usually to be CSRF. However I emphasize at the outset that I have csrf disabled for this test:

config['csrf_protection'] = FALSE;

I have set up some deliberately very simple test code. The controller looks like this:

class Ajax extends CI_Controller {

public function index() {


$this->load->view('pages/index');
}

public function hello($name) {
    $fullname = $this->input->post('fullname');
    echo 'Hello '.$fullname;

}

}//EOF

and the view looks like this:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo Ajax</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
    $(function() {
        $('#bttHello').click(function(){
            var fullname = $('#fullname').val();
            $.ajax({
                type:'POST',
                data: {fullname: fullname},
                url:'<?php echo base_url('ajax/hello'); ?> + fullname',
                success: function(result) {
                    $('#result1').html(result);

                }
            });

        });

    });
</script>
</head>
<body>

Name <input type="text" id="fullname">
<input type="button" value="Hello" id="bttHello">
<br>
<span id="result1"></span>

</body>
</html>

The console shows a Bad Request

POST XHR http://localhost/faith/ajax/hello%20+%20fullname [HTTP/1.1 400 Bad Request 9ms]

So if csrf is not the culprit, is it a Wamp issue? Everything else seems to work fine. I have spent so much time on this! What is going on?

Data are already sent through POST . No need to pass it through URL

<script>
$(function() {
  $('#bttHello').click(function(){
    var fullname = $('#fullname').val();
    $.ajax({
      type:'POST',
      data: {fullname: fullname},
      url:"<?php echo base_url('ajax/hello'); ?>",
      success: function(result) {
        $('#result1').html(result);
      }
    });
  });
});
</script>

And, remove parameter $name from controller action hello() .

public function hello() {
  $fullname = $this->input->post('fullname');
  echo 'Hello '.$fullname;
}

write url like this

"url": "<?php echo base_url().'ajax/hello';?>/" + fullname

after /fullname its a argument of function hello()

Try this..

    <?php echo form_open('ajax/hello', [
            'method' => 'post',
            'class' => 'create_form'
        ]); ?>
        <input type="text" name="fullname" value="Full Name"/>
<button type="submit">Create</button>
    <?php echo form_close(); ?>

and ajax

$(document).on('submit', 'form.create_form', function (e) {
            var self = this;
            var formData = new FormData($(this)[0]);
            $.ajax({
                url: $(self).attr('action'),
                type: 'POST',
                data: formData,
                async: false,
                dataType: 'json',
                success: function (res) {
                    console.log(res)
                },
                cache: false,
                contentType: false,
                processData: false
            });
            return false;
        });

The CodeIgniter Controller:

<?php
class Ajax extends CI_Controller
{
    public function index()
    {
        $this->load->view('pages/index');
    }
    /**
     * @param $name
     */
    public function hello($name)
    {
        // if no $name params value pass and post exist
        if ( ! isset($name) && $this->input->post('fullname')) {
            // get value from post params
            $fullname = $this->input->post('fullname', true);
        } elseif (isset($name) && ! $this->input->post('fullname')) {
            // get value from pass param method
            $fullname = $name;
        } else {
            // default value
            $fullname = 'No Name found';
        }
        // show ajax response
        echo $fullname;
    }
    /**
     * Another way if we using GET params
     * e.g. http://wwww.site.com/ajax/hello/my-name-value
     * @param $name
     */
    public function hello_another($name)
    {
        // if url has param as name value
        // remember codeigniter will map all url params as method params as they provided
        // no need to use get input, it will take from url string directly
        if (isset($name)) {
            // get value from get params
            $fullname = $name;
        } else {
            // default value
            $fullname = 'No Name found';
        }
        // show ajax response
        echo $fullname;
    }
    /**
     * Another way if we using GET params and security is on top
     * e.g. http://wwww.site.com/ajax/hello/my-name-value
     * @param $name
     */
    public function hello_another_secure($name)
    {
        // if url has param as name value
        // remember codeigniter will map all url params as method params as they provided
        // no need to use get input, it will take from url string directly
        if (isset($name) && preg_match("/^[a-zA-Z'-]+$/", $name)) {
            // get value from method params
            $fullname = $name;
        } else {
            // default value
            $fullname = 'No Name or invalid name found';
        }
        // show ajax response
        echo $fullname;
    }
}
//EOF

<script>
    $(function() {
        $('#bttHello').click(function(){
            var fullname = $('#fullname').val();
            $.ajax({
                type:'POST',
                data: {fullname: fullname},
                url:'<?php echo base_url('ajax/hello'); ?>',
                success: function(result) {
                    $('#result1').html(result);

                }
            });

        });

    });
</script>

<script>
    $(function() {
        $('#bttHello').click(function(){
            var fullname = $('#fullname').val();
            $.ajax({
                type:'GET',
                url:'<?php echo base_url('ajax/hello_another/'); ?> + fullname',
                success: function(result) {
                    $('#result1').html(result);

                }
            });

        });

    });
</script>

The CodeIgniter is fully capable to fulfil your needs, Just look their AWESOME Document first..

use this way
you should concate fullname variable after quatation.
like this
url:'<?php echo base_url('ajax/hello'); ?>' + fullname


<script>
$(function() {
    $('#bttHello').click(function(){
        var fullname = $('#fullname').val();
        $.ajax({
            type:'POST',
            data: {fullname: fullname},
            url:'<?php echo base_url('ajax/hello'); ?>' + fullname,
            success: function(result) {
                $('#result1').html(result);

            }
        });

    });

});

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