Reputation: 7510
Im pretty new with javascript, so im not sure how I would do this. But basically I want to add a for loop in the ajax data:
call, instead of list each item manually.
jQuery(document).ready(function()
{
var $payment = {
card: 'ajax-card',
month: 'ajax-month',
year: 'ajax-year',
cvv: 'ajax-cvv',
zip: 'ajax-zip',
phone: 'ajax-phone'
};
jQuery.each( $payment, function($key, $val)
{
jQuery('.'+$val).attr({ id: $val });
});
jQuery('#pay-bill form input[type=submit]').click(function()
{
jQuery.ajax(
{
type: "POST",
url: "<?php echo get_bloginfo('template_directory').'/cnotethegr8/functions/braintree.php'; ?>",
dataType: "json",
data:
{
card: jQuery('#'+$card+' input').val(),
month: jQuery('#'+$month+' input').val(),
year: jQuery('#'+$year+' input').val(),
cvv: jQuery('#'+$cvv+' input').val(),
zip: jQuery('#'+$zip+' input').val(),
phone: jQuery('#'+$phone+' input').val()
},
success: function(data)
{
if (data)
{
alert(data.msg);
}
}
});
return false;
});
});
Upvotes: 0
Views: 2661
Reputation: 18572
If you want an each function that can iterate with key->value pairs, checkout underscore.js: http://documentcloud.github.com/underscore/#each
_.each({key:'value',key2:'value2'},function(value,key){
// access the key->value during each iteration
});
Upvotes: 0
Reputation: 227200
Make a variable before calling $.ajax
, and make a loop to set the values.
var postData = {};
$.each($payment, function(k, v){
//postData[k] = $('#'+v+' input').val();
postData[k] = $('.'+v+' input').val();
});
$.ajax({
type: 'POST',
data: postData,
// ...
});
P.S. You don't need the loop you have (setting $('.'+$val).attr({ id: $val });
), you can just do $('.'+v+' input').val();
(inside a loop).
Upvotes: 1
Reputation: 348972
Replace the code after var $payment = {...}
by the code below. I have adjusted the loop where you're assigning IDs to the elements.
var data = {};
jQuery.each( $payment, function($key, $val)
{
var $element = jQuery('.'+$val);
$element.attr({ id: $val }); //<-- This line can be removed, depending on the
// circumstances
data[$key] = jQuery('input', $element).val();
});
jQuery('#pay-bill form input[type=submit]').click(function(){
jQuery.ajax(
{
type: "POST",
url: "<?php echo get_bloginfo('template_directory').'/cnotethegr8/functions/braintree.php'; ?>",
dataType: "json",
data: data,
success: function(data)
{
if (data)
{
alert(data.msg);
}
}
});
return false;
});
Upvotes: 2
Reputation: 1441
If the values you want to pass in are in a form you can use $('#myForm').serialize()
Upvotes: 2