1

I'm trying to send emails to multiple persons, once emails send successfully then i'm appending a message through ajax response. Below code is working fine

Php

if(!empty($sendEmails)){
    $sendCount = 0;
    foreach($sendEmails  as $mail){
        $sent = $this->sendEmail('', $mail, $subject, $data);
        if($sent != 'Message Sent'){
        $response['send_error'][] = 'There is an error with ['.$mail.']';
        }else{
            $sendCount++;
        } 
    }
}
$response['success'] = 'Email has been sent successfully to '. $sendCount. ' person(s).'; 

Ajax

$.ajax({
    type:'POST',
    url:'post.php',
    data:formData,
    dataType:"json",
    success:function(response){
        $(".sndMail").remove();
        if(response.success){
            $(".sendResponse").prepend('<div class="alert alert-success sndMail"> <strong>Alert! </strong> '+response.success+'</div>');
        }
        if(response.send_error){
            for(f=0; f<response.send_error.length; f++) {
                //alert(response.fileErr[f]);
                $(".sendResponse").prepend('<div class="alert alert-danger sndMail"> <strong>Alert! </strong> '+response.send_error[f]+'</div>');
            }
        }
        if(response.error){
            for(f=0; f<response.error.length; f++) {
                //alert(response.fileErr[f]);
                $(".sendResponse").prepend('<div class="alert alert-danger sndMail"> <strong>Alert! </strong> '+response.error[f]+'</div>');
            }
        }       
    }
});

But i want to make the user view more good by adding each email send response. I want to append each response message like Response: Email is send to php_dev@gmai.com while processing and once all emails are sent then i will show success message which is already working.

So can anyone guide me regarding this that is this possible with ajax or not? i would like to appreciate if someone guide me. I searched it but i didn't found the solution.

Ayaz Ali Shah
  • 3,453
  • 9
  • 36
  • 68

2 Answers2

1

What you want is not possible with one single ajax call, but it can be done with multiple calls.

The idea is to use one ajax call to run the process and a second call to periodically poll the progress.

Check this SO question : Multiple Response AJAX request

Community
  • 1
  • 1
Gabriel Glenn
  • 1,174
  • 1
  • 13
  • 30
0

Yes you can. Try some thing like this:

$response = array();
foreach($sendEmails  as $mail){
if(mail())    // success
{
   $response[$mail] = '';  // your message
}
else          // fail
{
    $response[$mail] = '';  // your message
}
}

echo json_encode($response);

ajax:

success:function(response)
{
    var data = JSON.parse(response);
    // data contains the success or failure message for each email id. 
    // Show the status by wrapping the each email in <li> or <div> by using $.each loop
}
Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59