I'm looking to improve my jQuery code.
The piece of code is submitting data to another PHP page for processing.
At the moment I'm taking data submitted from a form, and taking data from a custom data attribute from the page.
Here's the code
// Add new comment to nit on comment.php page
$('#new_comment_form').bind('submit', function(e) {
// Prevent default
e.preventDefault();
var commentNitId = $('#left_content').attr('data-nit-id');
var commentData = 'nit_id=' + commentNitId + '&new_comment_text=' + $('textarea.new_comment').val();
$.ajax({
type: "POST",
url: "ajax/addComment.php",
data: commentData,
dataType: "json",
success: function(comment_response) {
// Code upon success
},
error: function() {
// Error
alert("Error adding comment");
}
});
});
I'm just wondering if there is a better ("neater") way to serialize the data ready to submit to the form?
Kind Regards,
Luke
3 Answers 3
Yes. If you supply an object (a standard Javascript object) to $.ajax as the data option, jQuery will handle the serialization for you.
$.ajax({
type: "POST",
url: "ajax/addComment.php",
data: {
nit_id: commentNitId,
new_comment_text: $('textarea.new_comment').val()
},
dataType: "json",
success: function (comment_response) {
// Code upon success
},
error: function () {
// Error
alert("Error adding comment");
}
});
If you want to what this produces, the function used internally is jQuery.param. So:
jQuery.param({
nit_id: 5,
new_comment_text: 'foobar'
});
// output: "nit_id=5&new_comment_text=foobar"
Note that this has the added bonus of escaping characters where necessary.
Comments
Please look at jquery serialize() and serializeArray() functions. They provide a neat way to get form data.
2 Comments
$.ajax({
dataType: 'json',
type:'post',
url: "ajax/addComment.php",
data:$(this).parents('form:first').serialize(),
success: function (comment_response) {
// Code upon success
},
error: function () {
// Error
alert("Error adding comment");
},
});