0

I want to submit my form using ajax and process it using PHP. What I have done so far is, have it take the user's location (zip code/postal code) using ajax and process it using PHP to show users data related to his/her location. What I want to do now is add a form and display the relevant data when the form is submitted. I'm entirely new to Ajax, JSON. Is it possible to achieve this? Thanks in advance.

<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else { 
x.innerHTML = "Geolocation is not supported by this browser.";
 }
}
function showPosition(position) {

  const KEY = "hidden";
  const LAT = position.coords.latitude;
  const LNG = position.coords.longitude;
  let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${LAT},${LNG}&key=${KEY}`;
  //ajax request
  fetch(url)
    .then(response => response.json())
    .then(data => {
      console.log(data);
      let parts = data.results[0].address_components;

parts.forEach(part => {
       
  if (part.types.includes("postal_code")) {

const dbParam = JSON.stringify(part.long_name);
xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
 document.getElementById("demooo").innerHTML = this.responseText;
  }
   xmlhttp.open("GET","readJson.php?x=" + dbParam);
xmlhttp.send();
    }
   });

    })
    
}
   </script>

The following is my HTML code.

 <form action="readJson.php" method="get">
 <input id="datee" type="date" name="datee">
  <input id="submit" type="submit" name="search">  
  </form>


  <div id="demooo"></div>

What I want to achieve is something like this. The following is my php code

    $obj = json_decode($_GET["x"], false);

    if(isset($_GET['search'])){
    $res=mysqli_query($conn, "SELECT * FROM trin WHERE tr_departuredt LIKE '%$_GET[datee]%' && WHERE tr_postalcode=$obj");

    //if no match found
    if(mysqli_num_rows($res)==0){
    echo '<script>alert("Sorry Please try again ")</script>';
    echo "<script type='text/javascript'> document.location ='find.php'; </script>";

    }else{

    while($row= mysqli_fetch_assoc($res))
    {

    //the data i want here

    }

    }

    }

    //if the search button is not clicked
    else{

    $res=mysqli_query($conn, "SELECT * FROM trin WHERE tr_postalcode=$obj");

    while($row= mysqli_fetch_assoc($res))
    {

    //the data i want here


    }
doo_doo_fart_man
  • 396
  • 3
  • 11
Gamer boy
  • 43
  • 4
  • 1
    Add an event listener for the form's `submit` event. The event listener should use `event.preventDefault()` to prevent normal form submission, then call your AJAX code. – Barmar Oct 22 '21 at 16:17

0 Answers0