简体   繁体   中英

how to input value to database from 2 related option based on API data

I tried to input options value to database from 2 related option, the problem is the value on option is id, not the string. I successfully input value on 1 option value only, but i need 2 of that option value to inputted on my database.

here's my js code :

$(document).ready(function(){
    loadProvinsi('#oriprovince');
    loadProvinsi('#desprovince');
    $('#oriprovince').change(function(){
        $('#oricity').show();
        var idprovince = $('#oriprovince').val();
        loadCity(idprovince,'#oricity')
    });
});

function loadProvinsi(id){
    $('#oricity').hide();
    $('#descity').hide();
    $(id).html('loading...');
    $.ajax({
        url:'process.php?act=showprovince',
        dataType:'json',
        success:function(response){
            $(id).html('');
            province = '';
                $.each(response['rajaongkir']['results'], function(i,n){
                    province = '<option value="'+n['province_id']+'">'+n['province']+'</option>';
                    province = province + '';
                    $(id).append(province);
                });
        },
        error:function(){
            $(id).html('ERROR');
        }
    });
}
function loadCity(province,id){
    $.ajax({
        url:'process.php?act=showcity',
        dataType:'json',
        data:{province:province},
        success:function(response){
            $(id).html('');
            city = '';
                $.each(response['rajaongkir']['results'], function(i,n){
                    city = '<option value="'+n['city_id']+'">'+n['city_name']+'</option>';
                    city = city + '';
                    $(id).append(city);
                });
        },
        error:function(){
            $(id).html('ERROR');
        }
    });
}

if i change to this line code :

province = '<option value="'+n['province']+'">'+n['province']+'</option>';

it successfully become string but the other option cant show the list of city because its based on province id, any suggestion like 2 value on option maybe ?

slice of register form registuser.php

                          <tr>
                            <td><label for="prov_usr">Provinsi</label></td>
                            <td>
                            <select name="prov_usr" id="oriprovince">
                            <option>Provinsi</option>
                            </select>
                            </td>
                          </tr>
                          <tr>
                            <td><label for="kota_usr">Kota</label></td>
                            <td>
                            <select name="kota_usr" id="oricity">
                            <option>Kota</option>
                            </select>
                            </td>
                          </tr>

slice of process.php

header("Content-Type: application/json");
require_once('idmore.php');
$IdmoreRO = new IdmoreRO();
if(isset($_GET['act'])):
    switch ($_GET['act']) {

        case 'showprovince':
            $province = $IdmoreRO->showProvince();
            echo $province;
        break;

        case 'showcity':
            $idprovince = $_GET['province'];
            $city = $IdmoreRO->showCity($idprovince);
            echo $city;
        break;

idmore.php (php class)

class IdmoreRO{
    private $key;
    public function __construct()
    {
        //masukan api key disini
        $this->key = '3f01f13ce2b42ba983ad3f3bc4852f84';    
    }
    //menampilkan data provinsi
    public function showProvince()
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "http://rajaongkir.com/api/starter/province",
            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(
                "key: $this->key"
                ),
            ));
        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) {
            $result = 'error';
            return 'error';
        } else {
            return $response;
        }
    }
    //menampilkan data kabupaten/kota berdasarkan id provinsi
    public function showCity($province)
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "http://rajaongkir.com/api/starter/city?province=$province",
            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(
                "key: $this->key"
                ),
            ));
        $response = curl_exec($curl);
        $err = curl_error($curl);
        curl_close($curl);
        if ($err) {
            $result = 'error';
            return 'error';
        } else {
            return $response;
        }
    }

You need to work with the two values, the string to send to the server on submit, and the id to query for the cities in your ajax request. You will need to use the string in the value attribute since that's what the form will submit to the server, and add an additional attribute with the id so you can use it in the ajax request.

So to build the province select you can do this:

'<option value="'+n['province']+'" data-province_id="'+n['province_id']+'">'+n['province']+'</option>';

and where you get the province_id to query for the cities, access it like

var idprovince = $("#oriprovince option:selected").data("province_id");

Your code should look like this:

$(document).ready(function(){
    loadProvinsi('#oriprovince');
    loadProvinsi('#desprovince');
    $('#oriprovince').change(function(){
        $('#oricity').show();
        var idprovince = $("#oriprovince option:selected").data("province_id")
        loadCity(idprovince,'#oricity')
    });
});

function loadProvinsi(id){
    $('#oricity').hide();
    $('#descity').hide();
    $(id).html('loading...');
    $.ajax({
        url:'process.php?act=showprovince',
        dataType:'json',
        success:function(response){
            $(id).html('');
            province = '';
                $.each(response['rajaongkir']['results'], function(i,n){
                    province = '<option value="'+n['province']+'" data-province_id="'+n['province_id']+'">'+n['province']+'</option>'
                    province = province + '';
                    $(id).append(province);
                });
        },
        error:function(){
            $(id).html('ERROR');
        }
    });
}
function loadCity(province,id){
    $.ajax({
        url:'process.php?act=showcity',
        dataType:'json',
        data:{province:province},
        success:function(response){
            $(id).html('');
            city = '';
                $.each(response['rajaongkir']['results'], function(i,n){
                    city = '<option value="'+n['city_id']+'">'+n['city_name']+'</option>';
                    city = city + '';
                    $(id).append(city);
                });
        },
        error:function(){
            $(id).html('ERROR');
        }
    });
}

You can use jQuery.data() or jQuery.attr()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM