Tara Samons
Tara Samons

Reputation: 165

How to display results for a form in a div?

I am currently bringing a form into a div like this:

$('#m').load('http://example.com/converter/index.php #converty');

I need the results to display in the #m div, currently it takes me to the converter/index.php page, any help appreciated! The form that is loaded:

<form action="/converter/index.php" method="post" id="conversionForm" style="display: block;">
**do stuff**
</form>

FYI: the page with the script is at the root domain, while the converter is in the folder example.com/converter directory.

Upvotes: 1

Views: 55

Answers (1)

DavidDomain
DavidDomain

Reputation: 15293

Prevent the default behavior of the form submit by using the .submit method on the form element, then collect your form data by using .serializeArray and do what you need to do with it.

Here is an example.

$( "form" ).submit(function( event ) {
  var formData = $( this ).serializeArray();
  $.each(formData, function(i, item) {
    var $p = $("<p>");
    $p.text(item.name + ": " + item.value);
    $("#output").append($p);
  })
  event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
<form method="get" action="foo.php">
  <div><input type="text" name="a" value="1" id="a"></div>
  <div><input type="text" name="b" value="2" id="b"></div>
  <div><input type="hidden" name="c" value="3" id="c"></div>
  <div>
    <textarea name="d" rows="8" cols="40">4</textarea>
  </div>
  <div><select name="e">
    <option value="5" selected="selected">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    </select></div>
  <div>
    <input type="checkbox" name="f" value="8" id="f">
  </div>
  <div>
    <input type="submit" name="g" value="Submit" id="g">
  </div>
</form>

Upvotes: 3

Related Questions