Reputation:
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() {
$.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>
Upvotes: 2
Views: 1088
Reputation: 9561
It's because page will be reloaded on form submission.
Handle the submit event and add return false
.
<script id="source" language="javascript" type="text/javascript">
$("#myForm").submit(function() {
submitForm();
return false;
});
function submitForm() {
$.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>
Upvotes: 0
Reputation: 25352
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;
});
Upvotes: 6