You're looking at AJAX. You'd write a PHP "server" that sits on the site and accepts some sort of input (like a signal that says "send the mail"), actually sends the mail, and, after each one, gives a report either in Plain Text or, perhaps more likely as a JSON object. On the page/screen, JavaScript is present (it sent the signal, and waits for a response from the request; the callback function for the response updates part of the HTML DOM (a div, etc.) with the report (Plain Text or JSON).

http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php
https://www.tutorialspoint.com/php/php_and_ajax.htm

    minifairy;11060425 wrote:

    What I'm wanting to do is send emails and report to the screen after each email is sent.

    If you want to know when each mail gets sent, you need your php script that sends mail to communicate the sending of each mail somehow.

    minifairy;11060425 wrote:

    I have the emails in a mysql database and I have no trouble pulling them out and sending the email using php.

    Do you run this PHP script from the command line? Is it a cron job? Or do you request it in a browser? Does your PHP script send many emails? Or just one? If it just sends one, you could set up some AJAX requests to call it repeatedly and report that the emails are getting sent.

    minifairy;11060425 wrote:

    But reporting to the screen only happens at the end of the list when everything is done.

    You could run into problems if you are accessing your script in a browser and the script runs for a long time -- PHP has certain time limits for how long scripts may execute and it might get interrupted. If that doesn't concern you, you might consider calling [man]flush[/man] in your script right after you echo a message. Read the documentation link for more info. Basically, flush tries to force any output you've echoed all the way to the user's browser.

    minifairy;11060425 wrote:

    As I understand it the only way to report to the screen after each email is sent is with java script. I have a sort of idea how to do it but its very gray and hazy so would greatly appreciate if someone could clear it up.

    If you have one script that sends a lot of emails, you could try flush as I've mentioned OR you could alter your send_mail.php script so that it writes its progress to some other db table (or to a text file or something) and then write another file, progress.php, which checks that db table or file and reports what is going on. You could then set up either some AJAX to poll progress.php or even equpt your progress.php script with a meta refresh tag so that it refreshes every 5 seconds or something.

      sneakyimp;11060461 wrote:

      you could alter your send_mail.php script so that it writes its progress to some other db table (or to a text file or something) and then write another file, progress.php, which checks that db table or file and reports what is going on. You could then set up either some AJAX to poll progress.php or even equpt your progress.php script with a meta refresh tag so that it refreshes every 5 seconds or something.

      A thing to keep in mind here is that if send_mail.php and progress.php are (a) part of the same session, and (b) using the default file-based session infrastructure, then you want the send_mail.php script to avoid having the session open while it's working; otherwise, it will have a lock on the session file and progress.php will hang waiting for the lock to be released.

        Dalecosp This is the angle I was looking for but I'm not quite sure how to 'automate' the ajax response. I'm pretty new to ajax and don't really understand it well.

        I've used it for things like what I saw in your links where there is a form and you click a button and the ajax response goes to the <div> provided for it on the screen. If I wanted to click a button and send one email then click another button and send an email I could do this no problem. But the idea is more one of I click one button and it sends 50 emails but reports to the screen after each one is sent. That I don't know how to do.

        Thank you for your response Got anymore links that will go a bit deeper like how to trigger the ajax from the php without the user clicking something again?

        I've looked for some ajax example that will do something along those lines but haven't found one. I can easily echo each email address as 'mail sent to xxx@done.com' as I go but it doesn't display until its done which leaves the person sitting there looking at a pretty much blank screen wondering if it has died. So I wanted it to send the message to the user after each email.

          SneakyImp I'm running this from a browser.

          The php program that sends the email echo's that the mail is sent after each mail is sent. The problem is that it doesn't get to the screen until they are all sent then you get a big list to the screen.

          it sends one at a time along with some other info from the DB in the email as sort of mail merge type thing, but in total it can send quite a few like 10 or 50 or possibly 100 emails so waiting until they are all sent to display to the screen is the problem.

          I was thinking AJAX or something similar but have no idea how to feed the ajax from the script. I've used it with a click the button display this info but that would require the user to click a button for each email and that isn't what I'm wanting to do here. I haven't tried flush I'll have a look at that and see if it does the trick. Thanks for your response.

            Weedpacket I think I get what you are saying. The whole thing is running in a session and writing a new db table sounds sort of like a lot of extra. Would it work to update a session variable and have it display in say a little iframe that refreshes?

              minifairy;11060565 wrote:

              Dalecosp This is the angle I was looking for but I'm not quite sure how to 'automate' the ajax response. I'm pretty new to ajax and don't really understand it well.

              I've used it for things like what I saw in your links where there is a form and you click a button and the ajax response goes to the <div> provided for it on the screen. If I wanted to click a button and send one email then click another button and send an email I could do this no problem. But the idea is more one of I click one button and it sends 50 emails but reports to the screen after each one is sent. That I don't know how to do.

              Thank you for your response Got anymore links that will go a bit deeper like how to trigger the ajax from the php without the user clicking something again?

              If you want "one click, many actions", you're going to need to do that in JavaScript. There are probably several ways to skin that cat; if it were me I'd look into either setInterval() or setTimeout() . This is VERY VERY rough, but is intended to get you thinking about it:

              //JavaScript, but only pseudo-code (this doesn't do anything)
              
              function ajaxSendMail() {
              
              var thiss, that, the_other, jax;
              
              //do the Ajax stuff to tell my server to send a mail.
              
              //handle the response and update the web page/DOM
              
              }
              
              function SendLotsOfMail() {
              
              var i;
              
              for (i=0, i<50, i=i+1) {
                ajaxSendMail();
              }
              }

              In the HTML:

              <button id='mailsend' name='sendMail' onclick='SendLotsOfMail();return false;'>

                dalecosp Thanks I'll look through it that is what I'm looking for a place to start. I'm so bad with Java Script. I really need to spend some serious time with it but just haven't been able to find said time. Thanks alot for your help I'll let you know how it goes.

                  minifairy;11060569 wrote:

                  SneakyImp I'm running this from a browser.

                  The php program that sends the email echo's that the mail is sent after each mail is sent. The problem is that it doesn't get to the screen until they are all sent then you get a big list to the screen.

                  As I suggested, try putting a call to [man]flush[/man] after this echo statement.

                  minifairy;11060569 wrote:

                  I was thinking AJAX or something similar but have no idea how to feed the ajax from the script.

                  If your PHP script that sends mail is not going to be changed, your problem is not going to be fixed. If you want AJAX to repreatedly call a script that sends one email at a time, then you'll have to modify the mail-sending PHP script and come up with a Javascript loop that can loop and repeatedly call the one-mail-at-a-time script until all the emails get sent.

                    9 days later
                    dalecosp;11060573 wrote:

                    If you want "one click, many actions", you're going to need to do that in JavaScript. There are probably several ways to skin that cat;

                    dalecosp I'm not super familiar with either java script or ajax and am sort of in a hurry here. But I have come up with a plan that I think will work. Can you sort of tell me if I'm crazy or if this will do the trick. This application runs mostly in php and I'm most familiar with php so that is where I am doing most of the work. Here is what I've got so far.

                    I am pulling the info from the db and filling javascript arrays in php before sending it all to the browser. That is all working great. I can view the html source once it gets to the browser and the arrays are there all ready to go.

                    The plan I have was using a for each loop in the javascript to step through the arrays and send each member of the array back to php to send the mail and echo that it has sent xx@xx.com as it sends it to the php. Now comes my big question:
                    How do I send it to php and get it back while staying on the same page in the browser. I saw in another item here on the forum. Someone was calling php by

                    if (question){ window.location="SendInvitations.php"; }

                    I'm thinking I could do similar in a for each loop, however, I'm guessing

                    window.location{/AUOTE] is changing the page they are on totally. So could I do it in an iframe or similar? Or how would I call/invoke the php to send the mail while staying on the page I'm on? Or can I call a php function from javascript? Kinda stuck. All help is greatly appreciated.

                      I found a call to a php function from javascript on YouTube (https://www.youtube.com/watch?v=23WFRVmzFhY) but seem to have an issue. It doesn't wait for the function to be called. Here is the code where I defined the javascript function. At this point I have already filled the arrays but not done the for each loop yet.

                      #java script function to call php mail
                      			echo "function php_mail(etype, eml, fees){\n";
                      				echo "var result=\"".eletters($etype, $email, $fees)."\";";
                      				echo "alert(result);\n";
                      				echo "return(false);\n";
                      			echo "}\n";

                      here is the eletters function in php.

                      function eletters($etype,$email,$fees){
                      		$showname=cross_field("showinfo","id","showname","1",$sid);
                      		#show Dates
                      		$y=$cnfig[$sid.'shw_days'];
                      		for($x=1;$x<=$cnfig[$sid.'shw_days'];$x++){
                      			$day=explode('|',$cnfig[$sid.'shw_day'.$x]);
                      			if($x==($y))$sdates.=" and ";
                      			if($x==1){
                      				$sdates.= date("F jS, ", strtotime($day[0]));
                      			}elseif($x<$y){
                      				$sdates.= date("jS, ", strtotime($day[0]));
                      			}else{
                      				$sdates.= date("jS, Y", strtotime($day[0]));
                      			}
                      		}
                      		#basic email headers
                      		$headers="From: ".$cnfig['shop_email']."\r\n";
                      		$headers .= 'MIME-Version: 1.0' . "\r\n";
                      		$headers .= 'Content-type: text/html; charset=iso-8859-1' . " \r\n";
                      		$headers .= "Reply-to: ".$cnfig['shop_replyemail']."\r\n";
                      		$headers .= "Return-Receipt-To:".$cnfig['shop_replyemail']."\r\n";
                      		if($etype=='a'){#Approved Emails
                      			$subject="Congratulations! Your application for the ".$showname." has been approved";
                      			$bodya = "Hello ".cross_field("dealer","artid","fname","1",$row->artid).",<br>Congratulations! Your Application for the ".$showname." has been approved.<br>We are happy you will be joining us on ".$sdates;
                      			$bodya.="<br>".cross_field("textinfo","tid","infotxt","1",'cap')."<br>".$fees."<br>";
                      			if($cnfig[$sid.'shw_payopt']=='site'){
                      				$bodya.="If you have not yet paid, you can pay the balance of your booth fees online by going to this address <a href=\"http://".$cnfig['domain']."/".$cnfig['art_url']."?p=pbx".$sid."\">href=\"http://".$cnfig['domain']."/".$cnfig['art_url']."?p=pbx".$sid."</a><br><br>";
                      			}else{
                      				$bodya.="If you have not yet paid, please send your money order to: <br>".$cnfig[$sid.'shw_mail']."<br><br>";
                      			}
                      			$bodya.="If you have any questions, please don't hesitate to contact me, ".$cnfig['contact_person']."<br>".$cnfig['shop_replyemail']." Thanks again and see you soon.";
                      		}
                      		#mail ($email, $subject, $bodya, $headers);
                      		echo $email."<br>".$subject."<br>".$headers."<br>".$bodya."<br>";
                      		echo $email." has been sent";
                      	}

                      when I look at the page source running the whole thing here is what I see in the header where this java script is supposed to be.

                      <!-- Email Script bits -->
                      <script type="text/javascript">
                      var eml = []
                      var fees = []
                      eml[1]='marsha@nativeamericanartworks.com'
                      fees[1]='You signed up for the 10X10 Booth Total Fees $300.00<br>The balance is due by December 31st, 2016'
                      eml[2]='redironhorse.jbej12@gmail.com'
                      fees[2]='You signed up for the 10X10 Booth Total Fees $300.00<br>The balance is due by December 31st, 2016'
                      eml[3]='cgbordeaux@hotmail.com'
                      fees[3]='You signed up for the 10X10 Booth Total Fees $300.00<br>The balance is due by December 31st, 2016'
                      eml[4]='bettypadilladine505@gmail.com'
                      fees[4]='You signed up for the 10X10 Booth Total Fees $300.00<br>The balance is due by December 31st, 2016'
                      eml[5]='pclrivera@hotmail.com'
                      fees[5]='You signed up for the Youth with Adult Total Fees $0.00<br>The balance is due by December 31st, 2016'
                      eml[6]='manyhogansgrl@hotmail.com'
                      fees[6]='You signed up for the 10X10 Booth Total Fees $300.00<br>The balance is due by December 31st, 2016'
                      function php_mail(etype, eml, fees){
                      var result="<br>Congratulations! Your application for the has been approved<br>From:
                      MIME-Version: 1.0
                      Content-type: text/html; charset=iso-8859-1
                      Reply-to:
                      Return-Receipt-To:
                      <br>Hello ,<br>Congratulations! Your Application for the has been approved.<br>We are happy you will be joining us on <br><h3><strong><span style="font-family:arial,helvetica,sans-serif">Congratulations! &nbsp;You have been juried and selected for participation. &nbsp;</span></strong></h3>

                      <p>Booth fees are due in full, May 26th, 2017. After this date, there will be an additional late fee. Please make sure that you have mailed in your Special Event License with your NM CRS Tax ID number. It is required to sell your work.&nbsp;</p>

                      <h3><strong><span style="font-family:arial,helvetica,sans-serif">We are very excited that you will be joining us on August 17-19, 2017. &nbsp;We are looking forward to this year&rsquo;s event and anticipate a wonderful show showcasing Native fine art.&nbsp;</span></strong></h3>

                      <p><strong>If you have any questions, please don't hesitate to contact Paula Mirabal, pclrivera@hotmail.com.</strong></p>
                      <br><br>If you have not yet paid, please send your money order to: <br><br><br>If you have any questions, please don't hesitate to contact me, <br> Thanks again and see you soon.<br> has been sent";
                      alert(result);
                      return(false);
                      }
                      </script>

                      but when I look at the page source the result of the function is showing in the var result= bit? What did I do wrong here? from what I read the function should not execute until I call the javascript function?

                      found I had the email echoing from the php function but that still doesn't explain why its firing without the java script function it is contained in being called/invoked.

                        minifairy;11060947 wrote:

                        How do I send it to php and get it back while staying on the same page in the browser.

                        That's the essence of AJAX (Asynchronous Javascript And XML).

                        Because of cross-browser differences, it's often best to use a library or wrapper for AJAX (different functions for MSIE than other browsers).
                        jQuery is in widespread use, but no longer considered to be 'cutting-edge'. (That might means it's mature and worth using 😃) It has a method ".ajax" for dealing with AJAX requests and returns, and another method ".html" for writing the innerHTML of an element.

                        Here's an extremely simple jQuery implementation; assume your PHP file is "sendmail.php" and takes a variable "email" from GET, and that you have the email addresses in a JS array "emailAddresses":

                           
                        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <script> var i, send; //loop through the emailAddresses array for (i = 0; i < emailAddresses.length; i=i+1) { //send an email address to "sendmail.php" via GET send = jQuery.ajax("/sendmail.php?email="+emailAddresses[i]); //write the server's response to the HTML DIV with id "my_output_div" jQuery('#my_output_div').html = send.responseText; } </script>

                          dalecosp Ok this looks great thanks. But somehow I've screwed it up. I'm not getting any response back from the server. I know its getting there because I don't have a mail server on my local machine so I get an error in the log when it tries to email. but What did I do? Also I need to send a second $_GET variable to the case. I think I have that figured out I changed the send bit as follows:

                          send = jQuery.ajax("./show_pmts.php?p=smail&email="+eml+"fees="+fees);


                          Still not getting the response in the div id=cont

                            dalecosp Having trouble posting the java script here. but this is the part that is changed a bit from what you posted above.

                            var i, send;
                            for (i = 0; i < eml.length; i=i+1) {
                             send = jQuery.ajax("./show_pmts.php?p=smail&email="+eml[i]);
                            jQuery('#cont').html = send.responseText;
                            }
                            

                            getting errors on the forum trying to post the code. but the php echos the following after the mail is sent. Shouldn't this come back to the cont div?

                            echo $email." has been sent";

                              In jQuery .html() is a method, not a property/variable.

                              jQuery('#cont').html(send.responseText);

                                Thank you Dalecosp, Changed that. Still no response in <div id=cont> What am I missing?

                                  minifairy;11061015 wrote:

                                  Thank you Dalecosp, Changed that. Still no response in <div id=cont> What am I missing?

                                  Hard to say. Is the browser console saying anything?

                                  Also, make sure to debug your PHP 'server' ("show_pmts.php") ... feed it valid data using a browser or browser-like SW and make sure it's giving you the expected response apart from the AJAX.

                                    I recall jQuery also provides a way to deal with error responses from the server instead of silently dropping them on the floor. But even without that, as dalecosp suggests, the browser's dev tools would tell you what if anything the server is responding with.

                                      5 days later

                                      For starters I want to thank everyone that is helping me on this. I really appreciate it.
                                      Ok the console says nothing at all. I don't have a mail server on my local machine so I commented out the actual mail bit instead echoing the content of the email as well as the email address sent message. I get nothing. The source of the page showing the script part is in the attached text file. As far as I can see it looks right. I could not get the forum to put it in the code quote blocks so I uploaded it as a text file attachment.

                                      the place where the response is supposed to show up

                                      <h3 class=org>Email Progress</h3>
                                      <div id=cont>Response here</div>

                                      I can send individual emails to the subroutine and it works fine here is a link that works. This is localhost but it works online too.

                                      http://localhost/artshow/show_pmts.php?p=eax1xaxHEDRMARS

                                      note the p= portion before the x is the case it is going to. ea is the case that either sets up the java script or sends the same info to the smail routine in the case of only one person. So when someone clicks the send all emails button it goes to the ea case which builds the javascript in the attached text file and puts out the page where the progress is supposed to show up. If only one person is sent to that case in this example HEDRMARS then it builds the info and sends it to the smail case in a header stmt.

                                      header("location: show_pmts.php?p=smailx".$sid."x".$type."xa&email=".$eml."&fees=".$fees."&se=y");

                                      near as I can tell the header stmt is identical to the ajax except for the addition of the &se=y which tells it that it is a single email so it can put in the headers that would already be there for the multiple emails.

                                      The single email works. The multiple does not. If I remove the comment from the mail stmt in the php on my localhost (remember no mail server locally) then I get warnings in my apache error log

                                      [Fri Mar 10 11:19:15 2017] [error] [client 127.0.0.1] PHP Warning: mail() [<a href='function.mail'>function.mail</a>]: Failed to connect to mailserver at &quot;localhost&quot; port 25, verify your &quot;SMTP&quot; and &quot;smtp_port&quot; setting in php.ini or use ini_set() in C:\indigo\website\artshow\show_pmts.php on line 644, referer: http://localhost/artshow/show_pmts.php?p=lx1

                                      for each email it should be sending in the for next loop of the java script. But not getting any response in the 'Response Here' location on the page.

                                      Think I've tried to look everywhere just no idea what I'm missing.

                                      emailscriptsource.txt

                                        If the "console says nothing at all", there are a couple of things to note. One, apparently whatever JS you're using isn't throwing errors. That's good. Next, to do some debug tracing of your JS, add console.log() statements:

                                        myObject.myFunction();
                                        console.log("I just did the myFunction!");

                                        If your PHP script is logging a failure to send mail on the localhost, and you understand why, that's good enough. Most development machines aren't running full-fledged SMTP (Mail) servers, and I assume yours isn't, so that's cool, right?

                                        You say "But not getting any response in the 'Response Here' location on the page." Can you verify that a response is being sent? This would typically be in the "network" section of the debug console, instead of the "console" itself: