I have a form with a products table. Initially the table is empty and new products are dynamically inserted with a button press. When user presses the submit button, I would redirect him to a "preview.php" page. But first I need to build a custom JSON object in a function, make a POST request with this object and then redirect to "preview.php". Is that possible ? And what is the better way to perform this ?
Here's a sample of my files :
//------------
//invoice.php
//------------
<form id="newInvoice" action="preview.php">
<table>...</table>
<button type="submit">Preview</button>
</form>
//-----------
//invoice.js
//-----------
$('#newInvoice').submit(function() {
var data = [
"invoicenumber": code,
"client": {"firstname":"", "lastname":"", ...},
"products": [{...}, {...}, {...}], //multiple products
//building the rest of my data here
];
// I don't know what to do here.
// A call to $.post would send my data asynchronously but I want
// to send the data as I would do from invoice.php and be redirected
// to preview.php.
});
//------------
//preview.php
//------------
$data = json_decode($_POST['data']); // is this correct ?
//...
Thank you for your responses.
Why do you want to POST the data as a JSON object, when ultimately you want the $_POST data?
But if you're keen to do that, you can do so, using AJAX
. This is used only when you want to return to the client-side code, after executing some PHP(server-side) code.