1 year ago

How to get the ajax response from controller to a PHP variable on the view

Posted 1 year ago by bobmyles

I am making an ajax request to the controller as shown below;

    $(function() {
    // when select changes
        $('#languageselector').on('change', function() {
            // create data from form input(s)
            let formData = $('#myForm').serialize();
            // send data to your endpoint
                url: '/selected/languageId',
                method: 'post',
                data: formData,
                dataType: 'json', // we expect a json response
                success: function(response) {
                    // whatever you want to do here. Let's console.log the response

On the controller, I am returning

public function selectedLangId(Request $request)
    return response()->json(['success'=> $request->languageSelected]);

I would like to get this JSON response json(['success'=> $request->languageSelected]) and assign it to a PHP variable on the view.

How do I manage that?

From the logs, the response is in the form of {"success":"2"}

I would want to get this JSON response and save it into a PHP variable on the view....

I want to use this variable to display certain forms according to this selection.

Please sign in or create an account to participate in this conversation.