I am currently developing an application that allows users to send emails with one click of a button, whether its a singular email to an individual or bulk too all contacts.
I am stuck on how to link AJAX to the singular send button and PHPMailer file.
This is where the button is located as 'Send Single':
<script type="text/ng-template" id="display">
<td>{{data.customer_name}}</td>
<td>{{data.customer_email}}</td>
<td>
<input type="checkbox" name="single_select" class="single_select" />
</td>
<td>
<button type="button" class="btn btn-info btn-sm email_button" ng-click="sendData(data.customer_name)">Send Single</button>
</td>
<td>
<button type="button" class="btn btn-primary btn-sm" ng-click="showEdit(data)">Edit</button>
<button type="button" class="btn btn-danger btn-sm" ng-click="deleteData(data.id)">Delete</button>
</td>
</script>
<script type="text/ng-template" id="edit">
<td><input type="text" ng-model="formData.customer_name" class="form-control" /></td>
<td><input type="text" ng-model="formData.customer_email" class="form-control" /></td>
<td></td>
<td></td>
<td>
<input type="hidden" ng-model="formData.data.id" />
<button type="button" class="btn btn-info btn-sm" ng-click="editData()">Save</button>
<button type="button" class="btn btn-default btn-sm" ng-click="reset()">Cancel</button>
</td>
</script>
I have tried editing what the delete button is doing to allow this to send, but failed.
$scope.sendData = function sendData(){
if(confirm("Are you sure you want to send?"))
{
$http({
method:"POST",
url:"send_mail.php",
}).success(function(data){
$scope.success = true;
$scope.successMessage = data.message;
$scope.fetchData();
});
}
}
This is how the application currently looks, link below:
Image of current application
EDIT
The HTML code for the email is sat in the PHPMailer file, I do not need it to be processed through a form.
ORIGINAL WORKING VERSION
PHP
<?php
$count = 0;
foreach($result as $row)
{
$count++;
echo '
<tr id="index_table">
<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>
</td>
<td></td>
<td><button type="button" name="delete" id="delete" data-row="row"+count+"" class="btn btn-danger btn-xs delete">DELETE</button></td>
</tr>
';
}
?>
AJAX (didnt like code block)
$.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);
}
});
});
});
Thanks everyone :)
Here You Send Parameter and in function you not received
<button type="button" class="btn btn-info btn-sm email_button" ng-click="sendData(data.customer_name)">Send Single</button>
the workaround
$scope.sendData = function sendData(para){
In Angualr Js you should pass the parameter to the PHP script.
I guess you are not passing the value to PHP.
var Indata = {param:'val1',.....}
$scope.sendData = function sendData(){
if(confirm("Are you sure you want to send?"))
{
$http({
method:"POST",
url:"send_mail.php",
params: Indata
}).success(function(data){
$scope.success = true;
$scope.successMessage = data.message;
$scope.fetchData();
});
}
}
Try this method,
if you face still issue i think it's better if you share your PHP code here.....
Related
I tried to initialise a DataTable with data which comes from a database via this query:
public function qryUsers()
{
$users = User::orderBy('name')
->get();
return $users;
}
javascript:
function loadTable() {
$.getJSON('/admin/users3/qryUsers')
.done(function (data) {
console.log('data', data);
$('#table_id').DataTable({
"ajax": data,
"columns": [
{"data": "id"},
{"data": "name"},
{"data": "email"},
{"data": "active"},
{"data": "admin"}
]
});
})
.fail(function (e) {
console.log('error', e);
});
};
When I execute this, I get the error: DataTables warning: table id=table_id - Invalid JSON response.
When I check my json response in F12 -> network with jsonlint it says that this is valid json, so I don't really know what I'm doing wrong here.
This is what I've tried before, but when I add or delete or update a user, something goes wrong with reloading the table, which I do after each delete, add or update function. It just gives me all users, where it should give 10 with pagination, and when I sort them it still seems to use old data.
$.getJSON('/admin/users3/qryUsers')
.done(function (data) {
console.log('data', data);
// Clear tbody tag
$('tbody').empty();
// Loop over each item in the array
$.each(data, function (key, value) {
let tr = '';
if (value.name === "Amber Akkermans") {
tr = `<tr>
<td>${value.id}</td>
<td>${value.name}</td>
<td>${value.email}</td>
<td>${value.active}</td>
<td>${value.admin}</td>
<td>
<form action="/admin/users3/${value.id}" method="post" class="deleteForm">
#method('delete')
#csrf
<div class="btn-group btn-group-sm">
<button type="button" class="btn btn-outline-success btn-edit"
data-toggle="tooltip"
data-user="${value.name}"
data-id="${value.id}"
data-email="${value.email}"
data-active="${value.active}"
data-admin="${value.admin}"
title="Edit ${value.name}" disabled>
<i class="fas fa-edit"></i>
</button>
<button type="button" class="btn btn-outline-danger btn-delete"
data-toggle="tooltip"
data-user="${value.name}"
data-id="${value.id}"
title="Delete ${value.name}" disabled>
<i class="fas fa-trash-alt"></i>
</button>
</div>
</form>
</td>
</tr>`;
} else {
tr = `<tr>
<td>${value.id}</td>
<td>${value.name}</td>
<td>${value.email}</td>
<td>${value.active}</td>
<td>${value.admin}</td>
<td>
<form action="/admin/users3/${value.id}" method="post" class="deleteForm">
#method('delete')
#csrf
<div class="btn-group btn-group-sm">
<button type="button" class="btn btn-outline-success btn-edit"
data-toggle="tooltip"
data-user="${value.name}"
data-id="${value.id}"
data-email="${value.email}"
data-active="${value.active}"
data-admin="${value.admin}"
title="Edit ${value.name}">
<i class="fas fa-edit"></i>
</button>
<button type="button" class="btn btn-outline-danger btn-delete"
data-toggle="tooltip"
data-user="${value.name}"
data-id="${value.id}"
title="Delete ${value.name}">
<i class="fas fa-trash-alt"></i>
</button>
</div>
</form>
</td>
</tr>`;
}
$('tbody').append(tr);
});
$('#table_id').DataTable();
})
.fail(function (e) {
console.log('error', e);
})
}
All help is appreciated!
to return information to the format json.
change qryUsers function to :
public function qryUsers()
{
$users = User::orderBy('name')
->get();
return response()->json($users);
}
Basically my form adds to blade by help of javascript and then i can fulfill data and hit the save button.
The issue is save button doesn't work.
Here is screen record of the process and error you can watch
Code
This function will add new row and form to view where you see in video i filled input and hit save button
var textFieldsCount = 0;
function addTextField(){
textFieldsCount++;
var textfieldhelper = '';
var my_row = $('<div class="row mt-20" id="textField-' + textFieldsCount + '">');
var my_html = '{{Form::open()}}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><div class="col-md-4">{{ Form::label('customsubspecifications', 'Specifications') }}<select class="form-control" id="specification_id" name="specification_id"><option value="">Select</option>'+specifications+'</select></div>';
my_html += '<div class="col-md-4">{{ Form::label('text_dec', 'Your Custom Input') }}'+
'<input class="text_dec form-control" onkeypress="myFunction()" type="text" name="text_dec[]" id="'+ textFieldsCount.toString() +'">'+
'</div>';
my_html += '<div class="col-md-4">{{ Form::label('', 'Actions') }}<br><button type="button" class="btn btn-danger btn-xs" onclick="removeTextField(\'textField-' + textFieldsCount.toString() + '\')">Remove</button><button type="button" class="btn btn-info btn-xs" onclick="addTextField();">Add New</button><button type="button" id="custmodalsave" class="myButton custmodalsave btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
$('#fields').append(my_row);
}
here is where thing happen and I actually try to send data to back-end
$("#custmodalsave").click(function(e){
e.preventDefault();
$.ajax({
type: "post",
url: "{{ url('admin/addnewcustomsubspecifications') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'specification_id': $('#specification_id').val(),
'text_dec': $('.text_dec').val(),
'longtext_dec': $('.longtext_dec').val(),
},
success: function (data) {
$('#custspacmsg').append('<span class="text-success">Custom Specification added successfully in your product!</span>');
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
});
just to be clear I attached output form of my first ajax code so you
can see how things are printed
<div class="row mt-20" id="textField-1">
<form method="POST" action="http://newsite.pp/admin/products/15" accept-charset="UTF-8">
<input name="_token" value="DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16" type="hidden">
<input name="product_id" id="product_id" value="15" type="hidden">
<div class="col-md-4">
<label for="customsubspecifications">Specifications</label>
<select class="form-control" id="specification_id" name="specification_id">
<option value="">Select</option>
<option value="1">CPU</option>
<option value="2">ram</option>
<option value="3">LCD</option>
<option value="4">Mouse</option>
<option value="5">Graphic</option>
<option value="6">Keyboard</option>
</select>
</div>
<div class="col-md-4">
<label for="text_dec">Your Custom Input</label>
<input class="text_dec form-control" onkeypress="myFunction()" name="text_dec[]" id="1" type="text">
</div>
<div class="col-md-4">
<label for="">Actions</label>
<br>
<button type="button" class="btn btn-danger btn-xs" onclick="removeTextField('textField-1')">Remove</button>
<button type="button" class="btn btn-info btn-xs" onclick="addTextField();">Add New</button>
<button type="button" id="custmodalsave" class="myButton custmodalsave btn btn-xs btn-success" style="display: inline-block;">Save</button>
</div>
</form>
</div>
PS: I should add that I have this function working on bootstrap modal
but i wanted to change modal the way you see in video (print by click in blade)
Back-End is working perfectly since I can save data by this Ajax code with modal. Whatever the issue is, is coming from here.
You're defining your click function as
$("#custmodalsave").click(function(e){
But, when this function is defined, $("#custmodalsave") is not available in your DOM as you're appending it:
$('#fields').append(my_row); // my_row contains `[...] id="custmodalsave"`
To fix this, simply use event delegation:
$("body").on("click", "#custmodalsave", function(e){ ... });
For more info on event delegation, please check out the jQuery reference:
http://api.jquery.com/on/
I am using buttons for submit, as that is the only easy way to use fontawesome buttons. I detect which button was selected and place that value in a hidden field so that it is available in my Ajax routine.
This presents a problem, as one button requires a normal submit, as it goes to a script that creates a pdf.
The other conditions submit using Ajax. I attempted the following which, of course, will not work, as it creates a recursion loop.
Cannot figure a means to do this without creating a submit loop.
In Form:
<input type="hidden" id="Clicked" name="Clicked" value="" />
<button type="submit" class="btn btn-success ClickCheck" id="Create" style="display:inline;"> <i class="fa fa-file-pdf-o"> <span>Create Bill</span></i></button>
<button type="submit" class="btn btn-success ClickCheck" id="Reset" style="display:inline;"> <i class="fa fa-times"> <span>Reset</span></i></button>
<button type="submit" class="btn btn-success ClickCheck" id="SaveData"> <i class="fa fa-archive"> <span>Save Only</span></i></button>
<button type="submit" class="btn btn-success ClickCheck" id="Create-Save"> <i class="fa fa-archive"> <span>Create and Save</span></i></button>
jQuery Code:
$(document).ready(function()
{
$('.ClickCheck').click(function()
{
var ButtonID = $(this).attr('id');
$('#Clicked').val(ButtonID);
});
$("#MyForm").on("submit", function(event)
{
event.preventDefault();
var Form = $('#MyForm');
var Valid = verify();
if(Valid)
{
if($('#Clicked').val() == "Create")
{
$(Form).attr('action', './blformpdf.php');
$(Form).submit();
}
else
{
$.ajax(
{
type: "POST",
url: "scripts/Ajax.php",
data: Form.serialize(),
success: function(response)
{
console.log(response);
}
});
}
}
});
});
The callback should be done from verify() , I've written an example .
var goIsWaiting=false;
var goIsActive=false;
function go(){
if(goIsActive)
adviseGoIsActive()
else{
console.log("Go Is Waiting !");
goIsWaiting=true;
}
}
function activate(){
//.. Doing some stuff here
if(goIsWaiting) adviseGoIsActive();
goIsActive=true;
}
function adviseGoIsActive(){
console.log("Go Is Active !")
}
<input type="submit" value="Go" onClick="go()">
<input type="submit" value="Activate Go Action" onClick="activate()">
The solution for this problem was simply to use links rather than <input> or <button>.
Here is the HTML:
<input type="hidden" id="Clicked" name="Clicked" value="" />
<a class="btn btn-success ClickCheck" id="Create" href="javascript:void(0)"> <i class="fa fa-file-pdf-o"> <span>Create Bill</span></i></a>
<a class="btn btn-success ClickCheck" id="Reset" href="javascript:void(0)"> <i class="fa fa-times"> <span>Reset</span></i></a>
<a class="btn btn-success ClickCheck" id="SaveData" href="javascript:void(0)"> <i class="fa fa-archive"> <span>Save Only</span></i></a>
<a class="btn btn-success ClickCheck" id="Create-Save" href="javascript:void(0)"> <i class="fa fa-archive"> <span>Create and Save</span></i></a>
One of these buttons is a reset. Although you can define a <button> as type="reset", for consistency, as well as other reasons, I left that too as a link and, since the button id is part of my post, the Ajax script detects that and just returns a null, then used a jQuery reset to clear the form after the null Ajax call.
$(document).ready(function()
{
$('.ClickCheck').click(function()
{
var ButtonID = $(this).attr('id');
$('#Clicked').val(ButtonID);
var Form = $('#MyForm');
var Valid = verify(); // form verify function
if(Valid)
{
if(ButtonID == "Create") // Send to PDF script
{
$(Form).attr('action', './blformpdf.php');
$(Form).submit();
}
else
{
$.ajax(
{
type: "POST",
url: "scripts/Ajax.php",
data: Form.serialize(),
success: function(response)
{
// Do whatever here with response data
}
}
if(ButtonID == "Reset")
{
$('#MyForm').trigger("reset");
$('#Clicked').val('');
}
}
}
});
});
How to disable a button if certain condition happened. Example my order_status is 'Accepted' then the button for 'Accept' will be disabled. How can I disabled it using javascript?
Below is my code, but it didn't quiet working and I dont know why.
<div class="form-group">
<label for="order_status" class="col-sm-2 control-label" style="width:20%;">Order Status</label>
<input type="text" class="form-control" name="order_status" id="t_order_status" style="width:80%;" placeholder="" value="" required="required" readonly>
</div>
<button type="button" input style="background-color:#4CAF50;color:white;border-color:#000000;" name="submitDelivered" id="submitDelivered" class="btn btn-success" data-toggle="modal" data-target="#myDeliverModal" onclick="deliver('<?= $_POST['order_id'] ?>')" > Delivered </button>
<button type="button" input style="background-color:#0000FF;color:white;border-color:#000000;" name="submitAccept" id="submitAccept" class="btn btn-success" data-toggle="modal" data-target="#myAcceptModal" onclick="accept('<?= $_POST['order_id'] ?>')" > Accept </button>
<button type="button" style="background-color:#FFFF00;color:black;border-color:#000000;" class="btn btn-success" data-toggle="modal" data-target="#myDropdown" onclick="send('<?= $_POST['order_id'] ?>')"> Send </button>
<button type="button" input style="background-color:#f44336;color:white;border-color:#000000;" name="submitCancel" id="submitCancel" class="btn btn-success" data-toggle="modal" data-target="#myCancelModal" onclick="cancel('<?= $_POST['order_id'] ?>')">Cancel</button>
<script>
function viewOrder(order_id, order_id, user_id, order_date, order_time, order_deliveryCharge, order_totalAmount, address, coordinates, driver_number, order_status) {
document.getElementById("t_order_id").setAttribute("value", order_id);
document.getElementsByName("ORDER_ID_MODAL_2")[0].setAttribute("value", order_id);
document.getElementById("t_user_id").setAttribute("value", user_id);
document.getElementById("t_order_date").setAttribute("value", order_date);
document.getElementById("t_order_time").setAttribute("value", order_time);
document.getElementById("t_order_deliveryCharge").setAttribute("value", order_deliveryCharge);
document.getElementById("t_order_totalAmount").setAttribute("value", order_totalAmount);
document.getElementById("t_address").setAttribute("value", address);
document.getElementById("t_coordinates").setAttribute("value", coordinates);
document.getElementById("t_drivers_number").setAttribute("value", driver_number);
document.getElementById("t_order_status").setAttribute("value", order_status);
document.getElementById("ORDER_MODAL_ACCEPT").setAttribute("value", order_id);
document.getElementById("ORDER_MODAL_DELIVER").setAttribute("value", order_id);
document.getElementById("ORDER_MODAL_CANCEL").setAttribute("value", order_id);
}
function accept() {
var x = document.getElementById("t_order_status").value;
if(x == "Accepted"){
document.getElementById("submitAccept").disabled = true;
}
}
</script>
Please help me guys with my problem. If you have other suggestion/idea how can I solve this problem feel free to comment guys. I really appreciate it a lot guys, Thanks!
When I press accept button task should be updated with new value which I wrote in input.Sad thing it doesnt work like I want.Do i need to add id`s to array with objects?
or maybe there is some good method to send a object to function.Here`s the code:
<tbody>
<tr ng-repeat="task in tasks">
<td>
<button class="btn btn-danger" ng-click="deleteTask(task)">Delete</button>
<!-- $index-->
</td>
<td>{{task.taskName}}</td>
<td>
<input type="checkbox" ng-model="statusCheck"> </td>
<td style="{{setStyleToTd(statusCheck)}}">{{statusChecker(statusCheck)}}</td>
<td>
<button class="btn btn-primary" ng-click="editTask(task)">Edit</button>
</td>
</tr>
</tbody>
</table>
</div>
<div class="col-md-offset-8 edit-box" ng-show="editBoxShow">
<form action="" class="form-inline">
<div class="form-group">
<lable>Edit task here:</lable>
<div class="input-group">
<input type="text" class="form-control" ng-model="editTaskInput"> </div>
<button type="button" class="btn btn-success" ng-click="acceptEdit()">Accept</button>
</div>
</form>
</div>
$scope.editTask = function(taskToEdit) {
$scope.editBoxShow = true;
$scope.editTaskInput = taskToEdit.taskName;
}
$scope.acceptEdit = function() {
$scope.editBoxShow = false;
$scope.taskToEdit = $scope.editTaskInput;
}
You can capture the index of your table data while clicking edit button and then update the table data by using this index in acceptEdit function.
$scope.editTask = function (taskToEdit) {
$scope.selectedIndex=$scope.tasks.indexOf(taskToEdit);
$scope.editBoxShow = true;
$scope.editTaskInput = taskToEdit.taskName;
}
$scope.acceptEdit = function () {
$scope.editBoxShow = false;
$scope.tasks[$scope.selectedIndex].taskName=$scope.editTaskInput;
}