0

It's been more than 2 hours trying to find an optimal way to display the result rendered by an ajax call back function , Let me explain what i exactly want to do to better understand ...

I have a button "send" , on click event I defined a function that sends a $category_id to another page , where then I grab all the recipients from the database and send for each an Email. Now the whole process is working fine , but after each loop :

(foreach ($recipients as $recipient))
{send_mail();
echo "email sent successfully to ....";} 

I'm returning an echo statement telling that the email was correctly sent to that recipient . The Javascript function is defined to append those echo results in a div , but instead of displaying every statement after getting rendered , it gathers them all and display them at once .

$.ajax({
                async: true,
                url: 'send_emails.php?category='+category,
                success: function(r){
                    $('#status').append(r); //this happens all at once
                                    }
                }); 

Is there a better idea to reach my goal ?

thanks in advance

2
  • I don't get what is your goal, do you want to send emails one by one? Or do you want to display the messages in different elements in html? Commented Nov 11, 2014 at 10:15
  • No I want to display the message (email sent successfully ...) in the html page every time an email is sent . Commented Nov 11, 2014 at 10:18

2 Answers 2

1

The Success event of an ajax called is triggered when the XHR status changes to 200 (successful). This only happens when the back-end is done processing.

What you need is to check is the XHR readyState attribute. Which is set to '3' during processing of the request. You can then send updates from your PHP script to the webpage.

Here is a good blog that explains how to do it

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

2 Comments

that's exactly what I wanted to do ! thanks a lot , you saved my day
I think this is not what I really wanted , that script diplays the message every 1 second or as you defined it , but I was looking for a way to display a message after every loop !!
0

I think the problem is that you should go ahead and tell the user that the email is successfuly sent in your ajax callback -> there you know if(!err) then your request was successfull -> output that your message has been successfuly sent.

That every message is displayed "at once" is due to the fact that they are put into the stack and are called "ammediatly" - your ajax call is async to that and the callback is fired when the mail is actually sent.

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.