Skip to main content

Data push via Ajax/Post

I built an PHP/Ajax script to send mass newsletter emails through PHPMailer which works perfectly fine except getting the value from HTML INPUT BOX for the subject of the email.

The table gets the value from MySQL database with the following HTML/Bootstrap;

<div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <tr>
                        <th>Customer Name</th>
                        <th>Email</th>
                        <th>Select</th>
                        <th>Action</th>
                    </tr>
                <?php
                $count = 0;
                foreach($result as $row)
                {
                    $count = $count + 1;
                    echo '
                    <tr>
                        <td>'.$row["customer_name"].'</td>
                        <td>'.$row["customer_email"].'</td>
                        <td>
                            <input type="checkbox" name="single_select" class="single_select" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" />
                        </td>
                        <td>
                        <button type="button" name="email_button" class="btn btn-info btn-xs email_button" id="'.$count.'" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" data-action="single">Send Single</button>
                        </td>
                    </tr>
                    ';
                }
                ?>
                
                    <tr>
                        <td colspan="3"></td>
                        <td><button type="button" name="bulk_email" class="btn btn-info email_button" id="bulk_email" data-action="bulk">Send Bulk</button></td></td>
                    </tr>
                    <tr>
                </table>
            </div>

The following AJAX/POST submits the data to PHP to call PHPMailer function;

<script>
$(document).ready(function(){
    $('.email_button').click(function(){
        $(this).attr('disabled', 'disabled');
        var id  = $(this).attr("id");
        var action = $(this).data("action");
        var email_data = [];
        if(action == 'single')
        {
            email_data.push({
                email: $(this).data("email"),
                name: $(this).data("name")
            });
        }
        else
        {
            $('.single_select').each(function(){
                if($(this).prop("checked") == true)
                {
                    email_data.push({
                        email: $(this).data("email"),
                        name: $(this).data("name")
                    });
                } 
            });
        }

        $.ajax({
            url:"send_mail.php",
            method:"POST",
            data:{email_data:email_data},
            beforeSend:function(){
                $('#'+id).html('Sending...');
                $('#'+id).addClass('btn-danger');
            },
            success:function(data){
                if(data == 'ok')
                {
                    $('#'+id).text('Success');
                    $('#'+id).removeClass('btn-danger');
                    $('#'+id).removeClass('btn-info');
                    $('#'+id).addClass('btn-success');
                }
                else
                {
                    $('#'+id).text(data);
                }
                $('#'+id).attr('disabled', false);
            }
        })

    });
});
</script>

The following PHP Script grabs the data and sends email which works perfectly fine.

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

if(isset($_POST['email_data']))
{
    $output = '';
    foreach($_POST['email_data'] as $row)
    {
        $mail = new PHPMailer;
        $mail->IsSMTP();        
        $mail->XMailer  = "Gleez CMS 0.10.5";   
        $mail->SMTPKeepAlive = true;                    
        $mail->Host = "smtp.gmail.com";
        $mail->Port = 587;
        $mail->SMTPAuth = TRUE;
        $mail->Username = "user@gmail.com";
        $mail->Password = "password";
        $mail->SMTPSecure = "tls";
        $mail->From = "user@gmail.com";
        $mail->FromName = "Jack N";
        $mail->AddAddress($row["email"], $row["name"]);
        $mail->WordWrap = 50;
        $mail->IsHTML(true);
        $mail->Subject = "You have a new message";
        $mail->Body = "This line also supports html";

        $mail->AltBody = '';

        $result = $mail->Send();

        if($result["code"] == '400')
        {
            $output .= html_entity_decode($result['full_error']);
        }

    }
    if($output == '')
    {
        echo 'ok';
    }
    else
    {
        echo $output;
    }
}

?>

The challenge I face is to replace

$mail->Subject = "You have a new message";

with

$mail->Subject($row["subject"]);

The actions I tried was to include the following lines in my HTML page like,

<input type="text" name="subject" id="subject">

// modify the AJAX Script

subject:$(this).data("subject")
or var subject = document.getElementById("subject");

but none worked! :(

Any guidance, please? Thank you! Wish y'all a healthy days ahead. Cheers.



source https://stackoverflow.com/questions/67731296/data-push-via-ajax-post

Comments

Popular posts from this blog

Where and how is this Laravel kernel constructor called? [closed]

Where and how is this Laravel kernel constructor called? public fucntion __construct(Application $app, $Router $roouter) { } I have read the documentation and some online tutorial but I can find any clear explanation. I am learning Laravel and I am wondering where does this kernel constructor receives its arguments from. "POSTMOTERM" CLARIFICATION: Here is more clarity.I have checked the boostrap/app.php and it is only used for boostrapping the interfaces into the container class. What is not clear to me is where and how the Kernel class is instatiated and the arguments passed to the object calling the constructor.Something similar to; obj = new kernel(arg1,arg2) or, is the framework using some magic functions somewhere? Special gratitude to those who burn their eyeballs and brain cells on this trivia before it goes into a full blown menopause alias "MARKED AS DUPLICATE". To some of the itchy-finger keyboard warriors, a.k.a The mods,because I believe in th...

Why is my reports service not connecting?

I am trying to pull some data from a Postgres database using Node.js and node-postures but I can't figure out why my service isn't connecting. my routes/index.js file: const express = require('express'); const router = express.Router(); const ordersCountController = require('../controllers/ordersCountController'); const ordersController = require('../controllers/ordersController'); const weeklyReportsController = require('../controllers/weeklyReportsController'); router.get('/orders_count', ordersCountController); router.get('/orders', ordersController); router.get('/weekly_reports', weeklyReportsController); module.exports = router; My controllers/weeklyReportsController.js file: const weeklyReportsService = require('../services/weeklyReportsService'); const weeklyReportsController = async (req, res) => { try { const data = await weeklyReportsService; res.json({data}) console...

Confusion between commands.Bot and discord.Client | Which one should I use?

Whenever you look at YouTube tutorials or code from this website there is a real variation. Some developers use client = discord.Client(intents=intents) while the others use bot = commands.Bot(command_prefix="something", intents=intents) . Now I know slightly about the difference but I get errors from different places from my code when I use either of them and its confusing. Especially since there has a few changes over the years in discord.py it is hard to find the real difference. I tried sticking to discord.Client then I found that there are more features in commands.Bot . Then I found errors when using commands.Bot . An example of this is: When I try to use commands.Bot client = commands.Bot(command_prefix=">",intents=intents) async def load(): for filename in os.listdir("./Cogs"): if filename.endswith(".py"): client.load_extension(f"Cogs.{filename[:-3]}") The above doesnt giveany response from my Cogs ...