Show toast notification after reloading - javascript

I want to show the a toast notification after the page is reloaded that says that the file is uploaded. This is what I got so far
_fileUploads.delete = function(reload_on_return) {
var filtered = root.fileUploads().filter(_ => _._id() == _fileUploads._id());
var index = root.fileUploads.indexOf(filtered = filtered[0]);
filtered = ko.toJS(filtered);
swal({
text: 'Are you sure you want to delete this file?',
buttons: true,
dangerMode: true,
icon: 'warning'
}).then(function (allowDelete) {
if (allowDelete) {
$.ajax({
type: 'DELETE',
url: '/api/gridfs/files/' + filtered._id,
statusCode: {
204: function(response) {
toastrTrigger('The File has been Deleted')
if (reload_on_return) {
setTimeout( function() {
location.reload();
}, 0001);
}
}
},
error: function (xhr, status, error) {
console.log(xhr);
}
});
}
});
}
This only refreshes the page and not show the notification
This is the toastrtrigger function()
function toastrTrigger(message, title, type) {
setTimeout(function() {
toastr.options = {
closeButton: true,
progressBar: true,
showMethod: 'slideDown',
timeOut: 4000
};
toastr[type || "success"](message, title || 'File Uploads Repository');
}, 500);
}

Scripts do not persist after the page has been reloaded: once the document is closed, all scripts associated with the document go away with it. There's no way around that. You'll have to somehow pass information to the page you navigate to purely through the URL.
One solution is to pass a query string to the reloaded page:
if (reload_on_return) {
window.location.href = window.location.pathname + '?deleteSuccess=1';
}
Then, on the same page, on page load, do a check to see if a query string are present:
const { search } = window.location;
const deleteSuccess = (new URLSearchParams(search)).get('deleteSuccess');
if (deleteSuccess === '1') {
// The page was just reloaded, display the toast:
toastrTrigger('The file has been deleted');
}
Another solution is to save the data in sessionStorage instead, and retrieve data from sessionStorage on page load to identify whether a notification should be displayed.

Related

AJAX enters data twice in database

I have a function where a user can a report a post, the user clicks the report button, and then promptly enters the information for the report. This works, the problem is if the page hasn't reloaded and the user decided to report a second post the data for that report enters the database twice. Why is this?
Here's the code:
$(document).ready(function() {
$(".report_post").click(function(e) {
var nid = $(this).attr("id");
$("#report_reason").dialog({
resizable: false,
height: 300,
width: 400,
modal: true,
});
$('.submit_report_post').click(function() {
var content = $("#report_content").val();
var type = "Post";
if ($('input[name="report"]:checked').length > 0 && (content != null &&
content != "")) {
var complaint = document.querySelector('input[name="report"]:checked').value;
alert('Reported!');
$.ajax({
type: 'POST',
url: 'php/report_post.php',
data: {
type: type,
nid: nid,
reason: complaint,
content: content,
},
cache: false,
success: function(data) {
$("#report_content").val("");
$("input[name='report']").prop('checked', false);
//$("#report_reason").dialog('close');
}
});
} else {
alert('Fill all of the information!');
}
});
e.preventDefault();
});
});
You're submitting your form twice, once the normal way and once via AJAX. You have e.preventDefault(); in your code which would normally stop the typical non-AJAX submission, however you never created the e argument.
Change:
$('.submit_report_post').click(function() {
to
$('.submit_report_post').click(function(e) {
and this will make the form only submit through the AJAX code.
You are binding click on $('.submit_report_post') every time you click on $(".report_post"), you need to do it outside of first bind
$(document).ready(function() {
$(".report_post").click(function(e) {
var nid = $(this).attr("id");
$("#report_reason").dialog({
resizable: false,
height: 300,
width: 400,
modal: true,
});
e.preventDefault();
});
$('.submit_report_post').click(function() {
var content = $("#report_content").val();
var type = "Post";
if ($('input[name="report"]:checked').length > 0 && (content != null &&
content != "")) {
var complaint = document.querySelector('input[name="report"]:checked').value;
alert('Reported!');
$.ajax({
type: 'POST',
url: 'php/report_post.php',
data: {
type: type,
nid: nid,
reason: complaint,
content: content,
},
cache: false,
success: function(data) {
$("#report_content").val("");
$("input[name='report']").prop('checked', false);
//$("#report_reason").dialog('close');
}
});
} else {
alert('Fill all of the information!');
}
});
});

How to add headers at runtime in fine uploader

I am using fine uploader for uploading file on server, For this I need to make 2 web api calls.
On button click, First web api saving value and returning result in integer, and I need to pass that integer result in header for each file while uploading.
But I am not able to pass values in headers,
code,
uploader = new qq.FineUploader({
element: $('#manual-fine-uploader1')[0],
request: {
endpoint: Url.AddEvaluationFiles,
},
autoUpload: false,
text: {
uploadButton: '<i class="icon-plus icon-white"></i> Select Files'
},
debug: true,
callbacks: {
onSubmit: function (id, fileName) {
},
onStatusChange: function (id, oldStatus, newStatus) {
if (newStatus == "uploading") {
alert("Add header");
}
},
onUpload: function (id, name) {
alert("Onupload");
this.append("RequestId", $("#ReqId").val());
}
}
});
I am calling upload function in success block of first request,
$.ajax({
type: "POST",
url: Url.Details,
data: fileData,
async: false,
success: function (result) {
if (result == 0) {
toastr.error("Please pass user id");
} else {
$("#ReqId").val(result);
alert($("#ReqId").val());
uploader.uploadStoredFiles();
}
},
error: function (err) {
toastr.error("Not able to upload art details");
}
});
Here I want to pass RequestId header in onUpload event, but it's not working, What changes I need to make to make it happen.
The request option has a customHeaders property, that allows you to set any custom header.
Your constructor call should look something like
artistmanualuploader = new qq.FineUploader({
...
request: {
endpoint: "FoaUrl.AddEvaluationFiles",
customHeaders: {
"EvaluationRequestId": $("#CurrentEvaluationReqId").val()
}
},
...
});

Google api authentication window closed callback

I'm trying to get the contacts from google using javascript api:
$(document).on('click', '#connect_to_google', function() {
$('body').addClass('loading');
var config = {
client_id: GOOGLE_CP_CIENT_ID,
scope: 'https://www.google.com/m8/feeds'
};
gapi.auth.init(function() {
gapi.auth.authorize(config, function() {
var token = gapi.auth.getToken();
if (null !== token && (typeof token.access_token !== 'undefined')) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json&v=3.0",
dataType: "json",
cache: false,
success: function(data) {
//doStuff(data);
$('body').removeClass('loading');
},
error: function (xhr, error) {
$('body').removeClass('loading');
},
complete: function (xhr, error) {
$('body').removeClass('loading');
}
});
} else {
$('body').removeClass('loading');
}
});
});
});
The moment the client clicks the login button, the page displays a layer over it ($('body').addClass('loading');), to restrict any user interaction outside google auth page.
All works well, except for the situation when the user closes the google auth window manually, then nothing happens.
Is there any way to check if the user closed that window, to call the $('body').removeClass('loading');?
Or is there any way to open the gapi.auth.authorize window in a modal dialog container? That way I could very easy check it's status.
This seems to do the trick:
(function(wrapped) {
window.open = function() {
var win = wrapped.apply(this, arguments);
var i = setInterval(function() {
if (win.closed) {
clearInterval(i);
$('body').removeClass('loading');
}
}, 100);
};
})(window.open);
It's not the best solution, but it does the work

How to save a variable to the server using jQuery

I am implementing a video conference room and I have a variable (room_status) which holds the status of the room (0 = close & 1 = open). Now this variable is only accessible my the client who clicks open-room.
I need to save the room_status variable to the server so that it can be accessed on other client's side. Here is a piece of my code:
var room_status = 0; //room closed
$('#open-room').click(function () {
// http://www.rtcmulticonnection.org/docs/open/
$.ajax({
type: 'GET',
url: "../invite",
data: {
videoconference_id: $('#meetingID').val(),
invitee_id: 1111,
status: "Accepted"
},
success: function() {
alert("success!");
},
error: function() {
alert("fail");
}
});
//room_status = 1; //room opened
rmc.open();
rmc.streams.mute({video : true});
document.getElementById("on-off-video").style.color= 'red';
});
$('#join-room').click(function () {
if(room_status) {
// http://www.rtcmulticonnection.org/docs/connect/
rmc.connect();
rmc.streams.mute({video: true});
document.getElementById("on-off-video").style.color= 'red';
} else {
console.log("Waiting for meeting organizer");
}
});
Ajax is your friend.
Here is an example from a prject of mine with jquery ui :
function prepare_ajax_button(l){
$("#button").button().click(function(event,ui){
$.ajax({type: "GET",data: {"arg1":l},url: "update_variable.php",success: function(data){
alert("Success ?!");
},error: function(data){alert("Problem ?!");}});
});
}
The page "update_variable.php" can for instance write the variable in a text file, mysql...

Kendo Grid C# - Select current page without refresh datasource again

i have been trying to fix this, what i want to do is:
I have a datasource who gets data from server, when i go to server, i get the list of items, then i have to search the item i have to select (This item could be in any page), after i have the item and the page where the item is located (assuming each page has 30 items), then i call LINQ expression to skip the required ammount of data and take 30. Finally i return this list to the client side.
When data arrives to client i need to "auto-select" the selected item and change the page to locate the user in the right page where the selected item is located. I have the new page, skip, selected value and everything in the client side again.
What do you suggest to me to change the page into the kendo grid datasource without call a new refresh and go to the server again?
This is how the datasource looks like:
return new kendo.data.DataSource({
serverPaging: true,
transport: {
read: {
url: URLController.Current().getURL('MyURL'),
contentType: 'application/json',
accepts: 'application/json',
type: 'POST'
},
parameterMap: function(data, type) {
if (data) {
return JSON.stringify(
{
data: jsonData,
pageSize: data.pageSize,
skip: data.skip,
take: data.take
});
}
}
},
schema: {
data: function (data) {
var dropDownData = JSON.parse(data);
gridElement.attr('data-model', JSON.stringify({ data: data }));
return dropDownData.Data;
},
total: function (data) {
var dropDownData = JSON.parse(data);
return dropDownData.total;
},
model: {
id: 'ID'
}
},
pageable: true,
pageSize: 30,
error: function(e) {
alert('Error ' + e);
}
});
When the grid data is bounded i have to change the page to current page number and then select the current item.
grid.one('dataBound', function (e) {
var currentGridElement = this.element;
var currentModel = currentGridElement.attr('data-model');
var currentJsonData = parseDropDownDataJSONString(currentModel).data;
var gridDataSource = this.dataSource;
var selection = gridDataSource.get(currentJsonData.selectedValue);
if (selection != undefined) {
var row = currentGridElement.find('tbody>tr[data-uid=' + selection.uid + ']');
if (row != undefined) {
currentGridElement.attr('data-closeByChange', false);
gridDataSource.page(currentJsonData.pageNumber);
this.select(row);
dexonDropDownGrid.combobox().text(selection.DISPLAY);
}
}
var aaaa = 0;
});
This is how my databound event listener looks like, when i try to set the page it calls again the server and i got more delay to load the right data.
Is there any way to solve this?
Thanks
Have the same problem.
There is how I fix that(not the best solution ever, but it works):
var forcedPageChange = false;
var cachedResult;
var dataSource = new kendo.data.DataSource({
transport: {
read: function (options) {
if (forcedPageChange) { // prevent data request after manual page change
forcedPageChange = false;
options.success(cachedResult);
cachedResult = null;
return;
}
gridDataProvider.getData() // promise of data
.then(function (result) {
// check if current page number was changed
if ($scope.gridConfig.dataSource.page() !== result.pageNumber ||
$scope.gridConfig.dataSource.pageSize() !== result.rowsPerPage) {
cachedResult = _.clone(result);
forcedPageChange = true;
options.page = result.pageNumber;
options.pageSize = result.rowsPerPage;
$scope.gridConfig.dataSource.query(options);
}
options.success(result);
}, function () {
options.error();
});
}
},
schema: {
data: function (response) {
return response.items;
},
total: function (response) {
return response.totalCount;
}
},
//...
serverPaging: true,
serverSorting: true,
serverFiltering: true
});
I found that dataSource.page(newPageNumber) doesn't work in this situation. It just drop page number to 1.
This solution works, but I still have a bug with missing sorting icon after dataSource.query(options)...

Categories

Resources