edgar.dueñas
Enviado por edgar.dueñas el Mié, 11/05/2016 - 10:47

Enviar array con Ajax a PHP script en su Java Script:

dataString = ??? ; // array?
var jsonString = JSON.stringify(dataString);
   $.ajax({
        type: "POST",
        url: "script.php",
        data: {data : jsonString}, 
        cache: false,         success: function(){
            alert("OK");
        }
    });


En su PHP:

 

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

  // here i would like use foreach:

  foreach($data as $d){
     echo $d;
  }
?>


Ejemplo real, implementado en el projecto PPMD: 

/**
         * Ajax for select multi project
         */
        $(".block-block-3 a.button").click(function(){
 
            var allVals = [];
            $('.allocate-all-cheked:checked').each(function() {
                allVals.push($(this).val());
            });
 
 
            if(allVals.length != 0){
 
            $(".block-block-3").css( "display", "none" );
            $("#messages").css( "display", "none" );
            //$(".block-browse-projects-block").fadeOut("slow");                
 
            var jsonString = JSON.stringify(allVals);
 
                $.ajax({
                    type: "POST",
                    url: '/allocation-multi',
                    data: {data : jsonString},
                    success: function(data) {
 
                        //console.log(data);
                        $("#block-views-browse-projects-block").hide().html(data).fadeIn("slow");
 
                    }
                });            
 
            } else {     
                if($( "#messages" ).length == 0){ 
                    $( "#zone-content" ).prepend( '<div id="messages" class="grid-12"><div class="messages error"><h2 class="element-invisible">Error message</h2>You must select at least 1 project.</div></div>' );
 
                } else {
                     $("#messages").css( "display", "block" );      
                }
                $(document).scrollTop(0);
            }
 
        });
</code>
<br>