0

I returned from PHP array with two elements through JSON , but the " data.length " does not work . How can I get the size of the array in JS ? If I turn it to one of the elements in the array ( data.name.length ) returns the number of elements in STRING .

    for ($i = 0; $i < $result; $i++) {


        $img_name ['id'] = $get_img_id[$i]['id'];

        $img_name ['name'] = $get_img_id[$i]['id'];


    }

     return json_encode($img_name);

js:

$.ajax({
        url: "upimage",
        dataType: "json",
        type: "POST",
        data: formData,
       success: function(data) { 

        //$.each(data, function(i) {



          $("#all_files").val(data + " ,");

          for ( var i = 0, l = data.length; i < l; i++ ) {



             $(".returns_img").append("<div class='img_ls' id='" + i + "'><img src='/img/" + data['name'][i] + "'><button class='dell_img' id='"+ i +"'>מחק</button><br><button class='add_img' id='"+ i +"'>הוסף לכתבה</button></div>"); 

            }




      }, 

        cache: false,
        contentType: false,
        processData: false
    });

2 Answers 2

2

You are returning not array, but a single object from php code, to get what you need try this:

        $result = array();
        for ($i = 0; $i < $result; $i++) {
            $img_name ['id'] = $get_img_id[$i]['id'];
            $img_name ['name'] = $get_img_id[$i]['id'];
            $result[] = $img_name;
        }
        return json_encode($result);
Sign up to request clarification or add additional context in comments.

2 Comments

In Js how I came up to the array ? Thank you
@user3581731 in js your loop is correct, but to get access to each item name just use data[i].name (not data['name'][i]). BTW learn how to debug JS, its very useful.
0

Use like this,

var arr = [], len;

for(key in data) {
    arr.push(key);
}

len = arr.length;
console.log(len)

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.