How to prevent $.ajax form from sending multiple emails? - contact-form

I have two email forms on one webpage. The form sends email correctly when submitted only once, but when I hit the submit button for the second time or more, not only the email with data is sent, but also additional empty emails. I can't figure out how to fix it. Here's the code:
HTML:
<form id="notify-form" name="notify-form" action="#" method = "post">
<div class="input-group">
<input class="input-field" type="email" id="email-notify" name="emailnotify" placeholder="Type your email..." required>
<span class="input-label">
<button class="btn-submit" onclick="ajax_news();"><i class="icon-arrow"></i></button>
</span>
</div>
</form>
Script:
function ajax_news(){
var form = $('#notify-form'); //form id here
form.submit(function(event){
event.preventDefault();
var form_newsstatus = $('<div class="form_status"></div>');
var $form = $(this);
$.ajax({
type: 'POST',
url: "process-news.php",
data:{
Email2:$form.find("input[name='emailnotify']").val()
},
beforeSend: function(){
form.append(form_newsstatus.html('Sending...').fadeIn());
}
}).done(function(data){
form_newsstatus.html('Thank you! We will notify you soon!').delay(5210).fadeOut();
});
//delete messages when submit
document.getElementById("email-notify").value= "";
});
}
function ajax_post(){
//Similar code for the second form
}
PHP:
<?php
ini_set("mail.log", "/tmp/mail.log");
ini_set("mail.add_x_header", TRUE);
//variables
$email_address = strip_tags(htmlspecialchars($_POST['Email2']));
// Create the email and send the message
$to = 'email#email.com';
$email_subject = "Email subject";
$email_body = "Email message:\n\nEmail: $email_address\n\n\n";
$headers = "From: email#email.com\n";
$headers .= "Reply-To: $email_address";
if(mail($to,$email_subject,$email_body,$headers)){ echo "Mail sent!";}
else{ echo "Error, check your logs."; }
return true;

Related

Get value from a database and set it as selected value of a dropdownlist using Angularjs

I get some values from a database. With one of the values I get, I would like to have that as a selected value in the dropdownlist when another dropdownlist changes. Please see code below:
index
<div class="form-group">
<select ng-model="editProject.ClientId" name="client_id" ng-options="item as item.Company for item in clientList" class="form-control">
</select>
<div>-->{{editProject.ClientId}}</div> <=== This is to see if I am getting the value from js
<span style="color: red;" ng-show="formEditProject.client_id.$touched && formEditProject.client_id.$invalid">Select a client</span>
</div>
js
//=== This is the client list in the dropdown list ===>
$scope.editClient = {
"ClientId": null,
"Company": null,
"ContactPerson": null,
"EmailAddress": null
}
//== Retrieves clients from the database on page load ===>
$scope.getClients = function () {
return $http.get('/Clients/GetClients')
.then(function (response) {
$scope.clientList = response.data;
});
};
//== Event when a different dropdownlist is changed ===>
$scope.onProjectEditChange = function () {
console.log($scope.selectedProjectId.Id);
$http({
url: '/Project/GetProjectByProjectId',
params: {
"id": $scope.selectedProjectId.Id
},
method: 'post'
})
.then(function (response) {
$scope.editProject.Id = response.data.Id;
$scope.editProject.Description = response.data.Description;
$scope.editProject.ClientId = response.data.ClientId;
$scope.editProject.ProjectLead = response.data.ProjectLead;
$scope.editProject.IsApproved = response.data.IsApproved;
});
}
I am able to see the clientId change in the <div>-->{{editProject.ClientId}}</div> but it doesn't change the selected value of the dropdownlist.
Use ng-change option and check it
<div class="form-group">
<select ng-model="editProject.ClientId" name="client_id" ng-options="item as item.Company for item in clientList" class="form-control" ng-change='changeSelectedItem(editProject.ClientId")'>
</select>
<div>-->{{editProject.ClientId}}</div> <=== This is to see if I am getting the value from js
<span style="color: red;" ng-show="formEditProject.client_id.$touched && formEditProject.client_id.$invalid">Select a client</span>
</div>
$scope.changeSelectedItem = function(client){
$scope.editProject.ClientId= client.ClientId;
}

How to empty form inputs in angular js after submission

Hello amazing Stackoverflow Coders, Please how do I empty form inputs in angular Js after form submission.
below is my working code
$rootScope.sendNow = function () {
if ($rootScope.send_login.username.length < 1)
alert("Please enter username");
else if ($rootScope.send_login.password.length < 1)
alert("Please enter password");
else {
$http.post($rootScope.server_url + "post_Data", $rootScope.send_login)
.success(function (response)
{
// on success
$('#send_login.username').val('');
$('#send_login.password').val('');
toastr.success('Successful');
}
).error(function (response)
{
alert("sending failed");
});
}
};
My Form is here below
<input type="text" id="username" name="username" ng-value="send_login.username">
<input type="text" id="pass" name="pass" ng-value="send_login.password">
<input type="button" ng-click="sendNow()" value="Send">
Unlike Ajax, I have tried this below but cannot get it to work
$('#send_login.username').val('');
$('#send_login.password').val('');
you should use ng-model in the input tag, like:
html:
<input type="text" ng-model="name">
<button ng-click="sendData()"> Send</button>
js (angularjs Controller):
$scope.sendData = function (item) {
$scope.name = "";
}
Its better to take every form field ng-modal as a property of a object, like you have taken in "send_login".
After form submission reinitialize this object send_login = {};
Every field will be reinitialize. and a undefined property doesn't create a error in angular.
You should avoid so much use of $rootScope in your code.
You need to change ng-value to ng-model (to bind the angular variable to html input) and on ajax success clear the binded variable:
$http.post('...').success(function (response) {
$rootScope.send_login = {};
});

How to pass a model to AngularJS fileuploader?

I want to upload few files to server with angularjs-file-uploader. I have an array of viewModels, I want to upload files and get the IDs of uploaded files and assign them to corresponding viewModels.
Is there any way to pass my viewModels to fileUploader? Here are the codes I have written so far.
<div ng-if="vm.isFile(v.formItem)" class="form-group form-md-line-input form-md-floating-label no-hint">
<div class="form-group">
<input type="file" name="v.id" nv-file-select uploader="vm.uploader" />
<span class="help-block m-b-none">{{v.formItem.description}}</span>
</div>
</div>
I want to pass a "v.formItem" which has a property for uploadedFileId. so that I can assign uploaded file's Id to my Model.
this.uploader = new FileUploader({
url: 'File/UploadFile',
autoUpload: true,
removeAfterUpload: true,
queueLimit: 1
});
this.uploader.onSuccessItem = function (fileItem, response, status, headers) {
if (response.success) {
formItem.uploadedFileId = response.result.id ;
}
};
I found the solution. I just needed to use "options" property for file input. like this:
<input type="file" name="v.id" options={formItem:v.formItem} nv-file-select uploader="vm.uploader" />
javascript:
this.uploader.onSuccessItem = function (fileItem, response, status, headers) {
if (response.success) {
var formItem = fileItem.formItem;
formItem.uploadedFileId = response.result.id ;
}
};

angularjs and grails 2.5.0 save success, no errors but not saving to database

I've been looking for similar situations like mine has and I've seen that it is common to have this error but I can not find the right solution with my problem. I would really appreciate any help.
My problem right now is that when I execute this it return and HTTP 200 and also prints a line on my terminal which confirms me that it creates the JSON file. There are no errors but when I checked on my database, there's nothing in it.
What I've tried so far:
newBook.save(flush: true)
edit my datasource from create-drop to update (but my whole database disappears so I returned the data. I only need to save it during a demo so I understand that the data will be lost every time the application restarts)
Postman GET and POST
GET: 200 OK
POST: 200 OK
but when I GET again, nothing is showing
debugging using console and println (but there might be something that I missed since I'm just starting to learn both AngularJS and Grails)
I am hoping that these data can give a detailed information about my problem, I am open for any questions.
Here are my sample codes:
back-end codes: Grails 2.5.0
Domain class
class Book {
String name
int page
boolean new
static belongsTo = [student: student]
static constraints = {
}
}
Controller
import grails.converters.JSON
import org.springframework.security.access.annotation.Secured
#Secured('permitAll')
class BookController {
def index() {
render Book.list() as JSON
}
def save() {
def newBook = new Book(request.JSON)
newBook.save(flush: true)
println request.JSON
render(['success': true] as JSON)
}
def show() {
def Book = Book.get(params.id)
render Book as JSON
}
}
front-end codes: AngularJS
Controller
app.controller('Book', function($scope, store, $state, bookFactory){
$scope.book = {}
$scope.saveBook = function() {
$scope.book.assessment = $scope.getBook();
console.log($scope.book);
bookFactory.save($scope.book,function (result){
console.log(result)
}, function (error) {
console.log(error)
})
}
$scope.getBook = function() {
var result = "";
if ($scope.book.page > 10){
result = "many pages";
}else if ($scope.book.new && $scope.book.page > 20){
result = "new and many pages";
}else {
result = "old book";
}
return result;
};
})
Service
app.factory('bookFactory', ['$resource', function ($resource) {
return $resource('api/book',
{
'update': {method: 'PUT'}
})
}])
app.js
.state("book", {
url: "/book",
templateUrl: "assets/app/partials/book.html",
controller: 'Book',
data: {
requiresLogin: true
}
})
HTML
Book Name:
<input type="text" ng-model="book.name" name="bookName" required="" class="form-control" />
Number of Pages:
<input type="number" ng-model="book.page" name="numberPage" required="" class="form-control" placeholder="Number of Pages"/>
Bought within the last 30 days?
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="new" value=true ng-model="book.new" >
<font color=green>YES</font>
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="new" value=false ng-model="book.new">
<font color=red>NO</font>
</label>
</div>
</div>
<a ui-sref="book" class="btn btn-primary" name="bookBtn" ng-click="saveBook()"> Next </a>

How to get binding value in input hidden value Angular

I have file upload and I can upload file then get controller value put in input hidden value because I will be post form.
HTML CODE
<input type="file" class="form-control" id="i_file5" file-model="process.step.file5" ng-file-select="onFileSelect($files5)" />
<input type="hidden" ng-model="{{files.name}}"/>
Controller Code
$scope.uploadResult = [];
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$upload.upload({
url: 'lib/fileupload/',
file: $file,
progress: function(e){}
}).then(function(response) {
// file is uploaded successfully
$timeout(function() {
$scope.uploadResult.push(response.data);
console.log($scope.uploadResult);
});
});
}
}
I am assuming you have already specify controller in HTML. If not please implement as shown in below example. For ng-model you should not use {{ }} as you are binding the value not evaluating it.
<div ng-controller="files">
----
<input type="text" data-ng-model="files.name" style="display:none"/>
</div>

Resources