Scott Paterson
Scott Paterson

Reputation: 141

Retrieve data from mysql using ajax and populate input fields

I have a page with a lot of input fields. I am using Jquery to get all of the values of the form at once using data: $("#profile").serialize().

Since my MySQL columns have the same name as my input fields. Is there an easy to select * from my db and load the results into the appropriate fields using jquery / ajax? Perhaps an example or a link?

Thanks, Scott

Edit: Ok thanks for the help, but I am still a bit lost and not getting it to work, here is what I have so far:

<script type="text/javascript">
$(window).load(function(){
$.ajax({
url: "/profile_functions/profile_about_retrieve.php",
type: 'POST',
data: allFormFields,
success: function(){
    //console.log('done');
}
});

jQuery(#profile).find(":input").each(function(key, val) {
fieldName = jQuery(this).attr("name");
if(fieldName != "" && fieldName != undefined) {
    allFormFields[fieldName] = jQuery(this).val();
  }
 });
});
</script>

And a little test data from my db being echo'ed via json_encode

[{"key":"test","value":"9"}]

And html

<form id="profile" method="post">
<input type="text" name="test"
</form>

Upvotes: 1

Views: 1786

Answers (1)

Varun Sheth
Varun Sheth

Reputation: 156

           jQuery(formId).find(":input").each(function(key, val) {

                fieldName = jQuery(this).attr("name");

                if(fieldName != "" && fieldName != undefined) {
                    allFormFields[fieldName] = jQuery(this).val();
                }
            });

Use the allFormFields array to send to the PHP endpoint

                  $.ajax({
                        url: url,
                        type: 'POST',
                        data: allFormFields,
                        success: function(){
                            console.log('done');
                        }
                    });

Upvotes: 1

Related Questions