2

On a dropdown option, I would like to listen in and get the value of the option selected by the user.

Then I would like to pass this value to a PHP variable for use in the later part of the blade view PHP script.

I do not want to reload the page hence from the online look, I found ajax to be the only possible way.

I tried to implement as shown below but hitting a snag as the page loads on submit.

Even better is it possible to have a select option drop down that you get the selected value without submit?

My HTML code:

<form id="myForm">
    <div class="button dropdown">
      <select name="languageSelected" required="required" id="languageselector">
        <option value="">Select the language</option>
        @foreach($reviewForm_language as $lang)
         <option value="{{$lang->id}}">{{$lang->name}}</option>
        @endforeach
      </select>

    </div>
    <input id="ajaxSubmit" type="submit" value="Select"/>
  </form>

The JavaScript code:

<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

<script>    
jQuery('#languageselector').on('change', function(){      

    jQuery.ajax({
      url: "{{ url('/selected/id') }}",
      method: 'post',
      data: {
         id: $(this).val(),
      },
      success: function(result){
         jQuery('.alert').show();
         jQuery('.alert').html(result.success);
      }
    });

});

The PHP code to pick the selected language id

<?php
  $langId = request()->get('languageSelected');
?>

My route code;

Route::post('/selected/languageId', 'ProfileController@selectedLangId');

My controller Code;

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

I am learning AJAX, and for some reasons the page loads. Anyone kindly guide me?

Zeth
  • 2,273
  • 4
  • 43
  • 91
User101
  • 115
  • 1
  • 4
  • 11
  • 2
    Please write which snag you hit. Did it give you an error? Was the output blank? Did you computer explode? ;-) – Zeth Feb 11 '19 at 02:04
  • @Zeth the page reloads, this was unexpected as I wanted this not to happen – User101 Feb 11 '19 at 02:07
  • 1
    So, when you're selecting an option on your ``-button that the page reloads? – Zeth Feb 11 '19 at 02:12
  • @Zeth on submit thats when the page reloads – User101 Feb 11 '19 at 02:15
  • you post as `id` but when you retrieve the key using `languageSelected` – Kelvin Feb 11 '19 at 02:19
  • and your route is `'/selected/languageId'` but you post it to `'/selected/id'` – Kelvin Feb 11 '19 at 02:20
  • @Kelvin I changed the URL to test if I would get A 404. But still gets the page to reload... – User101 Feb 11 '19 at 02:23
  • What do you expect to happen when "Select" is clicked? The ajax query/response is only bound to the change of the language drop down. – Jon P Feb 11 '19 at 03:33

3 Answers3

1

Try changing the request parameter from id to languageSelected :

<script>    
jQuery('#languageselector').on('change', function(){

    jQuery.ajax({
    url: "{{ url('/selected/languageId') }}",
    method: 'post',
    data: {
        languageSelected: $(this).val(),
    },
    success: function(result){
        jQuery('.alert').show();
        jQuery('.alert').html(result.success);
    }
    });

});

</script>

And get to input (since you sent a post, not a get) :

<?php
    $langId = request()->input('languageSelected');
?>
Hasta Dhana
  • 4,699
  • 7
  • 17
  • 26
0

Reloading the page is normal behavior for an input of type submit. If you do not want this default behavior, you can change your input type to button like so: <input type="button"/>, or just use a button element like so: <button type="button"></button>.

Liew Xun
  • 99
  • 5
0

If I understand it correctly, then it's not possible, what you're trying to achieve. PHP is rendered server-side, - which means that if you're fetching a variable through AJAX, - that you can't 'put that into a PHP-variable', since that PHP-variable can only be populated on the server.

So once you've fetched the value using AJAX, then you would have to do the rest using JavaScript/jQuery, - or having to reload the page.

It looks like that you're trying to make an on-page language-selector. Even though it would be a neat feature to be able to change the language of a page without reloading the page, then I wouldn't recommend you of doing it. The reason being, that that would slow your page down significantly, since all languages would have to be loaded on all pages. ... And also; as a developer, a language-switcher is something that is being toggled and played with, since we (developers) have to check all languages and features on a page. But regular users never even touch it. They only use it, if your site incorrectly identifies which language the visitor prefers (a malfunction, if you will). Ideally, your site should show the same language that the visitors browser uses or based on geo-location. So it sounds like you're spending time on a feature, that I wouldn't, if I were you.

If you do insist on continuing what you've started, then I would modify my jQuery-code, so it doesn't only do something on success, but also if it hits and error, so you can see if you actually receives a value from your AJAX-request. This answer does it nicely.

Remember that you shouldn't need to press 'Submit' in order get the AJAX-response. Pressing 'Submit' will always submit the form (and reload the page), unless you unregister/unbind that function; and in that case, then you might as well not use a form at all.

If you replace your submit-button with a regular-button and bind that to the jQuery-function, that would be a good way of doing it:

<form id="myForm">
 <div class="button dropdown">
  <select name="languageSelected" required="required" id="languageselector">
    <option value="">Select the language</option>
    @foreach($reviewForm_language as $lang)
     <option value="{{$lang->id}}">{{$lang->name}}</option>
    @endforeach
  </select>
 </div>
<buttom id="ajaxSubmit" type="submit" value="Select" />
</form>


$(function(){
  $('#ajaxSubmit').click(function() {    

    jQuery.ajax({
      url: "{{ url('/selected/id') }}",
      method: 'post',
      data: {
        id: $(this).val(),
      },
      success: function(result){
        jQuery('.alert').show();
        jQuery('.alert').html(result.success);
      }
    });
  });
});
Zeth
  • 2,273
  • 4
  • 43
  • 91