简体   繁体   中英

Passing Array to PHP from Javascript

I'm trying to pass my JS array to PHP array and all of the solutions that I have found here is useless or I can integrate these solutions to my problem.

Javascript

$('#siparisButon').click(function(){
                 var splitListe = $('#siparis-block span').text();
                 splitListe = splitListe.split("- ");
                 splitListe = JSON.stringify(splitListe);
                 $.post("menu.php",{'siparisListe[]': splitListe});
                 // I have a div that shows the result of PHP function and it says undefined index.
                 $('#fonksiyon').show();
          })

PHP

function ekleme(){
          if($_POST['siparisListe']){
                 $liste = $_POST['siparisListe'];
                 echo $liste;
          }
   }

instead of this

$('#siparisButon').click(function(){
     var splitListe = $('#siparis-block span').text();
     splitListe = splitListe.split("- ");
     splitListe = JSON.stringify(splitListe);
     $.post("menu.php",{'siparisListe[]': splitListe});
     // I have a div that shows the result of PHP function and it says undefined index.
     $('#fonksiyon').show();
})

modify you code in to this

$('#siparisButon').click(function(){
     var splitListe = $('#siparis-block span').text();
     splitListe = splitListe.split("- ");

     var input_data = new FormData();
     $.each(splitListe,function(index,value){
         input_data.append("siparisListe["+index+"]",value)
     });
     $.ajax({
        url: "menu.php",
        data: input_data,
        type: "POST",
          success: function(data) {
            $("#passwordMatch").html(data);
        },
        error: function(data) {}
     })

     // I have a div that shows the result of PHP function and it says undefined index.
     $('#fonksiyon').show();
})

Remove the [] from the POST field name and pass it an array (jQuery will JSON encode it for you).

$('#siparisButon').click(function() {
     let splitListe = ($('#siparis-block span').text() || '').split('- ');

     if (splitListe) {
         $.post("menu.php", { siparisListe: splitListe });

         $('#fonksiyon').show();
     }
});

Then in your PHP to verify:

function ekleme() {
    if ($liste = $_POST['siparisListe']) {
         var_dump($liste);
    }

    echo 'No $liste array in POST.';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM