user2810718 user2810718 - 2 months ago 13
Ajax Question

Ajax post multiple objects and Retrieve in PHP

I have a form and an array containing some data. I am trying to post both these objects to my php script. The code I am using to post the form and array is shown below:

var json_data = JSON.stringify(data_vendor); //array to be posted

$.ajax({
url: '/crm/inventory/add_purchase_order.php',
type: 'POST',
data: {data_vendor:json_data,form_data:$("#purchase_orderform").serialize()},
dataType: 'json',


In the PHP script I am able to decode the array using the following :

$vendor_codes = json_decode($_POST["data_vendor"],true);


The form contains several fields/inputs one of which is called "order_quantity" . I am trying to retrieve this value using:

$order_quantity = $_POST["order_quantity"];


The data read shows up as NULL.

(i) Is the method used correct for posting multiple objects/strings correct?
(ii) Is the method used to retrieve the form inputs correct?

Answer

Usually when you use serialize() that is all you send because it is a urlencoded string. Then the form control names are available as keys in $_POST

But you currently only have 2 keys available to $_POST ... $_POST["data_vendor"] and $_POST["form_data"]

$_POST["form_data"] is a urlencoded string which you did with serialize() so it also needs to be decoded now manually

Try

$formData = urldecode($_POST["form_data"]);
$order_quantity = $formData ['order_quantity'];

To validate this just do a dump of $_POST["form_data"] and you will see that it is a string...not array

Comments