1

I have a KnockoutJS observable array which is prepared at the client side:

var invoices = function(invoiced_article_number,invoiced_article_name){
        this.invoicedArticleNumber = invoiced_article_number;
        this.invoicedArticleName = invoiced_article_name;
    };

Array is initialized on page load:

this.selectedInvoices = ko.observableArray();

And, On a click of a button certain elements are pushed in the array:

self.selectedInvoices.push(new invoices(self.selectedArticle().articleNumber,self.selectedArticle().articleName));

I want to pass this observable array to PHP through a Ajax post request to insert the data in MySQL. I have tried converting it to java script object using following code but i keep getting null in PHP.

var data = ko.toJS({"data":self.selectedInvoices});

Ajax Request:

$.ajax({
                url: "URL.php",
                type: "post",
                data: {invoiceData: data},
                cache: false,
                success: function(returnedData) {}
            });

PHP Code:

$invoice_data = trim($_POST['invoiceData']);

1 Answer 1

2

You need to use ko.toJSON to serialise your view-model into something which can be sent to PHP. Try:

var data = ko.toJSON({"data":self.selectedInvoices});

This will send a string representing a serialised state of your view-model to PHP. You can then deserialise it in PHP with:

$invoice_data = json_decode(trim($_POST['invoiceData']));
Sign up to request clarification or add additional context in comments.

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.