0

Been going around in circles trying to get an AJAX call to a PHP server happening. Closer than I was a few hours ago. Still stumped as to how to access the $_POST data in PHP with any sense.

My ajax out

    var __private_api = function() {

        // workhorse.  EVERY call to our server REST API comes through
        // this interface.  NO exceptions.  We will NOT have an interface per
        // form or per MODEL as is a common case.  Makes no sense having an API really.
        // Might as well just code willy7-nilly.

        var packed = JSON.stringify(packet);

        console.log(packed);

        jqxhr = $.ajax({
            method:         "POST",                                         // ALL API calls are POST
            url:            "oop/server.php/",                              // API code
            dataType:       "json",                                         // JSON back at us please
            //contentType:    "application/json",                           // HEADER.  IMPORTANT!
            data:           {"packed":packed}                               // form data + security packet

        }).fail(function(msg) {                                             // error is depreciated.  WHY? Dunno...
            alert("Database Communication failure");                        // this is a HARD failure sent to
            console.log(JSON.stringify(msg));                               // us by the comms stack, authentication, or OS
        }).done(function(data) {                                            // AJaX worked, deal with the resultant packet
            __private_callback(data);                                       // in our custom callback. success() has been
        });                                                                 // depreciated, replaced by bone().  Why???
    }

This gets to PHP as in I can do this

   $this->database->log_config->trace(json_encode($_POST));


    $this->crud = 'EXEC';
    $SQL = "SELECT * from patients limit 2";

    switch($this->crud) {

        case 'EXEC':                                                    // before we drop into CRUDDiness, handle
            $this->database->execute($SQL);                             // well?  This eithe dies or comes back
                                                                        // it CAN come back with an empty SET
                                                                        // that is an SEP.
            $db_result = $this->database->fetch_all();                  // retrieve tuples from the CURSOR
            //$this->response['data'] = $db_result->get_stack();          // and shove in the parcel to go back to the CLIENT API
            $this->response['data'] = json_decode(json_encode($_POST),true);          // and shove in the parcel to go back to the CLIENT API
            break;

That makes it back to my client side code, and the trace from the PHP code looks like this.

{"packed":"    {\"type\":\"USER\",\"method\":\"LOGIN\",\"email\":\"root\",\"pw\":\"S0lari    s7.1\",\"remember\":\"false\"}"} 

So stuff seems to be making it over the great divide OK. HOW, in my PHP code can I test the value of 'type' to see if it is 'USER'? I have been all over encode and decode but just don't seem to be getting it!

Cheers, Mark.

2
  • 1
    $_POST['packed']['type']?? Commented Mar 15, 2016 at 21:32
  • Do yourself a favor, simply place a print_r($_POST) or var_dump($_POST) at the top of the PHP page which receives the AJAX request. Perform the request and look closely at the data printed to the screen. Familiarize yourself with how form data is posted to your PHP, including what gets passed and what doesn't. If you're sending JSON you'll have to use json_decode() to get to the values properly. Commented Mar 15, 2016 at 21:39

1 Answer 1

2

The value of $_POST['packed'] is a JSON string. In order to check the value of type, you will first need to decode the JSON into a native PHP stdClass object using json_decode().

$packed = array_key_exists('packed', $_POST) ? 
          json_decode($_POST['packed']) : 
          null;

if ($packed && $packed->type === 'USER') {
    // do stuff
}

Here I am first making sure that 'packed' exists within the $_POST array. If it does, I pass it through json_decode(), otherwise I return null. If the value of $_POST['packed'] is, for some reason, not valid JSON, it will also return null.

Next I check that $packed is truthy, and that $packed->type equals 'USER'.

Sign up to request clarification or add additional context in comments.

4 Comments

Why should the OP "do this"? A good answer will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO.
Will array_key_exists() work before you have decoded the JSON?
Yes, it will, because 'packed' is a key in your posted data object. Only the value of $_POST['packed'] would be a JSON-encoded string.
{"packed":"{\"type\":\"USER\",\"method\":\"LOGIN\",\"email\":\"root\",\"pw\":\"S0laris7.1\",\"remember\":\"false\"}"} - Wed, 16 Mar 16 08:57:27 +1100 YEAH IT WORKED - Wed, 16 Mar 16 08:57:27 +1100 Thank you so much jpec! Was going around in circles!!! That did it a treat. Ta again!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.