1

I need some help with my jquery code as I have got a problem with output for each element from the PHP array when calling ajax function. I have stored the list of elements in the PHP array and I would like to output each element in the jquery loop using ajax but I am unable to do so.

When I try this:

var data = result.data.attachment;

for (var i = 1, len = data[i].length; i < len; i++) {
    alert(data.filename);
}

I have also tried this:

var data = result.data.attachment;

for (var i = 1, len = data[i].length; i < len; i++) {
    alert(data[i].filename);
}

Output for readDraft.php attachment:

Array
(
    [1] => Array
      (
         [is_attachment] => 1
         [filename] => draft_attachment.rar
         [attachment] =>
      )
)


Array
(
    [2] => Array
      (
         [is_attachment] => 1
         [filename] => draft_attachment - Copy.rar
         [attachment] =>
      )
)

Here is the full jquery code:

$(document).on('click','#openDraft', function(e) {

    $.ajax({
    url: 'readDraft.php',
    type: 'POST',
    data : {
        email_number: email_number
    },
    dataType: 'json',

    success: function(result) {
        console.log(result.data.attachment);            

        var data = result.data.attachment;

        for (var i = 1, len = data[i].length; i < len; i++) {
            alert(data.filename);
        }
    });
});

Here is the full code for readDraft.php:

<?php

$structure = imap_fetchstructure($draft, $email_number);
$overview = imap_fetch_overview($draft, $email_number);
$draft_from = $overview[0]->from;
$draft_to = $overview[0]->to;
$draft_subject = utf8_decode(imap_utf8($overview[0]->subject));
$draft_fulldate = $overview[0]->date;
$draft_date = convDate($draft_fulldate);
$draft_message = quoted_printable_decode(imap_fetchbody($draft, $email_number, 1.2));
$attachments = array();

if(isset($structure->parts) && count($structure->parts)) {

    for($i = 0; $i < count($structure->parts); $i++) {

        if($structure->parts[$i]->ifdparameters) {
            foreach($structure->parts[$i]->dparameters as $object) {
                if(strtolower($object->attribute) == 'filename') {
                    $attachments[$i]['is_attachment'] = true;
                    $attachments[$i]['filename'] = $object->value;
                }
            }
        }

        if($structure->parts[$i]->ifparameters) {
            foreach($structure->parts[$i]->parameters as $object) {
                if(strtolower($object->attribute) == 'name') {
                    $attachments[$i]['is_attachment'] = true;
                    $attachments[$i]['filename'] = $object->value;
                }
            }
        }

        if($attachments[$i]['is_attachment']) {
            $attachments[$i]['attachment'] = imap_fetchbody($connection, $message_number, $i+1);
            if($structure->parts[$i]->encoding == 3) { // 3 = BASE64
                $attachments[$i]['attachment'] = base64_decode($attachments[$i]['attachment']);
            }
            elseif($structure->parts[$i]->encoding == 4) { // 4 = QUOTED-PRINTABLE
                $attachments[$i]['attachment'] = quoted_printable_decode($attachments[$i]['attachment']);
            }
        }
    }
}

$data = array("receipt"=>$draft_to, "subject"=>$draft_subject, "encryption"=>$email_number_encrypt, "message"=>$draft_message, "attachment"=>$attachments);
$response = array("data"=>$data, "success"=>"successfully", "total_inbox"=>$total_inbox_unread, "total_spam"=>$total_spam_unread);
echo json_encode($response);
?>

Here is the console log:

1: {filename: "draft_attachment.rar"}
2: {filename: "draft_attachment - Copy.rar"}

What happens is when I'm calling the ajax function, there is no alert display so there is something wrong. What I'm expecting to do is when I am calling ajax function, I want to set the alert to display for each filename using the index value.

Can you please show me an example how I could output for each filename using the index value when I am using ajax function?

Thank you.

4
  • 1
    @T.J.Crowder There is no error as I have checked it. I have also checked on alert(result.data.attachment[1].filename); and alert(result.data.attachment[2].filename); so I get draft_attachment.rar and draft_attachment - Copy.rar as a return string. Commented Aug 12, 2019 at 22:05
  • @T.J.Crowder So how I can use the loop display the alert for the filename? Commented Aug 12, 2019 at 22:06
  • "Here is the console log:" There is no console.log in the quoted code. Commented Aug 12, 2019 at 22:38
  • @T.J.Crowder I have added console.log in the quoted code. Commented Aug 12, 2019 at 22:44

1 Answer 1

1

Two things:

  1. Array indexes start at 0, not 1; and

  2. It doesn't make sense to use data[i].length for len in for (var i = 1, len = data[i].length; i < len; i++) {

  3. alert(data.filename); accesses filename on data, not data[i].

You probably want:

success: function(result) {
    var data = result.data.attachment;

    for (var i = 0, len = data.length; i < len; i++) {
    // 0, not 1--^            ^
    // No [i] here ----------/
        alert(data[i].filename);
    // [i] here-- ^^^
    }
}

Or with a vaguely-modern JavaScript engine:

success: function(result) {
    result.data.attachment.forEach(function(entry) {
        alert(entry.filename);
    });
}

Or with an ES2015+ JavaScript engine:

success: function(result) {
    for (const entry of result.data.attachment) {
        alert(entry.filename);
    }
}

In a comment, you've said that when you output result.data.attachment, you see:

1: {filename: "draft_attachment.rar"}
2: {filename: "draft_attachment - Copy.rar"}

That tells us that what you have isn't an array, it's an object. Your best bet is to correct the PHP code so it gets serialized to a proper array. But if for any reason you can't do that, you can do this:

success: function(result) {
    var data = result.data.attachment;
    var i = 1;
    while (data[i]) {
        alert(data[i].filename);
        ++i;
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

,Crowder Thank you very much for this, I have tried the first one, no alert display. I have tried the second one, there is an error: result.data.attachment.forEach is not a function and the third one there is an error: result.data.attachment is not iterable.
@RobertJones - That tells us that result.data.attachment is not an array. Only debugging can tell you how to go forward from there.
Actually you are correct. I have checked console.log(result.data.attachment); and here is the answer: 1: {filename: "draft_attachment.rar"} 2: {filename: "draft_attachment - Copy.rar"}
@RobertJones - Added to the end of the answer. Sorry, I don't do enough PHP to be able to tell you how to update the PHP code so that what gets output is an array.

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.