1

I am trying to send multiple data arrays in my ajax save function.

I can do each array individually like data:hardwarePayload and it will work. If I do {hardware: hardwarePayload, service:servicePayload} I get very weird JSON output. that looks like:

hardware=%5B%7B%22hardwareName%22%3A%221%22%2C%22hardwareQuantity%22%3A%22%22%2C%22hardwareBYOD%22%3A%22%22%7D%5D&service=%5B%7B%22serviceName%22%3A%223%22%2C%22serviceQuantity%22%3A%22%22%7D%5D

I really need two arrays one hardware and one service so I can grab each one individually.

My code looks like this..

self.save = function (form) {
    var hardwareModel = [];
    var serviceModel = [];
    ko.utils.arrayForEach(self.services(), function (service) {
        serviceModel.push(ko.toJS(service));
    });
    ko.utils.arrayForEach(self.hardwares(), function (hardware) {
        hardwareModel.push(ko.toJS(hardware));
    }); 
  //allModel.push({accountId: ko.toJS(account)});
    var hardwarePayload = JSON.stringify(hardwareModel);
    var servicePayload = JSON.stringify(serviceModel);
  //alert(JSON.stringify(serviceModel) +JSON.stringify(allModel));
    $.ajax({
        url: '/orders/add',
        type: 'post',
        data: {hardware: hardwarePayload, service:servicePayload}, //            data:hardwarePayload,
        contentType: 'application/json',
        success: function (result) {
            alert(result);
        }
    });
};

2 Answers 2

1

You should try this

var hardwarePayload = hardwareModel;
var servicePayload = serviceModel;

var postData = {'hardware': hardwarePayload, 'service':servicePayload};

var postData = JSON.stringify(postData);

alert(postData);

$.ajax({
    url: '/orders/add',
    type: 'post',
    data: postData,
    contentType: 'application/json',
    success: function (result) {
        alert(result);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

I think you'll be better off if you do NOT stringify your data:

$.ajax({
    url: '/orders/add',
    type: 'post',
    data: {hardware: hardwareModel, service:serviceModel}, //            data:hardwarePayload,
    contentType: 'application/json',
    success: function (result) {
        alert(result);
    }
});

(Note that I'm using the not stringified hardwareModel and serviceModel)

This way you can have jQuery handle the (json) data for the request.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.