Home > database >  Is there any way to update a var in JS (ajax) using HTML Form?
Is there any way to update a var in JS (ajax) using HTML Form?

Time:09-16

So, I have the next code in HTML, my goal is to convert the location to Geocode (lat&long).

<html>

<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script>
        $.ajax({
            url: 'http://api.positionstack.com/v1/forward',
            data: {
                access_key: 'my private key',
                query: 'Thisshouldbeupdated(is my location e.g Transilvania,Romania)',
                limit: 1
            }
        }).done(function(data) {
            console.log(JSON.parse(data));
        });
    </script>

    <script>
        var query = "";

        function update() {
            // find the input element by ID and assign its value to `myVarToUpdate`
            query = document.getElementById("").value;
        }
    </script>
</head>

<body>
    <form>
        <input id="query" value="" />
        <button type="button" onclick="update()">Update</button>
    </form>
</body>

</html>

So, after I hit update (or submit) to update the var and to refresh and get the data from the PositionStack API.

Thank you so much

CodePudding user response:

First give your form a way to identify it. Add an id or class to select the form. Remove the onclick event listener and change the button's type to submit.

<form id="query-form">
  <input id="query" value="" />
  <button type="submit">Update</button>
</form>

You'll need to be able to call the $.ajax request every time you submit your form. The easiest way to do this is to wrap the AJAX request in a function. Let's call this function getPosition. Give the function a single parameter called query. This parameter is the string that we'll send to the server when calling the getPosition function.

function getPosition(query) {
  $.ajax({
    url: 'http://api.positionstack.com/v1/forward',
    data: {
      access_key: 'my private key',
      query: query,
      limit: 1
    }
  }).done(function(data) {
    console.log(JSON.parse(data));
  });
}

Now connect the form and the getPosition function.
Select the form and the query input. Listen to the submit event on the form element. This event is triggered whenever you press a submit button inside a <form> element.

While submitting, get the value of the query input. Then call the getPosition function while passing the query value.

const $form = $('#query-form');
const $query = $('#query');

$form.on('submit', event => {
  event.preventDefault(); // Don't submit, but do our custom behavior.
  const query = $query.val();
  getPosition(query);
});
  • Related