0

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

   <script>    
    $(function() {
    // when select changes
        $('#languageselector').on('change', function() {
            // create data from form input(s)
            let formData = $('#myForm').serialize();
            // send data to your endpoint
            $.ajax({
                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
                    console.log(response); 
                }
            });
        });
    });
  </script>

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.

User101
  • 115
  • 1
  • 4
  • 11
  • 1
    You cannot assign it to a PHP variable on the view through an AJAX call. You can use the value returned and make changes to your view using JS. – Bharat Geleda Feb 11 '19 at 06:46
  • 1
    I am not sure whether I understand your question correct or not. But you can create a hidden field in your HTML. You can set that value once Ajax succeed. and whenever you want to use this new value, you can pick that value by jQuery and can use that. – Rohit Mittal Feb 11 '19 at 06:46
  • @RohitMittal how do I achieve that? – User101 Feb 11 '19 at 06:47
  • Can you update your question and show us which PHP variable, you want to update after Ajax response? I will check that and can reply accordingly. – Rohit Mittal Feb 11 '19 at 07:04
  • Make a HTML hidden input element. . On ajax response, set it value by $("#phpvariable").val(response.success); and whenever you want to use its value. Get its value by let phpvariable = $("#phpvariable").val(); and you can compare phpvariable for your purpose. Hope it helps you. – Rohit Mittal Feb 11 '19 at 07:13

1 Answers1

-1
$.ajax({
                type: "POST",
                url: '<?php echo Router::url(array('controller'=>'nameofcontroller','action'=>'controllerfunction'));?>',
                data:formdata ,
                success: function (response)
                {
                    if (response > 0)
                    {

                    } else
                    {
                        $('#check_mail').html('');
                    }

                }
            });
Antu
  • 2,197
  • 3
  • 25
  • 40