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

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...

How to show number of registered users in Laravel based on usertype?

i'm trying to display data from the database in the admin dashboard i used this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count(); echo $users; ?> and i have successfully get the correct data from the database but what if i want to display a specific data for example in this user table there is "usertype" that specify if the user is normal user or admin i want to user the same code above but to display a specific usertype i tried this: <?php use Illuminate\Support\Facades\DB; $users = DB::table('users')->count()->WHERE usertype =admin; echo $users; ?> but it didn't work, what am i doing wrong? source https://stackoverflow.com/questions/68199726/how-to-show-number-of-registered-users-in-laravel-based-on-usertype

The number of nodes and edges I calculated manually and by a method provided by networkx library dont match

I am trying to analyse a graph using networkx library in Python. I have implemented a function that returns the nodes and edges of that graph. After that I counted the number of nodes and edges by implementing the len() function for nodes and edges, which gave me 17 for both nodes and edges. However, when I used the method graph.number_of_nodes() of networkx library it gave me 53. My code: import pandas as pd import networkx as nx import matplotlib.pyplot as plt header_list = ["a","b","w"] E =pd.read_csv("aves-barn-swallow-contact-network.edges",sep=" ",header= None,names=header_list) # print(E.head()) # prints first few rows of the csv file G = nx.from_pandas_edgelist(E,"a","b",["w"]) nx.draw(G) plt.show() class GraphAnalyse: #finding nodes and edges def nodeEdge(self,Graph): nodes = Graph.nodes() edges = Graph.edges() ...