Sean Kimball
Sean Kimball

Reputation: 4494

Retrieving posted data from ajax using php

I have a problem retrieving the posted data from an ajax call, not sure what is wrong. The console output from the script below shows everything as expectred before the ajax call, but the data is not available in the connector

   function updateOptions(data){

        console.log(data);
        console.log(data.id);
        console.log(data.action);

        var data = {id: data.id, action : data.action};

        console.log(data);

        $.ajax({

            type: 'POST',
            url: 'ajax.connector.php?action=updateOptions',
            data: JSON.stringify(data),
            cache: false,
            dataType  : "json",

            success: function(data, status) {

                if(data.status == 'success'){

                console.log('success');
                console.log(data);

                }else if(data.status == 'error'){
                    console.log('selects not updated');
                }

            },

            error: function(data){
                console.log('an error has occurred');
            },

        });

    }

So the first 4 console.log entries show the data correctly, the first console.log in the success condition shows correctly. The second, shows:

Object {status: "success", msg: "Category added successfully", id: null, action: null, post: Array[0]}

the connector [more like a director]

   case 'updateOptions':
        error_log('Running updateOptions function ' . print_r($_POST, TRUE), 0);
        $output = $sbb->updateOptions($_POST);
        break;

Logs this:

Running updateOptions function Array\n(\n)\n,

if I try to echo $_POST['action'] or $_POST['data'] or something to the log I get an undefined index.

I am forcing the ajax call to return success in the class that the php case function is calling:

public function updateOptions($data){

        $output = array(
            'status' => 'success',
            'msg' => 'Category added successfully',
            'id' => $data['id'],
            'action' => $data['action'],
            'post' => $data,
        );

        return $output;

}

So the ajax call itself does work, it's the data that's not being passed.

Somehow I am not getting [or correctly retrieving] the data from the ajax post.

What is the problem here?

Upvotes: 0

Views: 1476

Answers (1)

Musa
Musa

Reputation: 97672

You're posting JSON, $_POST is populated with key=value pairs, don't mix up JSON with application/x-www-form-urlencoded or multipart/form-data (which is what php uses to populate $_POST.
To send application/x-www-form-urlencoded data with jQuery.ajax pass an object with the data as the data parameter

data: data, // removed JSON.stringify

Upvotes: 3

Related Questions