Search code examples
javascriptajaxmaterialize

How do I get data from an input field into my ajax request?


I am trying to get the data from a text field into my ajax request so that I can get a response from an API. But I have little experience with JS so I can't figure it out.

I am using the materialize framework.

HTML:

<div class="input-field">
    <label for="country">Autocomplete</label>
    <input type="text" id="country" class="autocomplete">
</div>

JS:

$(document).ready(function() {
    //Autocomplete
    $(function() {
      $.ajax({
        type: 'GET',
        url: 'https://sandbox.iexapis.com/stable/search/**{I need the text from what the user has put in here}**?token='myiextoken',
        success: function(response) {...
          

Solution

  • You can use jquery val() method to get the input value, then you need to encode this value using encodeURIComponent before passing it into your url.

    $(document).ready(function() {
      //Autocomplete
      $(function() {
        var inputValue = $('#country').val();
        var url = 'https://sandbox.iexapis.com/stable/search/'
                  + encodeURIComponent(inputValue)
                  + '?token='myiextoken';
    
        $.ajax({
          type: 'GET',
          url: url,
          ...