I have code working to pass JSON objects from Jquery to PHP page.
The problem is with sending Cross-domain requests, If i try
dataType:'json'
in jquery, it gives me a xhttp error (the security) error which I understand.
I also understood after reading this post that JSONP only works for GET methods
This is how I am creating and using my object:
function order(id, name) {
return {
id: id,
name: name
}
}
var orders= [];
orders.push(order("123", "Lamb Kebab"), product("234", "Chicken"));
var jsonOrders = $.toJSON(orders);
$.post(
"process.php",
{orders: jsonOrders },
function(data){
$("#result").html(data);
}
);
What is the solution for me to pass a JSON object cross domain? if that is not possible, what is an alternate solution ?
Please advise
Thanks
Edit:
Jquery code
function product(code, type) {
return {
code: code,
type: type
}
}
var products = [];
products.push(product("333", "Product one"), product("444", "Second product"));
var jsonProducts = $.toJSON(products);
$.ajax({
type: "GET",
url: "http://page.tld/foo.php",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
data:JSON.stringify({products: jsonProducts}),
error: function (msg) {
//alert("error");
console.log("Error here" +msg);
},
success: function (msg) {
console.log("Success"+msg);
}
});
**
The error on PHP end is: Invalid argument supplied for foreach() in ....
**
PHP Code (simplified version)
<?php header("Content-type: application/json; charset=utf-8");
require_once('json.php');
if (isset($_GET['products'])) {
$products = json_decode($_GET["products"],"true");
foreach ($products as $product){
echo $_GET['callback'] . '(' .(json_encode($product["type"])). ')';
}
}
else
{
echo $_GET['callback'] . '(' .(json_encode("not found")). ')';
}
?>
it is going into the block where it is able to find $_GET['products'], is it a parsing error on my part? i am sure it is an obvious mistake but im not able to spot it.
real sorry about that