views:

35

answers:

1

Hello all,

I have used jQuery Form plugin to submit the whole form data to server while Ajax. When the server code (php) returns, the retrieved data is in JSON format. What is the best method to populate the form with jQuery.

Here is what I want to do:

  1. The user enters the data on the form
  2. The user submits the form data (I use ajax to submit)
  3. The server code returns.
  4. The user has the ability to retrieve the entered data.

So for the step 4, I want to know what the best method to use to populate a form?

Thank you

A: 

If you can ensure that the returned JSON object contains property names that match your form fields, it can be quite simple to populate the form.

Of course, you need to first evaluate the retrieved JSON, either using eval, or using a JSON library such as this for added security checks.

Then, you can just iterate over the object like this:

var obj = eval(json); /* or JSON.parse(json); */
for (var field in obj)
  $('#' + field).val(obj[field]);

If your form contains non-textual fields (such as a select) you could add an additional check to set the selected index instead.

casablanca
Do you know whether there is an existing example that I can follow?Thank you
q0987