I'm trying to take an input value and assign it to a PHP array. I believe I need to use AJAX, but I keep getting caught up because I need to use PHP to call to the API.
Just in case that's confusing: I need the user to be able to type in the area code and in the dropdown list, the array will call out to Twilio API with the correct area code (not 904) so that it can get the available phone numbers for purchase.
<?php
$sid = "AC655555555555555";
$token = "554353535355555435345";
$twilio = new Client($sid, $token);
?>
<label>DID Area Code</label>
<input class="form-control" type="number" id="did_area_code" required="" />
<label>DID Number</label>
<select class="form-control" name="did_number" id="company_source">
<option value="">--Select One--</option>
<?php
$numbers = $twilio->availablePhoneNumbers('US')->local->read(array("areaCode" => "904"));
foreach ($numbers as $record) {
echo "<option value='" . $record->friendlyName . "'>" . $record->friendlyName . "</option>";
}
?>
</select>
<script type="text/javascript">
$("#did_area_code").on('change', function(){
var area_code = $('#did_area_code').val();
alert(area_code);
});
The below code is what I am using now and works. Feel free to use it if you are trying to create an API call from Twilio to get a list of available numbers for purchase.
add_number.php
<label>DID Number</label>
<select class="form-control" name="did_number" id="did_number">
<option value="">--Select One--</option>
</select>
<script type="text/javascript">
$("#did_area_code").on('change', function(){
var area_code = $('#did_area_code').val().trim();
if (area_code.length == 3) {
$.get("../get_phone_nums.php", {area_code: area_code}, function (result) {
var select = document.getElementById('did_number');
var phone_numbers = JSON.parse(result);
// Clear the select field in case area code is changed
for(var i = select.options.length - 1; i >=1; i--) {
select.remove(i);
}
for(var i = 0; i < phone_numbers.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = formatPhoneNumber(phone_numbers[i]);
opt.value = phone_numbers[i];
select.appendChild(opt);
}
});
function formatPhoneNumber(phoneNumberString) {
phoneNumberString = phoneNumberString.replace(/[^\d]/g, "");
if(phoneNumberString.length == 11) {
return phoneNumberString.replace(/^1?(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
} else {
return null;
}
}
}
});
</script>
get_phone_nums.php
<?php
require_once 'twilio/autoload.php';
use Twilio\Rest\Client;
$sid = "AC5345353535353535435";
$token = "355343553535353535345";
$twilio = new Client($sid, $token);
$area_code = $_GET['area_code'];
$numbers = $twilio->availablePhoneNumbers('US')->local->read(array("areaCode" => $area_code));
$numberArray = array();
foreach ($numbers as $record) {
$numberArray[] = $record->phoneNumber;
}
echo json_encode($numberArray);
?>