I want to submit my form using ajax and process it using PHP. What I have done so far is, I have taken 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:
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(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))
{
}
}
}
else{
$res=mysqli_query($conn, "SELECT * FROM trin WHERE tr_postalcode=$obj");
while($row= mysqli_fetch_assoc($res))
{
}
What I have tried:
This is what I have tried. Once I click on submit the page refreshes and nothing happens.
<form id="myForm" action="readJson.php" method="post">
<input id="datee" type="date" name="datee">
<button class="submit" id="submit" type="submit" name="search">
</form>
<div id="demooo"></div>
The following is the script code I tried.
<script>
$(function() {
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
$(function() {
$(".submit").click(function() {
var date = $("#datee").val();
var dataString = '&date=' + date;
$.ajax({
type: "POST",
url: "readJson.php",
data: dataString,
});
return false;
});
});
});
</script>