Roman
Roman

Reputation: 3941

Laravel access JSON data in PHP controller

I have this AJAX function, which sends data to a route:

$.ajax({
    url : '/home/update_user_data',
    type : "post",
    contentType: 'application/json;charset=UTF-8',
    data : {'userid' : $('#user-general-i').data('userid'), 'datatype' : datatype, 'newcontent' : newcontent},
    success : function(response) {
        console.log("update_user_data", response);

        if (response['success'] == true) {
            console.log('success');
        } else {

        }
    },
    error : function(xhr) {
        console.log("update_user_data", xhr);
    }
});

In the route I cant figure out how to access the data, usually I can use $data->value but here it does not work. I assume because I dont serialize a form.

Here is how I try to access the data:

public function update_user_data(Request $data) {

    try {           
        error_log($data);
        error_log(print_r($data->all(), True));
        error_log($data->query('userid'));
        error_log($data->userid);
        error_log($data->datatype);
        error_log($data->newcontent);  
    } catch (\Exception $e) {  
        return ['success' => false, 'message' => $e->getMessage()];   
    } 

    return ['success' => true, 'message' => 'Konnte Nutzer nicht updaten'];   
}

I have red the laravel docu on requests and tried all ways to access the data, but I simply get an empty string, no errors.

BUT error_log($data); shows the request and there I can see that the data is there:

userid=4777&datatype=gender&newcontent=1

EDIT

I can get the above string with:

error_log($data->getContent());

But I cant get specific values, I could use regex to extract them or split the string, but that feels super hacky and wrong.

EDIT

I also tried to change the AJAX request:

data : JSON.parse(JSON.stringify(({'userid' : $('#user-general-i').data('userid'), 'datatype' : datatype, 'newcontent' : newcontent})))

I also tried to add:

dataType: "json"

But sadly nothing changed, all error_logare empty.

Laravel Version: Laravel Framework 5.8.27

Upvotes: 0

Views: 228

Answers (1)

Zeshan
Zeshan

Reputation: 2657

In your case, the $data is the Request object not the actual data.

You first need to get data out of the request object.

Try below:

public function update_user_data(Request $request) {
  $data = $request->all();

  // you can now be able to access your data like:
  $data['userid'];
  $data['datatype'];
  $data['newcontent'];
  //...
}

Or in the newer versions of Laravel, you can use request() global function to get data out from the Request object.

request('userid'); // gives you userid passed via ajax i.e `4777`

Change your ajax request:

contentType: 'application/json',
data: JSON.stringify( {"userid": $('#user-general-i').data('userid')} ),
// ...

Upvotes: 1

Related Questions