简体   繁体   中英

How can I populate form field with returned JSON data?

I have a two step form. The first step takes user input and sends it to a processor script. The processor script returns all of the data that was submitted to it and some new data using PHP json_encode. The code:

$FirstName      = filter_var($_POST["FirstName"], FILTER_SANITIZE_STRING);
$LastName       = filter_var($_POST["LastName"], FILTER_SANITIZE_STRING);
//and so on for all other POST data
$output = json_encode(array('type'=>'Return', 'first_name'=>$FirstName, 'last_name'=>$LastName, 'other_data'=>'stuff'));

echo($output);

Im using jQuery $.ajax submit to send the data from step 1 form to the processor. I need to populate the subsequently loaded step 2 form with the returned data. I'm using the success handler to load the new form and try and populate the fieldsThis is where I'm stuck.

The jQuery code:

success: function(data){
    if(data.type == "Return"){
        $('#mContent').load('Form/ToPayPal.php');
        $('#first_name').val(data.first_name);
    } else {
        alert('bad');
    }
}

How do I access the returned JSON array and populate the newly loaded form fields with the respective values? I'd prefer to not list each one out, possibly utilize an '.each' function with the 'key' + # and value? I can modify the returned json keys to match the form field IDs.

I had to put the code in a completion function for the .load() IE

$('#mContent').load('Form/ToPayPal.php', function(){
    $.each( data, function( key, value ) {
        $( '#' + key ).val( value ); 
    });
});

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