I'm trying to make a autofill for addresses in Javascript. On Google and Stackoverflow I have read a few topics.
However, I don't get it working. I don't get results in my disabled forms.
I use this code:
Index.php
For the form and for the check
<form name="form1" method="post" action="<? echo $PHP_SELF;?>">
<input id="postcode" type="text" class="form-control" name="postcode" placeholder="bijv. 0000AA" required="" aria-required="true">
<input id="number" type="text" class="form-control" name="number" placeholder="bijv. 000" required="" aria-required="true">
<input id="straat" type="text" class="form-control" name="straat" placeholder="" disabled>
<input id="plaats" type="text" class="form-control" name="plaats" placeholder="" disabled>
<input class="btn btn-primary" type="submit" name="submit" value="Controleer" />
</form>
<script type="text/javascript">
$(document).ready(function() {
function myrequest(e) {
var name = $('.username').val();
$.ajax({
method: "GET",
url: "pcget.php", /* online, change this to your real url */
data: {
postcode: pcode
number: pnumber
},
success: function( responseObject ) {
alert('success');
$('#straat').val( 'straat' );
$('#plaats').val('plaats');
/*
once you've gotten your ajax to work, then go through and replace these dummy vals with responseObject.whatever
*/
},
failure: function() {
alert('fail');
}
});
}
$('#fetchFields').click(function(e) {
e.preventDefault();
myrequest();
});
});
</script>
pcget.php
This is the place for the check.
<?php
include_once '../php/config.php';
$postcode = $_GET['pcode'];
$number = $_GET['pnumber'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.postcodeapi.nu/v2/addresses/?postcode=". $postcode ."&number=". $number ."",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"accept: application/hal+json",
"x-api-key: <snip>"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
$object = json_decode($response, true);
$postcode = $object['_embedded']['addresses']['0']['postcode'];
$plaats = $object['_embedded']['addresses']['0']['city']['label'];
$straat = $object['_embedded']['addresses']['0']['street'];
$number = $object['_embedded']['addresses']['0']['number'];
if(empty($_POST) === false)
{
echo ''. $plaats .', ';
echo ''. $straat .', ';
}
?>