BigJobbies
BigJobbies

Reputation: 4343

CodeIgniter - jQuery, JSON, simple example not working

Ok, Im a real newbie when it comes to ajax and json ... Im trying to figure it out in my codeigniter project.

Ive written something simple to start, just to bring up an alertbox, but it doesnt seem to be working, if someone could let me know where im going wrong, that would be grand.

In my view i have the following code.

$('.users').change(function(){
    $.ajax({
        type: "POST",
        url: "/edituser/returndata",
        data: {id: this.find(':selected').val()},
        dataType: json,
        success: function(data){
            alert(data);
        }
    });
});

in the edituser/returndata controller, i just simply have the following

function returndata(){
    echo $_POST['id'];
}

I know this will look pretty stupid to some people, but im still trying to figure it out, if someone could help :)

Cheers

----------------- UPDATED CODE BELOW

<script type="text/javascript" charset="utf-8">
$('#users').live('change', function(){

    $.ajax({
        type: "POST",
        url: "/edituser/returndata",
        data: {id: $(':selected', this).val()},
        dataType: 'json',
        success: function(data){
            alert(data.id);
        }
    });
});                     
</script>

Controller code

function returndata()
{
    $ID = $this->input->post('id');  // Use this instead of $_POST['id']
    echo json_encode(array('id'=>$ID));
}

Upvotes: 2

Views: 5351

Answers (2)

Ruan Mendes
Ruan Mendes

Reputation: 92274

UPDATE Disregard the answer. I thought the JSON was sent as a string, but it's not, as pointed out by Rocket. It is converted to url encoded value pairs. I'm leaving the answer up just in case someone thought the same thing as me....


The incoming JSON is not a request parameter, you need to read the body of the request

$json = json_decode(trim(file_get_contents('php://input'));
$id = $json->id;

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227240

Your dataType should be:

dataType: 'json',

Your data should be:

data: {id: $(this).find(':selected').val()},

Inside of a event callback, this is a DOM element, so it needs to wrapped in $().

or:

data: {id: $(':selected', this).val()},

Which is the same as above, just less characters.

Also, in your PHP, you need to output JSON.

function returndata(){
  $ID = $this->input->post('id');  // Use this instead of $_POST['id']
  echo json_encode(array('id'=>$ID));
}

Then in your success function, you can do:

alert(data.id);

Upvotes: 3

Related Questions