I need to send an array
using Ajax to a script PHP.
Javascript:
$.ajax({
type: "POST",
url: "vendas_funcoes.php",
data: {"data": arrayItens},
success: function(msg){
console.log("ok");
}
});
I already tried to use te example below, but it doesn't work.
vendas_funcoes.php:
<?php
$data = stripslashes($_POST);
// usar foreach para ler o array
foreach($data as $d){
echo $d;
}
?>
How do I receive this array
im my PHP script to manipulate him ? Aparently the code below sends the array
empty.
Excuse me for possible grammar mistakes, i'm brazilian.
PHP reads your POST data into the $_POST
array, so you can retrieve your original array by reading $_POST['data']
Javascript:
$.ajax({
type: "POST",
url: "vendas_funcoes.php",
data: {"data": arrayItens},
success: function(msg){
console.log("ok");
}
});
PHP:
<?php
$data = $_POST['data'];
// usar foreach para ler o array
foreach($data as $d){
echo $d;
}
?>
Tip, if you do print_r(arr)
or var_dump(arr)
on your array, you can easily see the structure of your array, and find an efficient way of manipulating it.
Your $data
is an object. You need to use $data["data"]
to get the array.
Your actual $data
is what you send via POST {"data": arrayItens}
.
$_POST['data']
has your data because you are sending the key as data
in
data: {"data": arrayItens},
It's better to have some sanity checks and then process the data.
if(isset($_POST['data']) && !empty($_POST['data'])){
// business logic
}