简体   繁体   中英

How to receive ajax json data in a codeigniter controller

On the client side I have :

var postData = {
    "id" : id,
    "message" : message
};

console.log(postData);

$.ajax({
    type: "POST",
    url: "controller/function",
    data: postData, 
    success: function(){
        alert(id + ' ' + message);
    }
});

This appears to be working properly as I can see the correct post parameters in chrome dev tools. In my codeigniter controller I have tried:

echo 'postid' . $_POST['id'].' '.$_POST['message'];

$postData=$this->input->post('id');

var_dump($postData); exit;

I'm getting:

Message: Undefined index: id
Message: Undefined index: message

boolean(false)

the $_POST array is empty.

How can I fix this? Thank you for your help

you may add dataType:'json' in your ajax options

$.ajax({
       type: "POST",
       url: "controller/function",
       data: postData,
       dataType:'json',
       success: function(){
           alert(id + ' ' + message);
       }
});

Did you configure your CI to use CSRF protection? If yes, you will need to include the CSRF field and value to your POST request.

$.ajax({
    type: "POST",
    url: "controller/function",
    data: postData, 
    success: function(data){
        alert(data.id + ' ' + data.message);
    }
});

ajax return json object in data , you forgot to written data in function

在客户端为$.ajax添加dataType:'json'参数。

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