0

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);
?> 
Dave K.
  • 1
  • 7
  • 2
    You can not make that API call on the initial page load already then; you need to make your AJAX request, pass the area code along, make your API call, and then return the appropriate data for the client-side JS to fill the select field accordingly. – 04FS Apr 23 '19 at 13:11
  • Just want to point out that you've got `` in there twice. Once when you `echo` it after your `foreach` loop, and then again a couple lines later, right after your closing `?>` tag. – RToyo Apr 23 '19 at 13:30
  • Thanks @RToyo. I think I did that last night when I was trying 101 different ways to get this to work. – Dave K. Apr 23 '19 at 13:33
  • Formatting improvements – Stephen S Apr 23 '19 at 14:16
  • Or just do a good old `
    ` submit and spit out the results on the "next" page.
    – deceze Apr 23 '19 at 14:26

1 Answers1

0

It sounds like what you'll want to do is have your JS function make an AJAX call to a separate PHP script, which will return the available phone numbers, and then use JS to populate those numbers back into your HTML form.

Below is a basic skeleton of what you'll need to do. I'll leave it to you to determine exactly how you pass the data back and forth between PHP and your AJAX call. I would suggest you encode the data as JSON, since PHP can easily encode an array to JSON, and JS can decode it back to an array, and then JS can proceed to loop through that array. If I understand your intent correctly, you'll need to have JS remove all the <option> children of your <select id="company_source">, and insert new <option> children with the AJAX response.

Here's a rough expansion of the JS in your original script, to make the AJAX call:

<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) {
                        /*
                        Here is where you read the results from the script (perhaps
                        return the phone numbers as json), and loop through them and
                        use javascript to populate your <select> with new <option>
                        tags containing the returned numbers.
                        */
            });
        }
});

And here's what your get_phone_nums.php file might look like:

<?php
    $sid    = "AC655555555555555";
    $token  = "554353535355555435345";
    $twilio = new Client($sid, $token);                                                                                                                                                      

    $numbers = $twilio->availablePhoneNumbers('US')->local->read(array("areaCode" => "904"));

    // Output $numbers for the AJAX call to pick up. Again, perhaps convert it to JSON.
    echo json_encode($numbers);
?>
RToyo
  • 2,877
  • 1
  • 15
  • 22
  • Thanks @rtoyo I tried to vote for your response but, I don't have enough points or whatever. After a lot of failures today, I discovered I had to actually create a separate array from Twilio's. It's working now though. – Dave K. Apr 23 '19 at 21:20