2

I'm getting an odd error and I'm not sure why it's happening. I'm trying to send multiple values to my ajax call which is resulting in undefined.

I tried to debug it and I realized that my PHP is getting a parse error with my json_encode. The reason seems to be with the passing of multiple values. Can anyone explain why is that so?

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

$files = glob("images/*.*");

for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
}

echo json_encode("array_of_images" => $files, "size_of_array" => sizeof($files));
?>

Update: Ajax Code

<script>
    $.ajax({    //create an ajax request to load_page.php
        type: "GET",
        url: "img.php",             
        dataType: "html",   //expect html to be returned                
        success: function(response){     
            alert(response.array_of_images);
            alert(response.size_of_array);
        },
        error:function (xhr, ajaxOptions, thrownError){
           // alert(thrownError);
        }
    });
</script>

3 Answers 3

4

The second value passed to json_encode should be options, not more data. You need to make your parameters into an array instead of passing it as 2 values:

 echo json_encode(array("array_of_images" => $files, "size_of_array" => sizeof($files)));
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but why do I still get an undefined on the following ajax response: success: function(response){ alert(response.array_of_images); alert(response.size_of_array); },
Try console.log(response) before you alert it to find out what exactly it contains.
Undefined in console.log as well. If I have only say json_encode($files) it works.
Response is undefined? You'd have to show your ajax code to see what's going on there.
Try changing your dataType to json.
2

Add header and json_encode receive as parameter an array so it would be like this:

header('Content-Type: application/json');
echo json_encode(["array_of_images" => $files, "size_of_array" => sizeof($files)]);

Comments

2

json_encode accepts array. So you must write it like

echo json_encode(array("array_of_images" => $files, "size_of_array" => sizeof($files)));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.