user2997418 user2997418 - 2 months ago 20
jQuery Question

jQuery .append doesn't work on .submit

I have an AJAX function that loads data from the database using a simple

select *
... to a div. the function works fine without submit, but when I use a form, it doesn't work and the
#itemContainer
is empty, Am I missing something? I even tried :

$(document).ready(function() {
$("#myForm").submit(function() {


but didn't work also

My code :

<script id="source" language="javascript" type="text/javascript">
$("#myForm").submit(function() // <<< This works when I use $(function ()
{
$.ajax({
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
});
</script>



Answer

You didn't cancel form submission event.

Add preventDefault() in your submit

Like this

$("#myForm").submit(function(event) {
  $.ajax({
    url: 'models/fetchUsers.php', //the script to call to get data
    dataType: 'json', //data format
    success: function(data) //on recieve of reply
      {
        $.each($(data), function(key, value) {
          $('#itemContainer').append(value.user_id);
        });
      }
  });
  event.preventDefault();
});

Update:

event.preventDefault() is depricated.

try to use return false;

Like this

$("#myForm").submit(function(event) {
  $.ajax({
    url: 'models/fetchUsers.php', //the script to call to get data
    dataType: 'json', //data format
    success: function(data) //on recieve of reply
      {
        $.each($(data), function(key, value) {
          $('#itemContainer').append(value.user_id);
        });
      }
  });
  return false;
});