How to send an ajax contact form with to a recipient email address - ajax

I've currently got this:
$.ajax({
url: '/some/url',
dataType: 'json',
type: 'POST',
data: formData,
success: function(data) {
if (window.confirm('Thank you for your message. Can I erase the form?')) {
document.querySelector('.form-input').val('');
}
},
error: function(xhr, status, err) {
console.error(status, err.toString());
alert('There was some problem with sending your message.');
}
});
Instead of it going to a URL, how can I change it to send directly to a specific email address? I am using this contact form with a React app I've created.

So react component, class based.
class Foo extends Component {
popupQuestion() {
// implement method
}
sendEmail() = () => {
axios.post('/some/url', {
subject: 'mail',
to: 'someone#example.com',
body: 'something',
name: 'name'
})
.then(function (response) {
popupQuestion();
})
.catch(function (error) {
console.log(error);
return 'Error occurred. Please refresh page and try again.';
});
}
render() {
return(
<form onSubmit={this.sendEmail}>
// ...
</form>
);
}
}
And php method that will be executed on some/url
public function sendEmailAction(): bool
{
$request = // get request;
$subject = $request->get('subject');
$to = $request->get('to');
$body = $request->get('body');
$name = $request->get('name');
$transport = (new Swift_SmtpTransport('smtp.example.org', 25))
->setUsername('your username')
->setPassword('your password');
$mailer = new Swift_Mailer($transport);
$message = (new Swift_Message($subject))
->setFrom(['mymail#exmaple.com' => 'me'])
->setTo([$to => $name])
->setBody($body);
$sent = $mailer->send($message);
return $sent ? true : false;
}

Related

I don't want to show pop error message when i disable switch using laravel

i am new at laravel ,when i enable switch popup message is working perfectly but I don't want to show error popup message when i disable to switch please how can i do that help me thanks.
Does Anyone have an idea please help me thank.
CONTROLLER
public function featured(Request $request)
{
if ($request->is_featured) {
$assignFeature = Product::where('is_featured', 1)->exists();
if ($assignFeature) {
$response['error'] = 'Product is already featured';
return response()->json($response, 422);
}
}
$id = $request->input('id');
$featured = $request->input('is_featured');
$featurediItem = Product::find($id);
if ($featurediItem->update(['is_featured' => $featured])) {
// form helpers.php
logAction($request);
$response['is_featured'] = true;
$response['message'] = 'product featured updated successfully.';
return response()->json($response, 200);
}
}
ajax script
$('.postfeatured').change(function () {
var $this = $(this);
var id = $this.val();
var is_featured = this.checked;
if (is_featured) {
is_featured = 1;
} else {
is_featured = 0;
}
axios
.post('{{route("product.featured")}}', {
_token: '{{csrf_token()}}',
_method: 'patch',
id: id,
is_featured: is_featured,
})
swal({
text: "Product is already featured",
type: 'error',
confirmButtonColor: '#4fa7f3',
})
.then(function (responsive) {
console.log(responsive);
})
.catch(function (error) {
console.log(error);
});
});
you can use axios.post.then method to work after getting response success fully. Something like this
axios.post('/login', {
firstName: 'Finn',
lastName: 'Williams'
})
.then((response) => {
swal({
text: "Product is already featured",
type: 'error',
confirmButtonColor: '#4fa7f3',
})
}
here you can use your response variable to check if is_featured true do something what you want

Laravel AJAX - How to show error in console.log

I want to show error, or to know why this code run in error:function()
Result is always run to error:function. I want to run success:function(data) and reload this page.
But console don't show anything about error.
https://imgur.com/ZubjYTc
https://imgur.com/mSfHnSR
====== Ajax ======
function ex_go(r_idx)
{
if(confirm("Are you sure?") == true)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:'POST',
dataType: 'JSON',
url: "{{ route('change-centerYn') }}",
data:{r_idx:r_idx},
success:function(data){
alert(data.success);
location.reload();
},
error:function(xhr, data){
console.log(xhr);
},
}else{
return false;
}
}
====== Controller ======
public function ex_ok(Request $request)
{
if(request()->ajax())
{
$r_idx = 'Hello';
var_dump('<pre>', $r_idx);
return response()->json(['msg'=>'Updated Successfully', 'success'=>true]);
}
}
Since you aren't using Try & Catch or error handling your controller will return 200 HTTP header status code, which means ajax will always think that process is correct and noting went wrong, try using error handling in your controller function and raise an exception if something went wrong during your code process. you can read at this link
you can see a sample code modification to your existing code below:
public function ex_ok(Request $request)
{
try
{
if(request()->ajax())
{
$r_idx = 'Hello';
var_dump('<pre>', $r_idx);
return response()->json(['msg'=>'Updated Successfully', 'success'=>true]);
}
}
catch(\Exception $e)
{
\Log::error($e); // create a log for error occurrence at storage/log/laravel.log file
return response()->json($e->getData(), $e->getStatusCode());
}
}
It's suddenly working! Unbelievable!
Thank you very much! You saved my morning!
Use try catch
========= AJAX ===========
function ex_go(r_idx)
{
if(confirm("해당 결제건을 지원센터로 보내시겠습니까?") == true)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log(r_idx);
$.ajax({
type:'POST',
dataType: 'JSON',
url: "{{ route('change-centerYn') }}",
data:{r_idx:r_idx},
success:function(data){
alert(data.success);
location.reload();
},
error:function(xhr, data){
console.log(xhr);
}
});
}else{
return false;
}
}
========= Laravel Controller =======
public function ex_ok(Request $request)
{
try
{
if(request()->ajax())
{
$r_idx = $request->r_idx;
$lecture = DB::table('class_order')
->select('*')
->where('r_idx', '=', $r_idx)
->first();
if ($lecture->r_oid != '') {
$insert_data = [
'r_oid' => $lecture->r_oid,
'r_user_id' => $lecture->r_user_id,
'r_name' => $lecture->r_name,
'r_tel' => $lecture->r_tel,
'r_hp' => $lecture->r_hp,
'r_email' => $lecture->r_email,
'r_zip' => $lecture->r_zip,
'r_addr1' => $lecture->r_addr1,
'r_addr2' => $lecture->r_addr2,
'r_class' => $lecture->r_class,
'r_enddate' => $lecture->r_enddate,
'app_endday' => $lecture->app_endday,
'whole_study' => $lecture->whole_study,
];
DB::table('ex_class_order')->insert($insert_data);
ClassOrder::where('r_idx', '=', $r_idx)->update(['centerYn' => 'y']);
$info_txt = "처리되었습니다.";
}
else
{
$info_txt = "처리실패";
}
return response()->json(['msg'=>'Updated Successfully', 'success'=>true]);
}
}
catch(\Exception $e)
{
\Log::error($e); // create a log for error occurrence at storage/log/laravel.log file
return response()->json($e->getData(), $e->getStatusCode());
}
}

Image is not validating: "The avatar must be an image"

I'm using a modal to preview an avatar. The even that triggers the modal is outside the ability to have a parent child structure so I have to pass the file object to my UpdateAvatar component.
Html
<avatar-update :image-blob="avatarFile" :show="avatarModalShow"
#close="avatarModalShow = !avatarModalShow"
:change-avatar="updateCrop"> </avatar-update>
Root Instance
data() {
return {
avatarModalShow: false,
avatarFile: null,
}
},
methods: {
onFileChange: function(e) {
this.avatarFile = e.target.files[0];
this.avatarModalShow = !this.avatarModalShow;
},
},
AvatarUpdate
export default {
props: ['show','imgUrl','changeAvatar','imageBlob'],
data() {
return {
image: null,
message: null,
internalImageObj: null
}
},
watch: {
changeAvatar: function(){
this.image = this.imgUrl;
},
imageBlob: function (newVal) {
let reader = new FileReader()
reader.readAsDataURL(newVal)
reader.addEventListener('load', () => {
this.internalImageObj = reader.result
}, false)
}
},
updated: function () {
this.image = this.imgUrl;
},
methods: {
close: function(){
this.$emit('close');
},
submitAvatar: function(){
const avatarFormData = new FormData();
avatarFormData.append('avatar', this.internalImageObj);
console.log(avatarFormData);
axios({
method: 'POST',
url: '/profile/avatar',
data: avatarFormData,
}).then(function (response) {
this.message = "Your avatar has been submitted";
}.bind(this))
.catch(function (error) {
console.log(error);
});
}
}
}
UserController
public function avatar(Request $request)
{
$request->validate([
'avatar' => 'image',
]);
return $request->all();
}
When I return $request->all(); in the avatar function with no validation on the UserController I'm getting this output: avatar:"data:image/png;base64,iVBORw0KGgoAAAANSUhSomeLongString
Error
{message: "The given data was invalid.", errors: {avatar: ["The avatar must be an image."]}}
errors
:
{avatar: ["The avatar must be an image."]}
avatar
:
["The avatar must be an image."]
0
:
"The avatar must be an image."
message
:
"The given data was invalid."
this is because your validation rule for avatar is image or mimes:jpeg,bmp,png this it will look for a file where the mime type is jpeg,bmp,png. but in your case your axios send it as a base64 which don't have a mime type. you need to include 'Content-Type': 'multipart/form-data' header in your axios object like this,
axios({
method: 'POST',
url: '/profile/avatar',
data: avatarFormData,
headers: {
'Content-Type': 'multipart/form-data'
}
})
hope this helps.

Download maatwebsite excel using ajax in laravel

I'm trying to download an excel file using ajax method in laravel.
Controller function:
$myFile = Excel::create($name, function ($excel) use ($export) {
$excel->sheet('Data', function ($sheet) use ($export) {
$sheet->fromArray($export);
$sheet->cells('A1:N1', function ($cells) {
$cells->setBackground('#dbdbdb');
$cells->setFontColor('#000000');
$cells->setFontWeight('bold');
$cells->setFont(array(
'family' => 'Calibri',
'size' => '9',
));
});
$sheet->setStyle(array(
'font' => array(
'name' => 'Calibri',
'size' => 9,
),
));
});
});
$myFile = $myFile->string('xlsx');
$response = array(
'name' => $name,
'file' => "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," . base64_encode($myFile),
);
return response()->json($response);
Ajax function:
$(document).on('click', '.ExportJobs', function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var ids = [];
$(".InvoiceCheckBox:checked").each(function(e) {
ids.push(this.value);
});
data = {
"ids": ids,
};
$.ajax({
method: "POST",
url: "/exportNew",
data: data,
success: function(response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
document.body.appendChild(a);
a.click();
a.remove();
}
});
});
But using above controller method is not returning excel formatted file if I change string value from xlsx to csv then csv formatted file is getting downloaded.
How do we make the excel formatted file downloaded? Any suggestions, Please!
I know this is quite late, but posting for others who struggle with same issue like me
I also needed to download excel from using Maatwebsite excel library by using ajax post call.
added a button to fire the ajax call to download excel file
<button onclick="downloadExcel()" id="btn-download-payroll" class="btn btn-dark-success btn-md" style="transform: translateY(50%); top: 50%; font-size: 13px;"><i aria-hidden="true" class="fa fa-cog mr-10"></i>
Download
</button>
Used following js code to post ajax request
function downloadExcel() {
var salaryMonth = $("#dp-salary-month").datepicker("getDate");
var department = $("#cbox-department");
var month = new Date(salaryMonth).getMonth() + 1;
var year = new Date(salaryMonth).getFullYear();
$.ajax({
xhrFields: {
responseType: 'blob',
},
type: 'POST',
url: '/downloadPayroll',
data: {
salaryMonth: month,
salaryYear: year,
is_employee_salary: 1,
department: department.val()
},
success: function(result, status, xhr) {
var disposition = xhr.getResponseHeader('content-disposition');
var matches = /"([^"]*)"/.exec(disposition);
var filename = (matches != null && matches[1] ? matches[1] : 'salary.xlsx');
// The actual download
var blob = new Blob([result], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
});
}
in routes/web.php file set the reoute for my controller
Route::post('/downloadPayroll', 'Payroll\\Process\\PayrollController#downloadPayroll');
Here I used maatwebsite/excel library to generate excel file with FromQuery approach but due to library update Excel::create has been replaced by Excel::download in "maatwebsite/excel": "^3.1" I used download method in my case here is my HelperClass to generate records according to my requirement
PayrollHelper.php
namespace App\Http\Helpers;
use App\PayrollEmployee;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\Exportable;
class PayrollHelper implements FromQuery
{
use Exportable;
public function forDepartment(int $department)
{
$this->department = $department;
return $this;
}
public function forMonth(string $month)
{
$this->month = $month;
return $this;
}
public function query()
{
// get the salary information for the given month and given department
return PayrollEmployee::query()->where(['salary_month' => $this->month,'department_id'=>$this->department]);
}
}
finally in my controller
class PayrollController extends Controller
{
public function downloadPayroll(Request $request)
{
$file_name = '';
try {
$requestData = $request->all();
$salary_month = $requestData['salaryMonth'];
$salary_year = $requestData['salaryYear'];
$department = $requestData['department'];
$is_employee_salary = boolval($requestData['is_employee_salary']);
$month = Carbon::createFromDate($salary_year, $salary_month);
$month_start = Carbon::parse($month)->startOfMonth();
$formated_month = Carbon::parse($month)->format('F Y');
$file_name = 'Employee_salary_' . $formated_month . '.xlsx';
// to download directly need to return file
return Excel::download((new PayrollHelper)->forMonth($month_start)->forDepartment($department), $file_name, null, [\Maatwebsite\Excel\Excel::XLSX]);
} catch (exception $e) {
}
}
}
After creating excel file return file to get as ajax response as blob
That's all
Just see the xhrFields to set responseType as blob and then see the ajax success part. Hope you everyone find the solution:
<script>
$(document).ready(function(){
$("#ExportData").click(function()
{
dataCaptureExport();
});
});
function dataCaptureExport(){
var FromDate = $('#dateFrom').val();
var ToDate = $('#dateTo').val();
var dataString = { FromDate: FromDate, ToDate:ToDate, _token: '{{csrf_token()}}'};
$.ajax
({
type: "POST",
url: '{{ route('invoice_details_export') }}',
data: dataString,
cache: false,
xhrFields:{
responseType: 'blob'
},
success: function(data)
{
var link = document.createElement('a');
link.href = window.URL.createObjectURL(data);
link.download = `Invoice_details_report.xlsx`;
link.click();
},
fail: function(data) {
alert('Not downloaded');
//console.log('fail', data);
}
});
}
It's late but help for others
You can do this way
In Ajax
$(document).on('click', '#downloadExcel', function () {
$("#downloadExcel").hide();
$("#ExcelDownloadLoader").show();
$.ajax({
url: '{{ route("admin.export_pending_submitted_tasks") }}',
method: "GET",
cache: false,
data: {
search_partner,
search_state,
search_city,
_token,
},
success: function (response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
document.body.appendChild(a);
a.click();
a.remove();
$("#downloadExcel").show();
$("#ExcelDownloadLoader").hide();
},
error: function (ajaxContext) {
$("#downloadExcel").show();
$("#ExcelDownloadLoader").hide();
alert('Export error: '+ajaxContext.responseText);
}
});
});
In Controller
// Get pending submitted tasks export excel
public function export_pending_submitted_tasks(Request $request){
$input = $request->input();
$pending_submitted_tasks = SubmittedTask::select('id', 'partner', 'se_id', 'description', 'created_at', 'status', 'updated_at');
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('partner_id', $input['search_partner']) : '';
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('state', 'like', '%'.$input['search_state'].'%') : '';
(isset($input['search_partner'])) ? $pending_submitted_tasks->where('city', 'like', '%'.$input['search_city'].'%') : '';
$pendingTaskList = $pending_submitted_tasks->where('status', 'pending')->get();
if($pendingTaskList->count() > 0):
$myFile = Excel::raw(new ExportPendingTaskHelper($pendingTaskList), 'Xlsx');
$response = array(
'name' => "Pending-Task-List.xlsx",
'file' => "data:application/vnd.ms-excel;base64,".base64_encode($myFile)
);
return response()->json($response);
else:
return back()->with('message', 'No Pending tasks available to download!!');
endif;
}
If you are using jquery:
// In controller:
return Excel::download(new SomeExport, 'Some_Report.xlsx', null, [\Maatwebsite\Excel\Excel::XLSX]);
// Ajax:
$.ajax({
type: 'GET',
url: '{{ route("some.route") }}',
data: {
"_token": "{{ csrf_token() }}"
},
xhrFields:{
responseType: 'blob'
},
beforeSend: function() {
//
},
success: function(data) {
var url = window.URL || window.webkitURL;
var objectUrl = url.createObjectURL(data);
window.open(objectUrl);
},
error: function(data) {
//
}
});

Does Vue.JS work with AJAX http calls?

I am trying to do the following from my HTML:
var vm = new Vue({
el: '#loginContent',
data: {
main_message: 'Login',
isLoggedIn: false,
loginError: '',
loginButton:'Login'
},
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
});
Basically user presses the login button, onLogin method is called that sends a post to my API. The post is working fine and I do get the response back in the .then() promise.
But, trying to do things like this.isLoggedIn = true; does not update my DOM with what I am expecting the HTML to do when the user logs in.
Could be that I am in some sort of background thread (sorry, mobile developer here) when I get the response in the promise and it can't find the "vm" instance?
Thanks
It is probably happening because your this is not pointing to correct scope, scope of this changes inside an $.ajax call, so you just have to do something like following:
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
var that = this
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
that.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
that.isLoggedIn = true;
} else {
that.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
I would propose another method use ES6 Arrow Functions like '=>'. It is simple and do not need extra variable.Like following:
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then((response) => {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
You might want to take a look at axios. I used $.ajax and got it working, but found axios and prefer axios over the ajax library.

Resources