Reputation: 93
I have a PHP script which is run with jQuery to print out some Html forms however the form does not work because it is loaded with AJAX. When I manually put the HTML form in, the AJAX worked so how can I make it work even when the form is being loaded with Ajax.
Here is the PHP code that echos the form via AJAX
echo "<form action='fetch_chat.php' method='post' class='chat_form' id='chatform_".$row['friends_user_id']."'>
<input type='hidden' name='friends_id' value='".$row['friends_user_id']."'/>
<input type='hidden' name='current_user' value='".$user_id."'/>
<input type='submit' class='chat_submit' name='submit' id='openchat_".$row['friends_user_id']."'/>
</form>";
And here is the ajax code for the form which does not work with the ajax loaded form
$('.chat_form').submit(function() {
var data = $(this).serialize();
$.ajax({
url: "../fetch_chat.php",
type: "POST",
data: data,
success: function(data) {
$('*').html(data);
},
error: function() {
alert('ERROR');
}
});
return false;
});
Upvotes: 1
Views: 90
Reputation: 14195
I generally prefer to stick to .on()
functions, rather than their shorthand equivalents.
Once you read the .on()
manual page, you will notice that it takes the selector
parameter:
selector
Type: String
A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element.
Once you add the selector parameter, the event is delegated instead of being directly bound (like in case of .submit
). Direct bind only works if the element already exists (so it doesn't work for dynamically loaded content).
$(document).on('submit', '.chat_form', function() {
// the rest of the code
});
Upvotes: 1