0

I need to add a small form to my site. I would like users to be able to submit the form using jQuery's $.ajax() and have the errors displayed by highlighting the invalid fields with a class. I am using PHP on my server to submit the data using cURL to a third party server, which returns a response in JSON.

If the server sends back a success message I need to replace the HTML where the small form was with a success message and display a few additional fields that the user can submit again.

I'm confused as to whether or not I should send a response back in JSON format or HTML? The second form needs to have some kind of data that can included with the form submission so the server knows which record to update.

If I send the response back in HTML, how can I add a class to each INPUT field? If I send it back in JSON, how can I show the HTML for the form with the additional fields?

Zoolander
  • 2,093
  • 4
  • 26
  • 37

2 Answers2

1

What I would do is send back the json response. You can use javascript to inspect the response and render the appropriate content. You can store any html for later use on your page using a script tag with the type "text/template".

HTML
<script id="response-form" type="text/template">
<div>
<span></span>
<form>
<input ... />
</form>
</div>

.

JQuery
if (success)
$('originalContentElem').html($('#response-form').html())

You can read more about templating here: Explanation of <script type = "text/template"> ... </script>

Community
  • 1
  • 1
user1026361
  • 3,390
  • 3
  • 19
  • 18
0

Well, since you're using jQuery you could send the response back in HTML and than create a jQuery object to add the classes:

var html = $(responseHTML);

html.find('input').addClass('yourClass');
Korikulum
  • 2,359
  • 19
  • 24