lorrainemutheu lorrainemutheu - 1 year ago 126
Javascript Question

AJAX sending array data as JSON object

I have a form and i wanted specific elements of the form which I got and stored the values in an array.

var that = $(this),
url = that.attr('action'),
type = that.attr('method'),

data = {};

var item_name = miniform.elements['itemId'].value;
var quantity = miniform.elements['quantityId'].value;
var amount = miniform.elements['amountId'].value;
var total = amount * quantity;
var cart = ["Item: ",item_name,"Quantity: ",quantity,"Amount: ",amount,"Total: ",total];


I would then like to convert this array into a JSON object and send it to a php file through ajax but its not working. Here is my ajax code:

$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data: JSON.stringify(cart),
success: function(){
console.log('Message Sent');
}
});


What could be the problem??

Answer Source

I found a solution to my problem and I combined some your responses to find the answer.

$('#miniform').on('submit',function(){  
    var that = $(this),
    url = that.attr('action'),
    type = that.attr('method'),

    data = {};
    var cart = {};

    cart.item_name = miniform.elements['itemId'].value;
    cart.quantity = miniform.elements['quantityId'].value;
    cart.amount = miniform.elements['amountId'].value;
    cart.total = cart.amount * cart.quantity;

    var jsonString = JSON.stringify(cart);

   $.ajax({
    url: url,
    type: type,
    data:{data:jsonString},
    success: function(){
        console.log('Email Sent');
     },
     error: function(error){
     throw new Error('Did not work');
      }
    });
 return false;
 });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download