简体   繁体   中英

jQuery populate form from json

I'm clearly missing something about jquery... I'm trying to populate a form that is inside a jQueryUI dialog box. I'm getting the JSON data just fine, but it escapes me how I reference the data and set the value of the form fields...

You will see THREE attempts below - the last one is the one almost everyone says to use - but the form remains BLANK... What am I missing?????

$( '#companies' ).on( 'click', '.uLink' , function( event ) {
    // set ID
    var xid = $( this ).data( 'identity' );
    // get record
    $.ajax({
        type: 'POST',
        url: 'm/company_edit.php',
        dataType: 'json',
        data: { id: xid },
        success: function ( data ) {
            // display dialog
            $( '#company-form-container' ).dialog( 'open' );

            /* ATTEMPT #1 - with a variant on 'name' - form remains blank
            // populate form
            $( '#companyid' ).val( value.id );
            $( '#name' ).val( 'test' + value.name );
            $( '#address1' ).val( value.address1 );
            $( '#address2' ).val( value.address2 );
            $( '#city' ).val( value.city );
            $( '#state' ).val( value.state );
            $( '#postalcode' ).val( value.postalcode );
            $( '#phone' ).val( value.phone );
            $( '#contact' ).val( value.contat );
            $( '#email' ).val( value.email );
            */

            /* ATTEMPT #2 - supposed to make some accommodation for field type...
                            Make assumption that fields are named same as JSON fields, and the you only
                            want to use the data value in that one spot...*/
                           /*
            var frm = '#company-form';
            $.each(data, function( key, value ){
                var $ctrl = $( '[name='+key+']', frm );
                switch( $ctrl.attr( "type" ) )  {  
                    case "text" :   
                    case "hidden":  
                    case "textarea":  
                    $ctrl.val(value);   
                    break;   
                    case "radio" : case "checkbox":   
                    $ctrl.each(function(){ if($(this).attr('value') == value) {  $(this).attr("checked",value); } });
                    break;  
                }  
            });  
            */

            // attempt 3 - still no go
            $.each( data, function( key, value ) {
                $( '#' + key ).val( value ); 
               });

/* // attempt suggested below - no changes... var c = jQuery.parseJSON( data );

            // populate form
            $( '#companyid' ).val( c.id );
            $( '#name' ).val( c.name );

*/

        },

        error: function () {    
            // there's an error
            $( '#message' ).html( '<p>There was a problem on the server... </p>' );
            $( '#message' ).removeClass( 'hidden' ).addClass( 'message' );
        }
    });

    return false;
});

Sample of JSON data

[{"id":"3", "name":"Sub Customer B", "address1":"232 road", "address2":"", "city":"Galatan ", "state":"TN", "phone":"", "email":""}]

and this is the HTML Form

<!-- the form -->
<div id="company-form-container" title="Create New Company">
<p class="validateTips">* fields are required.</p> 
<form id="company-form" >
<fieldset>

    <input type="hidden" name="customer_id" id="customer_id" value="" />

    <label for="name">name<sup>*</sup> <span class="fieldhint"></span></label> <br/>
    <input type="text" name="name" id="name" 
           size="50" maxlength="100" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="address1">address1 <span class="fieldhint"></span></label> <br/>
    <input type="text" name="address1" id="address1" 
           size="20" maxlength="100" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="address2">address2 <span class="fieldhint"></span></label> <br/>
    <input type="text" name="address2" id="address2" 
           size="10" maxlength="50" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="city">city <span class="fieldhint"></span></label> <br/>
    <input type="text" name="city" id="city" 
           size="20" maxlength="50" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="state">state <span class="fieldhint"></span></label> <br/>
    <input type="text" name="state" id="state" 
           size="5" maxlength="3" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="postalcode">postal code <span class="fieldhint"></span></label> <br/>
    <input type="text" name="postalcode" id="postalcode" 
           size="20" maxlength="15" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="phone">phone <span class="fieldhint"></span></label> <br/>
    <input type="text" name="phone" id="phone" 
           size="20" maxlength="20" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="contact">contact <span class="fieldhint"></span></label> <br/>
    <input type="text" name="contact" id="contact" 
           size="20" maxlength="50" class="text ui-widget-content ui-corner-all" /><br/>

    <label for="email">email <span class="fieldhint"></span></label> <br/>
    <input type="text" name="email" id="email" 
           size="20" maxlength="100" class="text ui-widget-content ui-corner-all" /><br/>

</fieldset>
</form>

myopic coding... brought on by too many little things...

the issue was that the form had a field "customer_id" but the JSON was feeding "id"...

$.each( data, function( key, value ) {
    $( '#' + key ).val( value ); 
});

THIS code did indeed work, once I corrected this error - of course I had to break it out into a separate page and isolate each step in order to see that - however it's give me a little better insight.

Thx for the help

Success function is returning json data into 'data' variable, while you are using 'result' variable in your 3rd attempt.

So, Changing "success: function ( data )" line into "success: function ( result )" maybe solve your problem.

EDIT

Check Using,

var c = jQuery.parseJSON( data );
$( '#companyid' ).val( c['id'] );
$( '#name' ).val( c['name'] );

use jQuery.parseJSON() to decode the json encoded data in the method 1. Make sure that you do send json encoded data from your company_edit.php

For Your Information

I guess it would be perfect if you can use a Javascript template engine which will do the trick for you. Try one of these with the method one.

Good Javascript template engine to work with JSON

JSON templating engine

What Javascript Template Engines you recommend?

http://www.jquery4u.com/javascript/10-javascript-jquery-templates-engines/

您可以使用https://github.com/corinis/jsForm用json填充表单字段(并再次返回)

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