I currently have my project working about 75% of the time, I create report/reports add them to a zip, unzip them to a certain location. When I run this in debug mode it works correctly. When i run it normally sometimes the ajax will run out of order and it will try to unzip the file before its zipped (nothing is there). I have been doing trial and error with this trying many different methods to get this to work.
I tried multiple ways to do this: with the success: of ajax. I tried a .done promise after ajax. I tried a bool : if statement I tried many different conditions. It seems to finally be working in the correct order when i first open the project and select the records and the button click. Only 1 time it will do it successful.
When I try to select new records and run it a 2nd time the unzip folder isnt always created Or if it'll be created but will be empty (No reports unzipped to it).
Here is what I currently have which sometime works. Once I have this going good then I have to create the last step which will be to create an email and attach the document.
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs" : arrSelectedChks },
success: function () {
window.location = '/Service/DownloadAsZip/';
// DownloadAsZip?mimeType=' + data;
},
error: function (request, status, error) {
alert("Error Generating Files");
//+ request.responseText);
}
}).done(function () {
$.ajax({
type: "POST",
url: "/Service/UnZipDownload",
data: {},
contentType: "application/json; charset=utf-8",
success: function (response) {
//alert("success in unzip");
CallEmail();
}
})
});
Here is another way i been doing this.
if (isValid) { /* At least 1 record is selected */
var phaseOne = $.ajax({
type: "GET",
async: false,
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs": arrSelectedChks },
success: function (response) {
window.location = '/Service/DownloadAsZip';
successful = true
},
complete: function () {
if (successful)
isZipped = true;
}
});
}
$.when(phaseOne).always(function () {
if (isZipped) { /* Files are Zipped to start this phase */
$.ajax({
type: "POST",
async: false,
url: "/Service/UnZipDocument",
data: {},
contentType: "application/json; charset=utf-8",
traditional: true,
});
}
})
P.S. I have both Controller Actions UnZipDownload and UnZipDocument (both similar) if needing to see the action i will post.
You have to call your the second function only if the first is successful
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs" : arrSelectedChks }
}).done(function(){
window.location = '/Service/DownloadAsZip/';
// DownloadAsZip?mimeType=' + data;
$.ajax({
type: "POST",
url: "/Service/UnZipDownload",
data: {},
contentType: "application/json; charset=utf-8"
}).done(function(){
//alert("success in unzip");
CallEmail();
});
}).fail(function(){
alert("Error Generating Files");
//+ request.responseText);
});
So I have tried SO MANY DIFFERENT results to try to get this to work with the click of 1 button. BUT the only way I have found out a way to get this to work is to have 1 button to do the report creating and zipping of the files. Then to have a second button (mines currently in a modal) and on this button click I am unzipping the file and creating the email. I have not been able to do everything all in 1 call. When I try my unzip functions is being called before my zip function I have tried many different ways to try to not have this happen [success, .done(), deferred objects, javascript promises]
$('#btnGetChkEmail').on('click', function() {
var arrChkBoxes = [];
var arrSelectedChks = [];
var myJSON = {};
var phaseOne, phaseTwo;
var isValid = false;
var bool = false;
var isZipped = false;
//var unZipped = false;
var successful = false;
// Turn all selected checkbox T/F values into QuoteIDs
$("input:checked").each(function (index, value) {
arrChkBoxes.push($(value).val());
});
// Push all Selected QIDs on NEW ARRAY
$.each(arrChkBoxes, function (key, value) {
if (IsPositiveInteger(value)) {
arrSelectedChks.push(value);
}
});
if (arrSelectedChks.length === 0) { // Create Modal (Error ~ None ~ Selected)
isValid = false;
alert("No Records Selected");
} else {
isValid = true;
}
/* EDITION LIKE GETCHKS */
if (isValid) {
$.ajax({
type: "GET",
url: "/Service/ExportFiles/",
contentType: "application/json; charset=utf-8",
traditional: true,
data: { "quoteIDs": arrSelectedChks },
success: function (response) {
window.location = '/Service/DownloadAsZip';
},
error: function (request, status, error) {
alert("Error Generating Reports");
}
}).done(function (data) {
/* Only way to do this 100% at the moment is to bring up a Button in a Modal */
var zipModal = $("#zipModEmail");
var modalHead = "<h3 class='modal-title'>Generate Email Messages</h3>";
var modalBody = "<span class='glyphicon glyphicon-ok-sign' style='font-size:5em; color:green;'></span>" +
"<p><b>Attach PDF's to email Confirmation</b></p>" +
"<p>Click 'OK' to Confirm</p>";
//var modalFoot = "";
zipModal.find(".modal-header").html(modalHead);
zipModal.find(".modal-header").addClass("alert-success");
zipModal.find(".modal-body").html(modalBody);
zipModal.modal("show");
});
}
$("#btnUnNemail").click(function (e) {
var myJSON = {};
var bool = false;
var ajaxCall = $.ajax({
type: "POST",
url: "/Service/UnZipDocument",
data: {},
contentType: "application/json; charset=utf-8",
success: function (response) {
debugger;
if (response.Status == "Unzipped") {
myJSON = { "Status": "Unzipped", "FilePath": response.FilePath, "FileName": response.FileName, "FileNames": response.FileNames };
bool = true;
}
$("#zipModEmail").modal("hide");
}
});
// Try switching to 'POST'
$.when(ajaxCall).then(function () {
if (bool) {
//debugger;
$.ajax({
type: "GET",
url: '#Url.Action("CreateEmailReport", "Service")',
contentType: "application/json; charset=utf-8;",
data: { "folderData": myJSON },
traditional: true,
})
}
});
});
Related
I want to get new value from controller and set it to view when form submit.
Controller:
public JsonResult GetVoucherNo()
{
var voucherno = 1001;
var lastvoucherno = db.PaymentsAndReceipts.Where(x => x.StakeHolder.StakeHolderType.Name == "Supplier").OrderBy(x => x.VoucherNo).ToList().LastOrDefault();
if (lastvoucherno != null)
{
voucherno = lastvoucherno.VoucherNo.GetValueOrDefault() + 1;
}
return new JsonResult { Data = voucherno, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
My Jquery function:
I just want to do when this function calls, I can get the value from controller action.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function () {
//don't know what to do here.
});
}
The data should be available in the done function argument like this:
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'Payments/GetVoucherNo',
dataType: "json"
}).done(function (result) {
//don't know what to do here.
console.log(result);
//you should see the exact JSON you return from the controller
});
}
I done it with success.
function getVoucherNo()
{
$.ajax({
contentType: 'application/json; charset=utf-8',
url: '/Payments/GetVoucherNo',
dataType: "json",
success: function (result) {
console.log(result);
return $('#VoucherNo').val(result); //to set value in textbox.
},
error: function (xhr, status, error) {
alert(xhr);
console.log(xhr, status, error);
}
});
}
I am writing CRUD application using ASP.NET MVC, KnockoutJS and database. When I write separate viewmodel for Create, Read, Update and Delete. and calling each view model in separate view (Create, Read, Update and Delete) then It's working fine. But when I include all view model in one single view model, then calling that view model in every View. Then I am neither able to create nor able to edit.
Please help me with this. I tried so many ways but could not get a proper solution.
I have written this function using Knockout:
$(function() {
ko.applyBindings(modelView);
});
Var parsedSelectedCourse = $.parseJSON(selectedCourse);
var modelView = {
Read: {
Courses: ko.observableArray([]),
viewCourses: function() {
var thisObj = this;
try {
$.ajax({
url: '/Home/ListCourses',
type: 'GET',
dataType: 'json',
contentType: 'application/json',
success: function(data) {
thisObj.Courses(data); //Here we are assigning values to KO Observable array
},
error: function(err) {
alert(err.status + " : " + err.statusText);
}
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Create: {
CourseName: ko.observable(),
CourseDescription: ko.observable(),
createCourse: function() {
try {
$.ajax({
url: '/Home/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this), //Here the data wil be converted to JSON
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Update: {
CourseID: ko.observable(parsedSelectedCourse.CourseID),
CourseName: ko.observable(parsedSelectedCourse.CourseName),
CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
updateCourse: function() {
try {
$.ajax({
url: '/Home/Update',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
},
Delete: {
CourseID: ko.observable(parsedSelectedCourse.CourseID),
CourseName: ko.observable(parsedSelectedCourse.CourseName),
CourseDescription: ko.observable(parsedSelectedCourse.CourseDescription),
deleteCourse: function() {
try {
$.ajax({
url: '/Home/Delete',
type: 'POST',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: successCallback,
error: errorCallback
});
} catch (e) {
window.location.href = '/Home/Read/';
}
}
}
};
function successCallback(data) {
window.location.href = '/Home/Read/';
}
function errorCallback(err) {
window.location.href = '/Home/Read/';
}
I have a website www.arabadukkan.com
I have cascading comboboxes at the top (araç türü->marka->model etc)
I am calling a webmethod to return the results but the result is the html of entire page.
This code works great in my local
WebMethod code :
public static string GetMarkas(string selectedId)
{
var items = Service.DS.GetMarkas().WithCategoryId(selectedId.SayiVer());
string donen = "<option value=''>Tüm Markalar...</option>";
foreach (var item in items) donen += string.Format("<option value='{0}'>{1}</option>", item.id, item.Title);
return donen;
}
I couldnt find any solution. When i look the network tab in chrome i see the GetMarkas response header is "Content-Type:text/html; charset=utf-8"
My script is :
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: $.toJSON(veriler),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
Try below code I guess u don't require json here..
function GetCombo(fromCombo, toCombo, method) {
var veriler = {
selectedId: $(fromCombo).val()
};
$(toCombo).find('option').remove().end().append("<option value='0'>Yükleniyor...</option>");
$.ajax({
type: "POST",
url: ResolveUrl('~/wm.aspx/') + method,
data: { selectedId : veriler},
dataType: 'html',
success: function (msg) {
$(toCombo).find('option').remove().end().append(msg.d);
$(toCombo).trigger("change");
},
error: function (msg, x, error) {
alert("Hata Oluştu." + error);
}
});
}
You may want to make sure that you've added necessary web.config entries, specifically httpModules section. Please go through this
why JSON doesn't work with html text (var text_html = '<p></p><t></t>'; ) but this will be work correct (var text_html = 'example';)
doesn't work
var text_html = JSON.parse('<p></p><t></t>');
Problem:
function Save() {
var text_html = '<p></p><t></t>';
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
My_Text: text_html
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
public JsonResult DodajTematSave(string My_Text)
{
return Json(new { Success = true});
}
also this doesn`t work
var dom_string = '<div>xxx<div>yyy</div></div>';
var text_html = dom_string.innerText();
also this doesn`t work
<script type="text/javascript">
function Save() {
var Temat_controll = $('#Temat').val();
var Streszczenie_controll = $.parseJSON('<p></p><t></t>');
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
try this:
var Streszczenie_controll = $.parseJSON('<p></p><t></t>');
and use ajaxSetup to instruct JQuery how to handle the data type
$.ajaxSetup({
contentType: "application/json; charset=utf-8",
dataType: "json"
});
Because those are escaping characters in JSON. You will have to parse html in a way to make it JSON friendly if you wanted it passed through JSON.
For this people who have problem with this I can show another way to fix this problem but very ugly click here
So here's the problem. I have three pages that make web service calls. The first time I land on the page and make the call it works fine, however if I switch to the second page it tries to make a web service call to the wrong service. Here's some info:
pages:
Page1.aspx - has Page1.js
Page2.aspx - has Page2.js
js files:
Page1.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page1.asmx/Page1FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page1List").html(html);
}
Page2.js
var filterCriteria = "";
function GetList() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2List",
contentType: "application/json; charset=utf-8",
data: "{'letter':'" + filterCriteria + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function GetSearchResults() {
$.ajax({
type: "POST",
url: "/webServices/Page2.asmx/Page2FilteredList",
contentType: "application/json; charset=utf-8",
data: "{'searchCriteria':'" + $("#Search").val() + "'}",
dataType: "json",
success: function (result) {
DisplayList(result.d);
}
});
}
function DisplayList(object) {
var html = '';
for (var i = 0; i < object.length; i++) {
//format results and append
}
if (object.length == 0) {
html += "<li class=\"filteredList\" style=\"padding: 10px;\">No Results Found</li>";
}
$("#Page2List").html(html);
}
So both have the same calls and the same information and the only real difference is that the results are different and they make a web service call to different web services that get different data.
Now each time that I switch between I get a new js file which is
jQuery-1.7.1.min.js/eval/seq/1
jQuery-1.7.1.min.js/eval/seq/2
jQuery-1.7.1.min.js/eval/seq/3
jQuery-1.7.1.min.js/eval/seq/4
depending on how many times I switch back an forth. Is there any way to stop the eval or is there something in my code that is causing the jQuery to store evals of the code I am using and what can I do to resolve it?
So the problem was that I was loading page transitions from jquery mobile. What was happening was that jquery mobile appends new page data to the DOM instead of forcing a page load. This was causing both javascript files to be loaded simultaneously meaning that which ever js file was loaded last was the primary and because both js files were calling functions with the same name it would load them multiple times.
Resolution
remove the $.mobile.load() event and force the click event to append the pathname to the url
$("#GoPage1").on("click", function () { window.location = "/dir/Page1.aspx"; });
$("#GoPage2").on("click", function () { window.location = "/dir/Page2.aspx"; });