I am learning AJAX by following some online tutorials and getting help from the very kind SO community when stuck. I am slowly getting the hang of it.
My question is based on 2 different tutorials I am following for a contact form
Tutorial 1 does the follwoing:
jQuery.ajax({
url: "contact_mail.php",
data:'userName='+$("#userName").val()+'&userEmail='+$("#userEmail").val()+'&subject='+$("#subject").val()+'&content='+$(content).val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
Tutorial 2 does the follwoing:
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
My question
Unfortunately both tutorials does not really cover the url
and data
attributes in the ajax call and this is where my question comes in.
- Where tutorial1 physically gets all the form fields i.e
data:'userName='+$("#userName").val()+
tutorial2 simply does the followingdata: formData
Thus am I correct in saying that you do not physically have to get all the form fields like in tutorial1 but rather you can just get the whole form and assign it to a variable and send that as data?
- Tutorial 1 hardcodes the
url
where tutorial2 gets the form and assign the action attribute to theurl: $(form).attr('action')
,
Thus am I correct in saying that you do not have to hardcode the URL but rather get it from the form and assign the attribute action to the url?
- Which example/ tutorial is the better one in terms of best practice?
Thanks in advance