Reputation: 21657
jQuery('body').on('click','#submit', function(){
var name = $('input[name=name]').val();
var email = $('input[name=email]').val();
var phone = $('input[name=phone]').val();
var message = $('textarea[name=message]').val();
var dataString = 'name='+ name +'&email='+ email +'&phone='+ phone +'&message='+ message;
var isValid = !jQuery('input[name=name],input[name=email],input[name=phone],textarea[name=message]').filter(function() {return !this.value;}).length;
if (isValid){
jQuery.ajax({
type: "POST",
url: "/submit.php",
data: dataString,
success: function(data) {
d = jQuery.parseJSON(data);
d = d.sent;
if (d == 1){
jQuery('input[name=fname], input[name=lname], input[name=email], input[name=phone], textarea[name=message]').val('');
}
}
});
} else {
console.log('Empty fields');
}
});
At the moment I use pieces of jQuery like above to collect the values
of each input
and textarea
then send them off to my submit.php
file.
I'm wondering if there are any better ways of sending off data using ajax
as I currently send the data off in a string such as
var dataString = 'name='+ name +'&email='+ email +'&phone='+ phone +'&message='+ message;
Thanks
Upvotes: 0
Views: 65
Reputation: 20860
You should send data in the key-value pair form in jQuery.ajax() like :
var dataString = {
'name': name,
'email': email,
'phone': phone,
'message': message
}
jQuery.ajax({
type: "POST",
url: "/submit.php",
data: dataString,
success: function(data) {
......
}
});
Upvotes: 0
Reputation: 3932
you could create a javascript object / model.
I.E
var myCustomModel = { name: null, email: null }
and then populate and send this object.
or easier, you can Serialize your form in one single hit
it would also be way less bloat if you gave your inputs and ID and then request with $("#idofitem").val();
Upvotes: 0
Reputation: 146
I usually prefer to send data as objects per Ajax:
var data = {
'name': name,
'email': email,
'phone': phone,
'message': message
}
In PHP it can then be easily accessed as an array and you don't need to explode the string.
Upvotes: 0
Reputation: 1298
You should create an object:
var DataObj = JSON.stringify({ name: name , email: email, ... }),
That way you can add arrays, lists etc if you need to in the future.
and then the request looks like:
jQuery.ajax({
type: "POST",
url: "/submit.php",
data: DataObj,
success: function(data) {
d = jQuery.parseJSON(data);
d = d.sent;
if (d == 1){
jQuery('input[name=fname], input[name=lname], input[name=email], input[name=phone], textarea[name=message]').val('');
}
}
});
Upvotes: 2