简体   繁体   中英

How to get and set default values for a form from server

I have a simple HTML form:

<div id="dialog-form-manageadvsertiser" title="Dialog title" style="display: none;">
    <div class="col-xs-12">
        <div class="form-group">
            <label for="inputUserId" class="col-xs-3 control-label">Account number</label>
            <div class="col-xs-9">
                <input data-val="true" data-val-number="The field must be a number." id="User_Id" name="User_Id" value="" />
            </div>
        </div>
    </div>
    <div class="col-xs-12">
        <div class="form-group">
            <label for="inputAdvName" class="col-xs-3 control-label">Advertiser name</label>
            <div class="col-xs-9">
                <input data-val="true" data-val-number="" id="AdvName" name="AdvName" value="" />
            </div>
        </div>
    </div>
</div>

I want to set default values for some fields, these values are dynamic, therefore I have a PHP script that returns a json representation of those values:

{
    "User_Id": "12345"
}

How can I assign this value to the form's UserID field when it loads?

I'm using jquery framework. I would expect some kind of mechanism that triggers a POST request to the server when the for loads, and then assigns the values from the response to the form according to the field ID.

I've tried researching it on google but did not find relevant info.

Thanks!

So you want to make ajax call and populate the fields with default value, you will need $.getJSON to make the call

//Function for get the data and assign default value
function getValues() {
    //get json from server
        $.getJSON( "ajax/test.json", function( data ) {
            $.each( data, function( key, val ) {
              //Am assuming your input name matches with form fields
              $( "input[name='"+ key +"']" ).val(val);
        });
    });
}

//jQuery document ready
$(function(){
    //on page load 
    getValues();

    //This will trigger on change of User_id
    $("#User_Id").on('change', getValues);
});

and in PHP, make sure you are returning a valid json with headers

header('Content-type: application/json');
echo json_encode($data_array);

Here is a working Plunk

for more info on $.getJSON see docs

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