Pass array by Ajax and receive in PHP script

Asked

Viewed 91 times

0

I need to pass a Array for Ajax to read it in a script PHP.

Javascript code:

$.ajax({
    type: "POST",
    url: "vendas_funcoes.php",
    data: arrayItens,
    success: function(msg){
        console.log("ok");
    }
});

I’ve tried using the following example I saw, but it didn’t work. I’ve also tried using stringify and did not roll.

sales_functions.php:

<?php
    $data = json_decode(stripslashes($_POST['data']));

    // usar foreach para ler o array
    foreach($data as $d){
        echo $d;
    }
?>

How do I get this Array in the script PHP so I can manipulate it ? The above code apparently does not enter the foreach that I have in my script .php.

  • 1

    Would not be data: {"data": arrayItens} in Jquery?

  • 1

    To take the value in this way "$_POST['data']" put the "date" of the jquery in the following form: { data : arrayItens }, that is to say if you define "date" in the php post you take "date", if you wanted another name you can do date : { test: arrayItens } and then in php you’ll have to put $_POST['test']

  • Thank you, @Andersoncarloswoss

  • This way it will enter my 'foreach' ? How can I test to see if I’m getting the same array ?

1 answer

1

You don’t need to give one json_decode in his POST, the default of contentType ajax is application/x-www-form-urlencoded, that will make the requisition as if it were a form HTML.

In this way:

<?php
    $data = stripslashes($_POST);

    foreach($data as $d){
        echo $d;
    }
?>
  • Apparently the array comes empty this way, as it does not enter the foreach

Browser other questions tagged

You are not signed in. Login or sign up in order to post.