What happened when ajax call Action and nothing happen - ajax

I need to pass values to Controller for making a PDF.
I create a Var Filter with many data, and other variable with respective necessesary.
When I call Controller, nothing happen.
I'm NOT an expert in MVC and AJAX.
Can someone help me?
View JavaScript:
function GeneratePdfUsuarios() {
var Filter = {
Nombre: $("#F_Nombre").val(),
Cargo: $("#F_Cargo").val(),
Iniciales: $("#F_Iniciales").val(),
UserName: $("#F_Usuario").val(),
Email: $("#F_Correo").val(),
Enabled: $("#EstadosList").val(),
BirthDay_Since: $("#F_Fecha_Desde").val(),
BirthDay_to: $("#F_Fecha_Hasta").val(),
RoleName: $("#RolesList").val(),
Sucursal: $("#SucursalesList").val()
};
var Title = "Usuarios";
var Description = "Listado de usuarios del sistema";
GeneratePdfList(1, Filter, Title, Description);
}
function GeneratePdfList(pDataCoType, pFilter, pTitle, pDescription) {
var token = $('[name=__RequestVerificationToken]').val();
var _data = {
DataCoType: pDataCoType //A number for Enumeration
, Filter: pFilter //An Object with Data
, Title : pTitle // Title for PDF
, Description: pDescription // Simple Description fpr Pdf
, __RequestVerificationToken: token
};
//ShowLoading();
$.ajax({
contentType: 'application/json; charset=utf-8'
,dataType: 'json',
url: "/Utility/GeneratePdfList",
type: 'POST',
data: _data,//JSON.stringify({ '_data': _data }),
success: function (data) {
if (data['success']) {
swal("Info","Entro","success");
//window.location.href = "#Url.Action("Usuarios", "Account")";
} else {
swal({
title: "Error!",
text: data['error'] + " !",
type: "warning",
timer: 100500,
allowOutsideClick: false,
allowEscapeKey: false,
showConfirmButton: true
});
swal("Peligro","Algo Fallo en el controlador "+e.Message,"warning");
//var message = document.createTextNode(data['error']);
//var p = $('#genericError')
//p.empty();
//p.append(message);
}
},
error: function () {
swal("Peligro", "Failed " + e.Message, "warning");
}
});
}
ActionResult in Controller:

Related

Data missing error when using Carbon::createFromFormat in laravel [dateFormat: year-month]

I'm getting "Data Missing" error when using Carbon to pass data to pdf view in Laravel.
The query work when the data is pass back to the same page with dropdown list but getting error when pass to another page.
the error that i get
I'm using date picker as my dropdown list & the date format that I'm using is:
"2020-December"
ajax:
changeMonth:true,
changeYear:true,
showButtonPanel:true,
dateFormat: "yy-MM",
onClose: function(dateText, inst) {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new Date(year, month, 1));
}
});
$('#convertBtn').click(function() {
var s = document.getElementById("sites");
var site = s.options[s.selectedIndex].text;
var startdate = $('#datepicker-8').val();
if(site != '' && startdate != '' )
{
$.ajax({
paging: false,
searching: false,
processing: true,
retrieve: true,
serverSide: true,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url:"{{ route('billing.bill') }}",
type:"GET",
dataType:"json",
data:{
site:site,
startdate:startdate,
},
success:function(data){
alert(JSON.stringify(data));
},
error: function(data){
alert('Error');
}
})
}
else
{
alert("Please select 'Site' & 'Date'. ");
}
});
controller
$sites['report_date'] = Carbon::createFromFormat('Y-F', $request->startdate);
$data = DB::table('monthly_data')
->where('site', $request->site)
->whereMonth('report_date', $sites['report_date'])
->whereYear('report_date',$sites['report_date'])
->get();
$pdf = \App::make('dompdf.wrapper');
$pdf -> loadView('pdf',compact('data'));
$pdf -> setPaper('a4','landscape');
return $pdf->stream('report.pdf');
may i know how to solve this error?
solution:
do some changes in ajax
data: {
site: site,
startdate: startdate,
},
xhrFields: {
responseType: 'blob' // to avoid binary data being mangled on charset conversion
},
success: function(blob, status, xhr) {
var ieEDGE = navigator.userAgent.match('/Edge/g');
var ie = navigator.userAgent.match('/.NET/g'); // IE 11+
var oldIE = navigator.userAgent.match('/MSIE/g');
if (ie || oldIE || ieEDGE) {
window.navigator.msSaveBlob(blob, fileName);
} else {
var fileURL = URL.createObjectURL(blob);
document.write('<iframe src="' + fileURL + '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>');
}
},
error: function(data) {
alert('Error');
}
remove dataType:"json"; and replace it with xhrFields: { responseType: 'blob'} then it works

merge ajaxform with ajax to upload image

I try to create upload photos in my nodejs site.
I used this code to choose file and upload the image:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
With loadfile funcion i choose my image, and with Uploadfile function i upload the image with ajax.
if i use it alone its work perfect and upload the image to the location.
but when i try to add this code to my code, it make alot of errors.
in my code i send to back end all the forms in the pug file:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
i try to merge the ajaxform with the ajax but when i merege the formdata or i send in ajaxform the data of the file is send error.
how can i merge the codes?
thanks for helping.
Try to submit form it will submit form with your image.
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
#Yogesh Patel
when i use this code:
$('#account-form-btn2').on('click', function(e) {
let form = $("#account-form");
$.ajax({
url: $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
error: function (e) {
if (e.responseText == 'title-empty') {
av.showInvalidTitle();
}
},
success: function (responseText, status, xhr, $form) {
if (status == 'success') {
$('.modal-alert').modal('show');
}
}
});
});
for some reason it sends the values to "routes" three times.
and it doesn't catch the erorrs or success.
and it sends me to a white window with the value of the callback.
if needed, i can send the function that gets the values and returns them (app.post).

ajax call returning promis and resolve it by the calling function to its value

By now i read somewhere around 6 pages containing documentations and stackoverflow answers but I don't get the method.
My function is by now after reading all the stuff built like this:
async function getFToken(postId){
const response = await $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data:{
action:'get_f_token',
postId: postId,
},
success:function(response) {
}
});
return response;
}
and in my other function is like this:
function getFeedback(postId){
$(".show_company").hide();
$(".show_feedback").show();
$.ajax({
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data:{
action:'get_feedback',
postId: postId,
},
success:function(response) {
var postTitle = '';
for (i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
var test = getFToken(387);
alert(Promise.resolve(test));
};
$("#result").html(postTitle);
}
});
}
is there any chance, that this is a bigger issue because i call a async in another Ajax call trying to retrieve the value? I'm trying to get the string from the first ajax call and hand it to the second function in the ajax call to attach it to the posts i retrieve from WordPress
The alert is giving me [object Promise] but how do i get the value passed from the php script?
php-scrtipt:
//get fToken from specific feedbacks
add_action( 'wp_ajax_get_f_token', 'get_f_token' );
function get_f_token() {
if(isset($_POST['postId'])){
$postId = $_POST['postId'];
}
$fToken = get_post_meta($postId, 'fToken', true);
echo $fToken;
wp_die();
}
Don't use success callbacks when you can use async/await:
async function getFToken(postId) {
return $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data: {
action: 'get_f_token',
postId: postId,
}
});
}
async function getFeedback(postId) {
$(".show_company").hide();
$(".show_feedback").show();
const response = await $.ajax({
// ^^^^^
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data: {
action: 'get_feedback',
postId: postId,
}
});
let postTitle = '';
for (const i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
const test = await getFToken(387);
// ^^^^^
alert(test); // no Promise.resolve, you don't want to alert a promise
}
$("#result").html(postTitle);
}

How to implement Antiforgerytokens with partial views in mvc4?

I am trying to implement antiforgerytoken in my project. I am able to implement it when making ajax call below.
function docDelete(id) {
var _upload_id = $("#docId").val();
var _comments = $("#name").val();
var forgeryId = $("#forgeryToken").val();
$("#dialog-form").dialog("open");
$.ajax({
type: 'GET',
cache: false,
url: '/DeleteDocument/Delete',
dataType: 'json',
headers: {
'VerificationToken': forgeryId
},
data: { _upload_id: _upload_id, _comments: _comments },
success: function (data) {
$('#dialog-form').dialog('close');
$('#name').val('');
$('#dvSuccess').val(data);
Getgridata(data);
}
});
}
above code works fine. But in some cases i am making ajax request as below.
var forgeryId = $("#forgeryToken").val();
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
headers: {
'VerificationToken': forgeryId
},
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}
Above code does not send any token to below method.
private void ValidateRequestHeader(HttpRequestBase request)
{
string cookieToken = string.Empty;
string formToken = string.Empty;
string tokenValue = request.Headers["VerificationToken"]; // read the header key and validate the tokens.
if (!string.IsNullOrEmpty(tokenValue))
{
string[] tokens = tokenValue.Split(',');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken); // this validates the request token.
}
}
In layout.cshtml i have implmented code to get token.
<script>
#functions{
public string GetAntiForgeryToken()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + "," + formToken;
}
}
</script>
<input type="hidden" id="forgeryToken" value="#GetAntiForgeryToken()" />
The variable tokenValue catching null each time. So what i understood is through headers i am not able to send token value. I tried many alternatives. So anyone suggest me how can i overcome this issue? Thank you in advance.
I tried as below still i am getting null value.
var token = $('[name=__RequestVerificationToken]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
alert(token);
var forgeryId = JSON.stringify($("#forgeryToken").val());
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
cache: false,
headers: headers,
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}

Ajax Form Submit with attachment

I have a Form on my Site thats submitted true ajax. This Form has a field where to attache .pdf files. How when submitting the form though the file is not send with the rest of data.
How can i get this to work?
Here is my ajax code:
$('#submit_btn').click(function () {
$.ajax({
type: 'POST',
url: '/contact.php',
dataType: "json",
data: $('#contactform').serialize(),
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});
On the php side i have phpmailer setup and am handling the file so:
if(!empty($_FILES['file'])) {
$_m->addAttachment($_FILES['file']['tmp_name'],$_FILES['file']['name']);
}
$('#submit_btn').click(function () {
var formData = new FormData($('#contactform'));
$.ajax({
type: 'POST',
url: '/contact.php',
// dataType: "json",
data: formData ,
processData: false,
contentType: false,
success: function (data) {
console.log(data.type);
console.log(data.msg);
var nClass = data.type;
var nTxt = data.msg;
$("#notice").attr('class', 'alert alert-' + nClass).text(nTxt).remove('hidden');
//reset fields if success
if (nClass != 'danger') {
$('#contactform input').val('');
$('#contactform textarea').val('');
}
}
});
return false;
});

Resources