Jquery – Post form in JQuery and populate DIV – broken in IE

ajaxformsjquery

I am trying to create a form that posts data via jQuery and populates the return into the same DIV. This way the page does not refresh on post action.

<div id="add_value_form">

<form method="POST" action="#" onsubmit='return false'>
  <!-- input fields -->
  <input type="submit" value="Add" onclick='post_form("/add_value");'>
</form>

</div>

The JS function:

function post_form(url) {
  $.post(url, {'test':'test'}, function(data) {
    $("#add_value_form").empty().append(data); 
  }, "text");
}

This works perfectly in FF3, however it would only work randomly in IE6/7.

The server confirms that post requests are coming through from IE, yet it would get the post data only occasionally.

Curious, I decided to alert the data variable:

$.post(url, {'test':'test'}, function(data) {alert(data);}, "text");

Surely enough, FF3 would print out the return HTML every time, while IE6/7 would mostly print blanks, with an occasional HTML return. I was not able to find anything on this problem, so what am I doing wrong?

Resolved: I tracked this to an HTTP redirect I had in my request handling code. So the function handling the POST request would throw a redirect, and IE does not like it. I had a total mental constipation at the time, and I don't really need the redirect.

The weird part, of course, is that this works in FF, and IE would on occasion work as well, with the redirect in place.

Best Answer

I would say that you don't have to use the form tag at all in this scenario.

<div id="add_value_form">
  <!-- input fields -->
  <input type="button" value="Add" onclick='post_form("/add_value");' />
</div>

Edit As Paolo Bergantino said I would also avoid using the inline javascript. So instead use:

<div id="add_value_form">
  <!-- input fields -->
  <input type="button" value="Add" class="formSubmitButton" />
</div>

Javascript

$(document).ready(function() {
  $('.formSubmitButton').click(function() {
      $.post('/add_value', {'test':'test'}, function(data) {
          $("#add_value_form").empty().append($(data));
      }, "text");
  });
});

Update Since this is still causing a problem, I would perform some testing with the $.ajax method. Also, I don't believe that POST calls would ever get cached, but just in case try setting the cached to false. Another test, to make sure your not having a serialization issue, is to pass your data in already encoded. And if your still having issues you can try to set your dataType to text

$.ajax({
  url: '/add_value',
  type: 'POST',
  cache: false,
  data: 'test=testValue',
  dataType: 'text',
  complete: function(xhr, textStatus) {
    alert('completed');
  },
  success: function(data) {
    alert(data);
  },
  error: function(xhr, textStatus, errorThrown) {
    alert('woops');
  }
});