posting javascript populated form to another php page

129 views Asked by At

I'm trying to take some js that pulls data from another web application and populates a form by clicking "Populate Contact Info" and then click a "Submit" button to push the fields to a new php that then processes them. So basically how do I pass populated form field to a second form on the same page that I can then submit? Or is there a better way?

<form action="#" name="data" id="data">
<input type='button' value='Populate Contact Info' onclick='popAllContactFields()' />
Contact Info: 
First Name: <input type='text' readonly="readonly" id='cfname' name='cfname' />
Last Name:<input type='text' readonly="readonly" id='clname' name='clname' />
Email: <input type='text' readonly="readonly" id='cemail' name='cemail' />
</form>
<script type="text/javascript">
/* popAllContactFields()
Populates all the contact fields from the current contact.
*/
function popAllContactFields()
{
    var c = window.external.Contact;
    {
        // populate the contact info fields
        popContact();
    }
}

/* popContact()
Populates the contact info fields from the current contact.
*/
function popContact()
{
    var c = window.external.Contact;
    // set the contact fields
    data.cfname.value = c.FirstName;
    data.clname.value = c.LastName;
    data.cemail.value = c.EmailAddr;
}
</script>

<form action="ordertest.php" method="post">
<input name="cfname" id="cfname" type="hidden" >
<input name="clname" id="clname" type="hidden" >
<input name="cemail" id="cemail" type="hidden" >
<input type="submit" value="Submit">
</form>

1

There are 1 answers

0
Gábor Imre On

If you can manage to receive the data with an AJAX call as a JSON then it's vary easy. With using jQuery ($) and Lodash (_ but you can try Underscore as well):

$.get('an-url-that-returns-the-json', function(parsedData) {
    _.forEach(_.keys(parsedData), function(key) {
        console.log('key:', key);
        $('#'+key).val(parsedData[key]); 
    });
});

If it's tough at first sight read some about jQuery selectors, AJAX ($.get()) and $(...).val().

You can also make a list about the keys that you want to copy, e.g. var keysToCopy = ['cfname', 'clname', 'cemail'] and then _.forEach(keysToCopy, function(key) {...}), this gives you more control with the copied data.

If you cannot use AJAX but can control the output of the source PHP, then I'd rather create the data as a raw JS object. If you cannot control the generated stuff then you must use something like you wrote, that also can be helped by some jQuery based magic, e.g.

_.forEach(keysToCopy, function(key) { 
    var prop = $('#source-form #'+key).val();
    $('#target-form #'+key).val(prop)
});

Based on these you can think how you can solve if the source and target IDs are not the same.