File attachment with AJAX and PHP - php

I want to add file upload function to my job application form. For now everything is working, i get a meesage to my mail but i want to add CV upload option. I made input type file for that but i dont know how to take that file and send it to my mail as attachment. Thank u.
This is my AJAX code:
var sucessMessagee = $("#sucessMessage");
$("#contact_form").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
console.log('Invalid form');
} else {
event.preventDefault();
submitForm();
}
});
function submitForm(){
var name = $("#name").val();
var surname = $('#surname').val();
var email = $("#email").val();
var year = $("#year").val();
var month = $("#month").val();
var day = $("#day").val();
var adress = $("#adress").val();
var phone = $("#phone").val();
$.ajax({
type: "POST",
url: "/php/jobs.php",
data: "name=" + name + "&surname=" + surname + "&email=" + email + "&year=" + year + "&month=" + month + "&day=" + day + "&adres=" + adress + "&phone=" + phone,
success : function(text){
if (text == "success"){
formSuccess();
} else {
console.log('Failed message');
}
}
});
};
function formSuccess(){
$("#contact_form")[0].reset();
$("#posao1").css("display", "none");
showMessage();
setTimeout(function() {sucessMessagee.css('display', 'none')},4000);
};
function showMessage() {
sucessMessagee.css('display', 'block');
};
And this is my php code:
<?php
require 'phpmailer/PHPMailerAutoload.php';
$result = $_POST['result'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$adress = $_POST['adress'];
$phone = $_POST['phone'];
/*if (isset($_FILES['attachment']['name']) && $_FILES['attachment']['name'] != "") {
$file = "attachment/" . basename($_FILES['attachment']['name']);
move_uploaded_file($_FILES['attachment']['tmp_name'], $file);
} else
$file = "";*/
$mail = new PHPMailer;
$mail->setFrom($email, 'Prijava za posao');
$mail->addAddress('luka9825#hotmail.com', 'Office');
$mail->Subject = 'Prijava za posao sa sajta proenterijer.rs';
$mail->Body = "Ime i prezime: $name $surname
\nDatum rođenja: $day.$month.$year
\nAdresa stanovanja: $adress
\nKontakt telefon: $phone
\nE-Mail adresa: $email";
if(!$mail->send()) {
} else {
echo "success";
}
?>

// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
$('form').on('submit', uploadFiles);
// Catch the form submit and upload the files
function uploadFiles(event)
{
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
// START A LOADING SPINNER HERE
// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'submit.php?files',
type: 'POST',
data: data + "name=" + name + "&surname=" + surname + "&email=" + email + "&year=" + year + "&month=" + month + "&day=" + day + "&adres=" + adress + "&phone=" + phone,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
submitForm(event, data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
Now you can get the file from $_GET['files'] in php and then use that to send through the email. Add

You will have to need a slight modification to your submitForm() function as follows:
function submitForm(){
var name = $("#name").val();
var surname = $('#surname').val();
var email = $("#email").val();
var year = $("#year").val();
var month = $("#month").val();
var day = $("#day").val();
var adress = $("#adress").val();
var phone = $("#phone").val();
var form_data = new FormData();
form_data.append('file', $('#ID_OF_YOUR_FILE_INPUT').prop('files')[0]);
form_data.append('name',name);
form_data.append('surname',surname);
form_data.append('email',email);
form_data.append('year',year);
form_data.append('month',month);
form_data.append('day',day);
form_data.append('adress',adress);
form_data.append('phone',phone);
$.ajax({
type: "POST",
url: "/php/jobs.php",
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
success : function(text){
if (text == "success"){
formSuccess();
} else {
console.log('Failed message');
}
}
});
};
And your PHP would have to be modified to something like:
<?php
require 'phpmailer/PHPMailerAutoload.php';
$result = $_POST['result'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$year = $_POST['year'];
$month = $_POST['month'];
$day = $_POST['day'];
$adress = $_POST['adress'];
$phone = $_POST['phone'];
$mail_attachment = $_FILES['file']; // Observe, you don't have to upload the file to your server
$mail = new PHPMailer;
$mail->setFrom($email, 'Prijava za posao');
$mail->addAddress('luka9825#hotmail.com', 'Office');
$mail->addAttachment($mail_attachment);
$mail->Subject = 'Prijava za posao sa sajta proenterijer.rs';
$mail->Body = "Ime i prezime: $name $surname
\nDatum rođenja: $day.$month.$year
\nAdresa stanovanja: $adress
\nKontakt telefon: $phone
\nE-Mail adresa: $email";
if(!$mail->send()) {
} else {
echo "success";
}
?>

Related

php file not called from ajax call

Have a problem to call my server.php to add some values into db.
server.php:
<?php
$db = new PDO('mysql:host=localhost;dbname=test','user','password');
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$address = $_POST['address'];
$stmt = $db->prepare("INSERT INTO user (name,email,phone,address) VALUES(?,?,?,?)");
$stmt->bindParam(1,$name);
$stmt->bindParam(2,$email);
$stmt->bindParam(3,$phone);
$stmt->bindParam(4,$address);
$stmt->execute();
echo "data saved";
?>
Calling the server.php directly, the data will be saved.
But from my Html/Ajax code it will not:
<script>
function saveData(){
var name = $('#name').val();
var email = $('#email').val();
var phone = $('#phone').val();
var address = $('#address').val();
$.ajax({
type: "POST",
url: "server.php",
data: "name=" +name+"&email="+email+"&phone="+phone+"&address="+address,
}).done(function(data){
alert('success');
$('#result').html("<br/><div> class='alert alert-info'>" + data +"</div>");
)};
return false;
</script>
The alert('success') won't be called also #result div isn't filled.
Whats wrong with this code?

Question mark gets appended to URL when error encountered?

I have a form. When I submit and try to insert a duplicate record in the database, the page reloads and the error message is logged in the console. However, after* the page reloads, a question mark is already appended to the end of the URL. Why is that so?
Like from this:
http://localhost/project/home
to this (after database error occurred due to duplicate record):
http://localhost/project/home?
Controller:
public function loadBoardManagement()
{
$role = $this->session->userdata('role');
$user_id = $this->session->userdata('user_id');
$board_id = $this->uri->segment(3);
$role = 'Admin';
$user_id = 1;
if ($this->uri->segment(3) == null)
{
$board_id = 178;
}
if ($this->session->userdata('first_board_id') !== null && $board_id == 0)
{
$board_id = $this->session->userdata('first_board_id');
}
$data['boards'] = $this->Board_model->getBoards($role, $user_id);
$data['board_assignees'] = $this->Team_model->getBoardAssignees($board_id);
$data['all_teams'] = $this->Team_model->getAllTeams();
$data['team_quantity'] = $this->Team_model->getBoardTeamsQuantity($board_id);
$data['board_name'] = $this->Board_model->getBoardName($board_id);
$data['board_id'] = $board_id;
$this->load->view('board_management', $data);
}
public function fast_signup()
{
$username = $this->input->post('username');
$password = $this->input->post('password');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$email = $this->input->post('email');
$role = $this->input->post('role');
$fast_signup = $this->User_model->fastSignup($username, $password, $first_name, $last_name, $email, $role);
if ($fast_signup)
{
echo 'success';
}
else
{
echo $fast_signup;
}
}
javascript:
function addMember()
{
var username = $('#username').val();
var password = $('#password').val();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
var role = $('#role option:selected').val();
console.log('Role: ' + role);
console.log(username + password + first_name + last_name + email);
$.ajax({
type: 'POST',
url: base_url + 'user/fast_signup', //controller for inserting new members, but the current page is localhost/project/board/loadBoardManagement
data: {
'username': username,
'password': password,
'first_name':first_name,
'last_name': last_name,
'email': email,
'role' : role
},
success: function(msg)
{
if (msg == 'success')
{
console.log('Member created');
window.location.href = window.location.href;
}
else
{
console.log('Failed to create member!' + msg);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('Response: ' + jqXHR.responseText);
console.log('Status code: ' + textStatus);
console.log('Error thrown: ' + errorThrown);
}
});
}
$('#create_user_member').click(function() {
addMember();
});

input to database successfully but still always give a fail alert jquery

I am trying to input data from a input form to database, but it always gives a fail alert even the data is success to input. so this is the part of my code
jquery
$("#daftar").click(function(){
nim = $("#kdAlumni").val();
tahun = $("#kdTahun").val();
nama = $("#Nama").val();
nohp = $("#Nohp").val();
foto = $("#Foto").val();
email = $("#Email").val();
jurusan = $("#kdJurusan").val();
judul = $("#judul").val();
fakultas = $("#kdFakultas").val();
tgl = $("#Lahir").val();
$.ajax({
type: "POST",
url: "insertupdate.php",
data: "nim=" + nim + "&nama=" + nama + "&nohp=" + nohp + "&email=" + email + "&jurusan=" + jurusan + "&foto=" + foto + "&judul=" + judul + "&fakultas=" + fakultas + "&tahun=" + tahun + "&tgl=" + tgl,
success: function(dat)
{
if(dat == 'true')
{
alert("input success");
$("#kdAlumni").val("");
$("#kdTahun").val("");
$("#Nama").val("");
$("#Nohp").val("");
$("#Foto").val("");
$("#Email").val("");
$("#kdJurusan").val("");
$("#judul").val("");
$("#kdFakultas").val("");
$("#Lahir").val("");
}
else if(dat == 'false')
{
alert("input fail");
$("#kdAlumni").val("");
$("#kdTahun").val("");
$("#Nama").val("");
$("#Nohp").val("");
$("#Foto").val("");
$("#Email").val("");
$("#kdJurusan").val("");
$("#judul").val("");
$("#kdFakultas").val("");
$("#Lahir").val("");
}
}
});
return false;
});
php
<?php
session_start();
$host = "localhost";
$user = "root";
$pass = "";
$name = "buku_tahunan";
$koneksi = mysqli_connect($host,$user,$pass,$name);
if(mysqli_connect_errno())
{
die("koneksi DB Gagal".mysqli_connect_error());
}
$nim = $_POST["nim"];
$nama = $_POST["nama"];
$nohp = $_POST["nohp"];
$email = $_POST["email"];
$jurusan = $_POST["jurusan"];
$fotoN = $_FILES['foto']['name'];
$fotoT = $_FILES['foto']['tmp_name'];
$tujuan = "foto/" .$fotoN;
$judul = $_POST['judul'];
$fakultas = $_POST["fakultas"];
$tahun = $_POST["tahun"];
$tgl = $_POST["tgl"];
$sql="INSERT INTO `data_alumni`(`kdAlumni`, `nama`, `noHP`, `email`, `foto`, `judulSkripsi`, `kdFakultas`, `kdTahun`, `kdJurusan`, `tgl_lahir`) VALUES ('$nim','$nama','$nohp','$email','$tujuan','$judul','$fakultas','$tahun','$jurusan','$tgl')";
$insert = mysqli_query($koneksi,$sql);
move_uploaded_file($sumber, $tujuan);
if($insert)
{
echo 'true';
}
else
{
echo 'false';
}
?>
that's all of my code to input data to database, so what's the real problem from my code? thank you
It's not uncommon to have extra whitespace in the response. Try trimming any whitespace:
success: function(dat){
dat = dat.trim();
if(dat == 'true'){.....
Also check what dat is in the response to be sure it is what is expected and to narrow down where the actual issue lies.
Generally easier to use json for all responses
finally I realize the reason of this error, when I try to debug the script I see the problem that caused by $_FILES. The way that I input value from in javascript is the real problems

Using SweetAlert to Display messages after inserting data to MySql using php

I have combined html, php and ajax to insert data in mysql database. And I want to display success or error messages in ajax success function using SweetAlert. The data is getting inserted into the database but I am unable to display the messages.
Following is my code:
insert.php
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("hotelmanagement", $connection);
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$checkInDate = $_POST['checkInDate'];
$checkOutDate = $_POST['checkOutDate'];
$adults = $_POST['adults'];
$children = $_POST['children'];
$specialInstructions = $_POST['specialInstructions'];
$query = mysql_query("INSERT INTO reservation(FirstName,LastName,Address1,Address2,Phone,Email,Adults,Children,CheckInDate,CheckOutDate,SpecialInstructions) VALUES('$fName','$lName','$address1','$address2','$phone','$email','$checkInDate','$checkOutDate','$adults','$children','$specialInstructions')");
echo json_encode($query);
mysql_close($connection);
?>
And this is my ajax code:
$("#submit").click(function(){
var fName = $("#fName").val();
var lName = $("#lName").val();
var address1 = $("#address1").val();
var address2 = $("#address2").val();
var phone = $("#phone").val();
var email = $("#email").val();
var checkInDate = $("#checkinDate").val();
var checkOutDate = $("#checkoutDate").val();
var adults = $("#adults").val();
var children = $("#children").val();
var specialInstructions = $("#specialInstructions").val();
if(fName == '' || lName == '' || phone == ''){
swal("Oops!!", "Looks like you missed some fields. Please check and try again!", "error");
}else{
$.ajax({
type:'post',
url:'insert.php',
data: {fName:fName,lName:lName,address1:address1,address2:address2,phone:phone,email:email,checkInDate:checkInDate,checkOutDate:checkOutDate,adults:adults,children:children,specialInstructions:specialInstructions},
dataType:'json',
succcess:function(data){
swal("Success", "Data Saved Successfully", "success");
},
error:function(xhr, thrownError, ajaxOptions){
},
});
}
});
Could you please tell me what am I missing. Thank you.
your success callback is triple ccc and try to remove dataType:'json',
try this ajax request
$.ajax({
type:'post',
url:'insert.php',
data: {fName:fName,lName:lName,address1:address1,address2:address2,phone:phone,email:email,checkInDate:checkInDate,checkOutDate:checkOutDate,adults:adults,children:children,specialInstructions:specialInstructions},
success:function(data){
swal("Success", "Data Saved Successfully", "success");
},
error:function(xhr, thrownError, ajaxOptions){
}
});

contact form jquery php phonegap - success issue

i try to create a contact form in jquery php 4 phonegap, my problem how can i have response success from php? or if i can try other solutions but havent ideas 4 for the moment ^^
thx a lot
p.s. the form works (if i delete response success form js)
index.js
$(document).on('pageinit', function() {
$('#send').click(function() {
var url = 'send02.php';
var error = 0;
var $contactpage = $(this).closest('.ui-page');
var $contactform = $(this).closest('.contact-form02');
$('.required', $contactform).each(function(i) {
if($(this).val() === '') {
error++;
}
});
// each
if(error > 0) {
alert('Inserisci tutti i campi obbligatori segnati con asterisco*.');
} else {
var email = $contactform.find('input[name="email"]').val();
var datetime = $contactform.find('input[name="datetime"]').val();
var mobilephone = $contactform.find('input[name="mobilephone"]').val();
var selectnative4 = $contactform.find('select[name="selectnative4"]').val();
var message = $contactform.find('textarea[name="message"]').val();
//submit the form
$.ajax({
type : "POST",
url : url,
data : {
email : email,
datetime : datetime,
mobilephone : mobilephone,
selectnative4 : selectnative4,
message : message
},
success : function(data) {
if(data == 'success') {
// show thank you
$contactpage.find('.contact-thankyou').show();
$contactpage.find('.contact-form').hide();
} else {
alert('Impossibile inviare il messaggio. Per piacere riprova.');
}
}
});
//$.ajax
}
return false;
});
});
and send.php
<?php
header('content-type: application/json; charset=utf-8');
if (isset($_GET["email"])) {
$email = strip_tags($_GET['email']);
$datetime = strip_tags($_GET['datetime']);
$mobilephone = strip_tags($_GET['mobilephone']);
$selectnative4 = strip_tags($_GET['selectnative4']);
$message = strip_tags($_GET['message']);
$header = "From: ". $firstname . " <" . $email . ">rn";
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$today = date("F j, Y, g:i a");
$recipient = 'mark#facebook.com';
$subject = 'Prenotazione Online';
$mailbody = "
Nominativo: $email
Telefono: $mobilephone
data prenotazione: $datetime
Scelta dal Menù: $selectnative4
Messaggio: $message
in data: $today
";
$result = 'success';
if (mail($recipient, $subject, $mailbody, $header)) {
echo json_encode($result);
}
}
?>

Categories