3

I'm trying to pass a javascript array to PHP file like this:

Code in JS file:

let directories =JSON.stringify(["John", "Sara", "Max"]);   
$.post('../test.php', {directories: directories});

And inside the PHP file:

$directories = json_decode($_POST['directories']);

But each time I get an empty array! How can I fix this?

Update:

PHP

<?php
function getDirContents($directories, &$results = array()){

    $length = count($directories);
    for ($i = 0; $i < $length; $i++) {

    $files = array_diff(scandir($directories[$i]), array('..', '.'));;
    foreach($files as $key => $value){
        $path = $directories[$i].DIRECTORY_SEPARATOR.$value;
        if(is_dir($path)) {
          getDirContents($path, $results);
        } else {
          $directory_path = basename($_SERVER['REQUEST_URI']);
          $results[] =  'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
        }
    }

    }

    return $results;
}

$directories = json_decode($_POST['directories']);
print_r($_POST['directories'] 



echo json_encode(getDirContents($directories));

Javascript

$(document).ready( function() {


    let directories =JSON.stringify(["recognition final tests", "4789"]);   
    $.post('../test.php', {directories: directories});

        $.ajax({
            type: 'POST',
            url: '../test.php',
            data: 'id=testdata',
            dataType: 'json',
            cache: false,
            success: function(result) {
            console.log(result);
            preload(result);

            },
        });
});




function preload(arr){
arr = arr.map(x => encodeURI(x));   
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global.Preload = factory());
}(this, (function () { 'use strict';

    function preloadOne(url, done) {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onprogress = event => {
            if (!event.lengthComputable) return false
            let item = this.getItemByUrl(event.target.responseURL);
            item.completion = parseInt((event.loaded / event.total) * 100);
            item.downloaded = event.loaded;
            item.total = event.total;
            this.updateProgressBar(item);
        };
        xhr.onload = event => {
            let type = event.target.response.type;
            let blob = new Blob([event.target.response], { type: type });
            let url = URL.createObjectURL(blob);
            let responseURL = event.target.responseURL;
            let item = this.getItemByUrl(responseURL);
            item.blobUrl = url;
            item.fileName = responseURL.substring(responseURL.lastIndexOf('/') + 1);
            item.type = type;
            item.size = blob.size;
            done(item);
        };

        xhr.onerror = event => {
        console.log('an error happed herrt')
    };

        xhr.send();
    }

    function updateProgressBar(item) {
        var sumCompletion = 0;
        var maxCompletion = this.status.length * 100;

        for (var itemStatus of this.status) {
            if (itemStatus.completion) {
                sumCompletion += itemStatus.completion;
            }
        }
        var totalCompletion = parseInt((sumCompletion / maxCompletion) * 100);

        if (!isNaN(totalCompletion)) {
            this.onprogress({
                progress: totalCompletion,
                item: item
            });
        }
    }

    function getItemByUrl(rawUrl) {
        for (var item of this.status) {
            if (item.url == rawUrl) return item
        }
    }

    function fetch(list) {  
        return new Promise((resolve, reject) => {
            this.loaded = list.length;
            for (let item of list) {
                this.status.push({ url: item });
                this.preloadOne(item, item => {
                    this.onfetched(item);
                    this.loaded--;
                    if (this.loaded == 0) {
                        this.oncomplete(this.status);
                        resolve(this.status);
                    }
                });
            }
        })
    }

    function Preload() {
        return {
            status: [],
            loaded: false,
            onprogress: () => {},
            oncomplete: () => {},
            onfetched: () => {},
            fetch,
            updateProgressBar,
            preloadOne,
            getItemByUrl
        }
    }

    return Preload;

})));


const preload = Preload();

preload.fetch(arr).then(items => {
  // use either a promise or 'oncomplete'
  console.log(items);
});

preload.oncomplete = items => {
  console.log(items);
}

preload.onprogress = event => {
  console.log(event.progress + '%');
}

preload.onfetched = item => {
  console.log(item);
}

};

UPDATE 2:

JS

$(document).ready( function() {


    let directories =JSON.stringify(["recognition final tests", "4789"]);   
    //$.post('../test.php', {directories: directories});

        $.ajax({
            type: 'POST',
            url: '../test.php',
            data: {directories: directories , id : "testdata"} ,
            dataType: 'json',
            cache: false,
            success: function(result) {
            console.log(result);
            preload(result);

            },
        });
});

PHP

$directories = json_decode($_POST['directories']);
print_r($_POST['directories'] 

Still I get jquery-3.4.1.min.js:2 POST https://reed123.000webhostapp.com/test.php 500

8
  • What shows with print_r($_POST['directories'] Commented Mar 31, 2020 at 19:13
  • Use the json_last_error function in order to get the idea that what may be wrong with the json Commented Mar 31, 2020 at 19:14
  • Your php code is right. please tell us what do you see on your console Commented Mar 31, 2020 at 19:14
  • I get an empty array in console... I update the question and add the full code... Commented Mar 31, 2020 at 19:22
  • Try to print $_POST Commented Mar 31, 2020 at 19:31

1 Answer 1

1

Try print your response with print_r($_POST)

You will see you don't send {directories: directories} in your request's body and in your php you try get data: $_POST['directories'] so you get a response with server error (500 status)

Updated:

And it's better if you send just one request and send all data with that

    $.ajax({
        type: 'POST',
        url: '../test.php',
        data:  {directories: directories , id : "testdata"},
        dataType: 'json',
        cache: false,
        success: function(result) {
            console.log(result);
            preload(result);

        },
    });
});

and in your php code:

print_r($_POST['directories']) ;

You haven't closed the prantese :)

Sign up to request clarification or add additional context in comments.

10 Comments

Thanks for the answer...plus one but I need the second request too... How can I use them at the same time?
both your requests try to send to a same address. so you can send a request with a data like {directories: directories , id : "testdata"}
Please have a look at update 2... I can't make your solution work...
I updated my anwer. if you dont get your answer please make comment. I 'll update my answer again. Thank you
print_r($_POST['directories'] این رو میگم. پرانتز رو نبستی خب
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.