dimanche 20 décembre 2020

html form does not get sent after onSubmit function

The geocodeAddress() function uses fetch to send a http request. Before I added "event.preventDefault()" as a parameter to the function, it would not run properly (TypeError: Network Error) as the request was being interrupted by the page reloading caused by the form being sent. However, once I added it, the form no longer gets sent. I don't think the problem lies with the php code as I have not altered it at all. What could be causing this?

I had the same error in this post before 'TypeError: NetworkError when attempting to fetch resource' on form submit ReactJS

    <form action="private/database.php" method="POST" onsubmit="geocodeAddress(event.preventDefault())"> 
      <input type="text" name="surname" placeholder="性氏" required><br>
      <input type="text" name="given_name" placeholder="名字" required><br>
      <label for="male">
        <input type="radio" id="male" name="gender" required>
        男性
      </label>
      <label for="female">
        <input type="radio" id="female" name="gender">
        女性
      </label><br>
      <input type="text" name="email" placeholder="電子信箱" required><br>
      <input type="text" name="phone_number" placeholder="電話" required><br>
      <input type="text" id="address" name="address" placeholder="地址" required><br>
      <input type="hidden" id="lat" name="lat">
      <input type="hidden" id="lng" name="lng">
      <input type="date" name="cleaning_date" required><br>
      <input type="submit" name="form_submit">
    </form>
    <script>
        function handleErrors(res) {
          if (!res.ok) {
            throw Error(res.statusText);
          }
          return res;
        }

        function geocodeAddress() {
          const address = document.getElementById('address').value;
          fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=AIzaSyDxsdfWYv25UrruPXLqeXKVYUnD-VyReA`)
            .then(handleErrors)
            .then(res => res.json())
            .then(data => {
              console.log(data);
              document.getElementById('lat').value = data.results[0].geometry.location.lat.toString();
              document.getElementById('lng').value = data.results[0].geometry.location.lng.toString();
            })
            .catch(error => console.log(error));
        }
    </script>



Aucun commentaire:

Enregistrer un commentaire