0

I have a PHP file sending data to an external jQuery, it's a dropzone where upload multiple images (each image has different informations inside). I've built a foreach PHP loop which generates arrays (foreach image) and each of those should perform the same functions in that jQuery (delete, update, etc).

How can I send and process the loop from PHP to jQuery?

I'm trying to use the .each method but I guess I'm wronging, because the loop generated shows the same image (with same informations) repeated for the number of arrays!

My PHP

<?php
        $args = array(
            'order'             => 'ASC',
            'orderby'           => 'post_date',
            'post_type'         => 'attachment',
            'author'            => $current_user->ID,
            'meta_key'          => 'is_portfolio',
            'meta_value'        => '1',
            'numberposts'       => -1,
        );
        $attachments = get_posts($args);
        if ($attachments) 
            {
               foreach ($attachments as $attachment) 
                {
                    $url = $attachment->guid;
                    $imggg = $attachment->post_mime_type; 
                    $url = wp_get_attachment_url($attachment->ID); 
                    $thumb = wp_get_attachment_image_src($attachment->ID, 'thumbportfolio');
                    ?>
                    //here is my jQuery array generated for X number of attachments uploaded
                    var mockFile = { 
                        name: "<?php echo $attachment->post_title ?>", 
                        size: 12345, 
                        serverId: '<?php echo $attachment->ID ?>',
                        post_title : "<?php echo $attachment->post_title ?>",
                        post_desc : "<?php echo $attachment->post_content ?>",
                        thumb : "<?php echo $thumb[0] ?>"
                    };
                    <?php           
                }
            } ?>

My jQuery where .each of mockFile ( should initiate a Dropzone Thumb with relative infos and other stuff).

$.each( mockFile, function( index, value ){
        //variables accessing array keys
        var mockThumb = mockFile['thumb'];
        var mockID = mockFile['serverId'];
        var mockTitle = mockFile['post_title'];
        var mockDesc = mockFile['post_desc'];
        //initiate dropzone
        myDropzone.options.addedfile.call(myDropzone, mockFile);
        myDropzone.options.thumbnail.call(myDropzone, mockFile, mockThumb  );
        //Other stuff
        jQuery( "#itemtitle" ).prop( "id","itemtitle-"+mockID);
        jQuery( "#itemtitle-"+mockID ).prop( "value", mockTitle);
        jQuery( "#itemdescription" ).prop( "id","itemdescription-"+mockID );
        jQuery( "#itemdescription-"+mockID ).prop( "value", mockDesc );
        jQuery( "#updateinformations" ).prop( "id","updateinformations-"+mockID );
        change_ids(mockID);
        console.log(mockFile);
    });

Result with this? The same image repeated.

Can you help me?

middlelady
  • 573
  • 2
  • 13
  • 36
  • 1
    You don't pass 'loops' of arrays. A loop is a piece of logic to execute. PHP execution and JavaScript execution are separate processes, and you can't 'inject' a PHP loop into JavaScript. You can however pass a piece of data in various ways, and once you've got it in a JavaScript array you can iterate over it in the usual JavaScript way. So regarging the data part, this question is a duplicate. Regarding the loop part, you misunderstood the concept of loops and the context they run in. – GolezTrol Jul 23 '16 at 12:12
  • 1
    @GolezTrol thanks for your answer, it's just matter of explaining it. Yes I misunderstood the thing, I'm a newbie and I will study it for sure now that I know it. People don't get enlightened from the sky and not all have an IT engineering degree... Somebody approaches the code as amateur and get involved deeper, later on. So I thought this was the place where to be to learn more but maybe there is only a bunch of selfish people jealous of their little knowledge. Have a great. – middlelady Jul 23 '16 at 12:22
  • Don't take it too hard, and please don't be that harsh. There are millions of questions on StackOverflow, answered by thousands of volunteers that are not possessive at all of their knowledge. But if they think a question is too similar to another they will close it, because it's usually better to have one canonical, more elaborate answer than a bunch of half-hearted duplicates. It's nothing personal, it's just an attempt to make StackOverflow the best resource for you and everybody after you. – GolezTrol Jul 24 '16 at 10:42
  • @GolezTrol I'm nothing against you neither. Thanks for explaining. – middlelady Jul 25 '16 at 09:07

2 Answers2

2

You need to build up the mockFile JS variable gradually. Currently your loop is probably echoing multiple variables called mockFile into the output page (try View Source when the page is loaded). Like any program, if you re-declare the variable multiple times, only the last version will get used. Remember that PHP is just building up a string of output to be sent to the browser and interpreted as HTML/Javascript. There's no instrinsic interaction between them - PHP is just a mechanism for dynamically adjusting the content that is output to the browser. The browser doesn't know (or care) if the content was from a static .html file or pieced together by a PHP script.

So anyway, try it something like this:

    $attachments = get_posts($args);
    //next, we declare a JS array "mockFile" to be output to the browser
    ?>
    var mockFile = [
    <?php
    if ($attachments) 
    {
           $count = 0;
           foreach ($attachments as $attachment) 
           {
                $url = $attachment->guid;
                $imggg = $attachment->post_mime_type; 
                $url = wp_get_attachment_url($attachment->ID); 
                $thumb = wp_get_attachment_image_src($attachment->ID, 'thumbportfolio');
                if ($count > 0) echo "," //put comma in front of previous array entry, if there is one
                ?>
                //here is my jQuery array generated for X number of attachments uploaded
                { 
                    name: "<?php echo $attachment->post_title ?>", 
                    size: 12345, 
                    serverId: '<?php echo $attachment->ID ?>',
                    post_title : "<?php echo $attachment->post_title ?>",
                    post_desc : "<?php echo $attachment->post_content ?>",
                    thumb : "<?php echo $thumb[0] ?>"
                }
                <?php
                $count++;
           }
    } ?>
    ];
    <?php
    //just above this comment is the end of the JS array. Even if there are no elements, the array will still be declared and be valid;
    ?>
ADyson
  • 57,178
  • 14
  • 51
  • 63
  • Thank you dude! I really appreciate your solution. I've actually read many articles and a lot of jQuery documentation. I've found the solution using `arraypush` as I'm going to answer now below. My solution might be not really refined but does the job! I will try your answer too! Have a great day. – middlelady Jul 24 '16 at 08:59
  • @XiLab no problem, happy to help. Saw your solution below, good attempt actually. I think my version just removes the step of doing array.push, by building up the array definition directly, but otherwise it's pretty similar. – ADyson Jul 25 '16 at 09:55
0

Thank to ADyson for his precious help, I will try his solution. I've actually solved later on searching and studying some jQuery documentation. Assuming I have 2 files which interact each other:

  • main.php
  • myscript.js

The first can send multiple variables with the same name through an object (this was my question basically). So I've declared an array before the loop and used .push for each $attachment to store everything in that place like (main.php):

var myarray = [];
<?php
        $args = array(
            'order'             => 'ASC',
            'orderby'           => 'post_date',
            'post_type'         => 'attachment',
            'author'            => $current_user->ID,
            'meta_key'          => 'is_portfolio',
            'meta_value'        => '1',
            'numberposts'       => -1,
        );
        $attachments = get_posts($args);
        if ($attachments) 
            {
               foreach ($attachments as $attachment) 
                {
                    $url = $attachment->guid;
                    $imggg = $attachment->post_mime_type; 
                    $url = wp_get_attachment_url($attachment->ID); 
                    $thumb = wp_get_attachment_image_src($attachment->ID, 'thumbportfolio');
                    ?>
                    var mockFile = { 
                        name: "<?php echo $attachment->post_title ?>", 
                        size: 12345, 
                        serverId: '<?php echo $attachment->ID ?>',
                        post_title : "<?php echo $attachment->post_title ?>",
                        post_desc : "<?php echo $attachment->post_content ?>",
                        thumb : "<?php echo $thumb[0] ?>"
                    };
                    myarray.push(mockFile);
                    <?php           
                }
            } ?>

Console.log(myrray) shows multidimensional array like

[{attachment1},{attachment2},{attachment3}]

So I've created my .each jQuery function like (myscript.js)

$.each( myarray, function( i, el ){
        //blablabla accessing keys and values.
    });

Once again, I don't know if this is the best way to accomplish it but works fine and my page loads faster than before. Maybe I should learn more about json enconding to exchange informations but for now I'm proud of myself.

middlelady
  • 573
  • 2
  • 13
  • 36