I am trying to add some functionality to a register page that I am building.
The functionality is finding an address from a postcode and adding that data to the input form.
I have found a way to do this but there are some issues involved with the way that I am doing it. At the moment I am using a form with a submit button then using if(isset($_post) which means the page will be reloaded once this submit button is hit which I dont want.
My thinking is that I will need to use some jquery or ajex to do with without reloading the form but honestly I am not sure where to begin.
I have wrote a funtion that returns the data that I need as an array
postcode_api_test.php
<?php
function lookuppostcode($postcode)
{
$postcode = str_replace(" ", "", $postcode);
$key = 'MY API KEY';
$request = 'https://api.getAddress.io/v2/uk/' . $postcode . '?api-key=' . $key;
$response = file_get_contents($request);
$jsonresponse = json_decode($response, true);
$returnData = array();
$returnData['lat'] = $jsonresponse['Latitude'];
$returnData['lon'] = $jsonresponse['Longitude'];
$returnData['totalAddresses'] = count($jsonresponse['Addresses']);
$addressArray = explode(',', $jsonresponse['Addresses'][0]);
$returnData['locality'] = $addressArray[4];
$returnData['city'] = $addressArray[5];
$returnData['county'] = $addressArray[6];
$returnData['addresses'] = array();
foreach ($jsonresponse['Addresses'] as $address) {
$addressArray = explode(',', $address);
$fullAddress = '';
foreach ($addressArray as $item) {
if ($item != ' ') {
$fullAddress .= $item . ",";
}
}
$fullAddress = trim($fullAddress, ",");
$returnData['addresses'][] = array(
'line1' => $addressArray[0],
'line2' => $addressArray[1],
'line3' => $addressArray[2],
'line4' => $addressArray[3],
'locality' => $addressArray[4],
'city' => $addressArray[5],
'county' => $addressArray[6],
'fullAddress' => $fullAddress,
);
}
return $returnData;
}
?>
postcode.php:
<?php
include 'postcode_api_test.php';
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src = "ajex_test.js"> </script>
<form method="post">
<form method = "post">
<div class="form-group">
<label class="control-label">Entity Type</label>
<label class="control-label">Title</label>
<input type="text" name="postcode" id="postcode" class="form-control" value = "">
<button class="btn btn-success" onclick = "postcodelookup()" name = "postcodebtn" id="postcodebtn"> </button>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
</form>
</form>
I was wondering if anybody has any pointers of how to start this off?
ajax_test.js
function postcodelookup($postcode){
$("#postcodebtn").click(function(){
$.ajax({
type: "GET",
url: "postcodecall.php",
data:{"postcode":$("#postcode").val},
success: function(data){
$("#div1").html(data);
}
});
});
};
postcodecall.php
<?php
include 'postcode_api_test.php';
if(isset($_GET["postcode"])){
$postcode = $_GET["postcode"];
lookuppostcode($postcode);
echo $data;
}
?>