1

I don't really know how to use the Ajax post data function, but i'm using some free simple file and trying to tweak it a little bit.

The simple code part that i want to change is that:

post_data = {
'clcon_user_name'       : $('input[name=name]', clientConParent).val(),
'clcon_user_lastname'   : $('input[name=lastname]', clientConParent).val(),
'clcon_user_email'  : $('input[name=email]', clientConParent).val(),
'clcon_phone_number'    : $('input[name=phone]', clientConParent).val(),
'clcon_msg'         : $('textarea[name=message]', clientConParent).val(),
'pro_mailto'    : $('input[name=promailto]', clientConParent).val()
};

I want to make it dynamic so it will loop through the fields on my form and grab them all in this format: 'npf_{the name atrr of the field}' : $('input[name={the name atrr of the field}]', theForm).val(), for the post_data (for the Ajax $.post(... function).

I tried:

post_data = {
$("input, textarea, select", theForm).each(function(){
'\'npf_$'+$(this).attr('name')'\'' : $('input[name='++$(this).attr('name')+']', theForm).val(),
});
};

Didn't work, also tried:

post_data = {
$("input, textarea, select", theForm).each(function(){
var theName = $(this).attr('name');
'npf+theName' : $('input[name='+theName+']', theForm).val(),
});
};

Didn't work, also tried:

post_data = {
$("input, textarea, select", theForm).each(function(){
var theName = $(this).attr('name');
'npf+theName' : $('input[name='+theName+']', theForm).val(),
});
};

I know i must be doing a couple of things here wrong... i can use some "For Dummies" explanation sense i'm a beginner.

Nori
  • 121
  • 8
  • Use [`serializeArray`](http://api.jquery.com/serializeArray/) then simply [change the names of the properties](https://stackoverflow.com/questions/8483425/change-property-name) to match what you want. – Heretic Monkey Jun 29 '17 at 21:22

1 Answers1

1

Create an empty object and then loop through your form to set the properties on that object.

post_data = { };

$("input, textarea, select", theForm).each(function(){
    var theName = $(this).attr('name');
    post_data['npf_' + theName] = $(this).val();
});
Brett
  • 579
  • 3
  • 10
  • For some reason, if i use `post_data['npf_' + theName] = $(this).val();` like you suggested it doesn't work, but if i use `post_data['npf_' + theName] = $('input[name='+theName+']', theForm).val()` it does. can you tell why? – Nori Jun 30 '17 at 06:22
  • Inside of the each loop `this` is bound to the current HTML element, if it works for getting the name of the element it should also be able to get the value. I suspect something else was wrong, but I can't tell what without seeing more of your code or the error you were getting. Here's an example showing it work: https://jsfiddle.net/jk8y0916/2/ – Brett Jun 30 '17 at 19:54