Search code examples
phpajaxslim-3

Passing data via AJAX responds in NULL values


Passing additional data to my REST server doesn't work quite well.

I have this simple ajax call:

// Client
$(document).on('click', '#car', function(e){   
    e.preventDefault();
    var name  = $(this).data('name');    // Tesla
    var model = $(this).data('model');  // X
    $.ajax({ 
        type: "GET", 
        contentType: 'text',
        cache: false,   
        url: "http://server:80/api/v1/cars/" + name,
        data: JSON.stringify({
                "model": model
              }),         
        success: function(data, textStatus, jqXHR){ },
        error: function(jqXHR, textStatus, errorThrown){}                      
    });
});

The problem is that model is always NULL on my server whereas car is working fine. I also var_dumped the whole request and searched for model but it is not there unfortunately.

// Server
public function show($request, $response, $args)
{          
    $model = $request->getParsedBody()['model']; 
    $name  = $args['id'];

    echo $model;     // NULL
    echo $name;      // Tesla
}

I also don't understand why my request URL looks like this under the developement tools in the browser:

http://server:80/api/v1/cars/Tesla.txt?{"model":"X"}

He puts the JSON at the end of the request url and I think this is not a standard behavior?


Solution

  • Why

    Usually get is a Query String where data is passed through the URL with variables appended to the URL and POST the data is passed through the request body POST can pass more data then GET. in GET everything has to be part of your URL no more data can be added in POST all your data has to be sent throught the message body

    as basic as it get

    Your typical query String : http://example.com/over/there?name=ferret&sname=somethingelse
    
    Yout would use $_GET['name'];
    
    and For POST
    
    URL:http://example.com/over/there
    Message Body name=ferret&sname=somethingelse
    
    $_POST['name'];
    

    so in php you have something called $_REQUEST; in jave you would use request.getParameters which will automatically handle it for you this $_REQUEST handles both get and POST data