Google Script to empty emails in trash folder - javascript

I was using the below google app script to delete emails automatically from my trash folder. for some reason, this is no longer deleting the emails however the trigger dashboard shows the script executed successfully. can someone help to modify the script ? thanks in advance.
function removeMyTest2() {
var mymail = "me";
var mylabel = "del";
var permanentlyRemoveMyLabel = true;
var pageToken;
do {
var threadList = Gmail.Users.Threads.list('me', {
q: 'in:trash' + mylabel,
pageToken: pageToken
});
if (threadList.threads && threadList.threads.length > 0) {
threadList.threads.forEach(function(thread) {
Logger.log('id: %s snippet: %s', thread.id, thread.snippet);
if (permanentlyRemoveMyLabel) {
Gmail.Users.Threads.remove(mymail, thread.id);
Logger.log('id: %s snippet: %s REMOVED', thread.id, thread.snippet);
}
});
}
pageToken = threadList.nextPageToken;
} while (pageToken);
}

Try this:
I believe you were missing the label key.
function removeMyTest2() {
var pageToken=null;
do {
var threadList=Gmail.Users.Threads.list('me', {q:'in:trash label:del',pageToken:pageToken});
if (threadList.threads && threadList.threads.length>0) {
threadList.threads.forEach(function(thread) {
Gmail.Users.Threads.remove("me", thread.id);
});
}
pageToken=threadList.nextPageToken;
} while (pageToken);
}
I tested this with another label and it works fine
I needed this scope: https://mail.google.com/

Related

onComplete in AjaxUpload getting before server side code hits

I am working on some legacy code which is using Asp.net and ajax where we do one functionality to upload a pdf. To upload file our legacy code uses AjaxUpload, but I observed some weird behavior of AjaxUpload where onComplete event is getting called before actual file got uploaded by server side code because of this though the file got uploaded successfully still user gets an error message on screen saying upload failed.
And here the most weird thins is that same code was working fine till last week.
Code:
initFileUpload: function () {
debugger;
new AjaxUpload('aj-assetfile', {
action: '/Util/FileUploadHandler.ashx?type=asset&signup=False&oldfile=' + assetObj.AssetPath + '&as=' + assetObj.AssetID,
//action: ML.Assets.handlerPath + '?action=uploadfile',
name: 'AccountSignupUploadContent',
onSubmit: function (file, ext) {
ML.Assets.isUploading = true;
ML.Assets.toggleAsfMask(true);
// change button text, when user selects file
$asffile.val('Uploading');
$astfileerror.hide();
// If you want to allow uploading only 1 file at time,
// you can disable upload button
this.disable();
// Uploding -> Uploading. -> Uploading...
ML.Assets.interval = window.setInterval(function () {
var text = $asffile.val();
if (text.length < 13) {
$asffile.val(text + '.');
} else {
$asffile.val('Uploading');
}
}, 200);
//if url field block is visible
if ($asseturlbkl.is(':visible')) {
$asfurl.val(''); //reset values of url
$asfurl.removeClass('requiref error'); //remove require field class
$asfurlerror.hide(); //hide errors
}
},
onComplete: function (file, responseJSON) {
debugger;
ML.Assets.toggleAsfMask(false);
ML.Assets.isUploading = false;
window.clearInterval(ML.Assets.interval);
this.enable();
var success = false;
var responseMsg = '';
try {
var response = JSON.parse(responseJSON);
if (response.status == 'success') { //(response.getElementsByTagName('status')[0].textContent == 'success') {
success = true;
} else {
success = false;
responseMsg = ': ' + response.message;
}
} catch (e) {
success = false;
}
if (success) {
assetObj.AssetMimeType = response.mimetype;
$asffile.val(response.path);
$asffile.valid(); //clear errors
ML.Assets.madeChanges();
if (ML.Assets.saveAfterUpload) { //if user submitted form while uploading
ML.Assets.saveAsset(); //run the save callback
}
} else { //error
assetObj.AssetMimeType = "";
$asffile.val('');
$astfileerror.show().text('Upload failed' + responseMsg);
//if url field block is visible and type is not free offer.
if ($asseturlbkl.is(':visible') && this.type !== undefined && assetObj.AssetType != this.type.FREEOFFER) {
$asfurl.addClass('requiref'); //remove require field class
}
ML.Assets.hideLoader();
}
}
});
}
I was facing the same issue but I fixed it with some minor change in plugin.
When “iframeSrc” is set to “javascript:false” on https or http pages, Chrome now seems to cancel the request. Changing this to “about:blank” seems to resolve the issue.
Old Code:
var iframe = toElement('<iframe src="javascript:false;" name="' + id + '" />');
New Code with chagnes:
var iframe = toElement('<iframe src="about:blank;" name="' + id + '" />');
After changing the code it's working fine. I hope it will work for you as well. :)
Reference (For more details): https://www.infomazeelite.com/ajax-file-upload-is-not-working-in-the-latest-chrome-version-83-0-4103-61-official-build-64-bit/

Ajax posting on localhost but not on VPS host

I've been facing this issue for many days i've searched the whole internet fixed my php.ini even the ngnix.confg file
Please tell me if anything is wrong with the code
i've edited the Cropper Plugin not to download but replace the current image.
so what i did i used the ajax post to do it.
PS: Ajax is sending huge data in post since it's a canvas and this whole process is working fine on localhost but not working on server. The whole site is on laravel but this code is on native php.
I've also figured out that if image is small then it's working fine and if image is large then it's not working on server.
AJAX code in main.js file
$('.docs-buttons').on('click', '[data-method]', function () {
var $this = $(this);
var data = $this.data();
var $target;
var result;
if ($this.prop('disabled') || $this.hasClass('disabled')) {
return;
}
if ($image.data('cropper') && data.method) {
data = $.extend({}, data); // Clone a new one
if (typeof data.target !== 'undefined') {
$target = $(data.target);
if (typeof data.option === 'undefined') {
try {
data.option = JSON.parse($target.val());
} catch (e) {
console.log(e.message);
}
}
}
if (data.method === 'rotate') {
$image.cropper('clear');
}
result = $image.cropper(data.method, data.option, data.secondOption);
if (data.method === 'rotate') {
$image.cropper('crop');
}
switch (data.method) {
case 'scaleX':
case 'scaleY':
$(this).data('option', -data.option);
break;
case 'getCroppedCanvas':
if (result) {
var temp = $(' #image').attr('src');
jQuery.ajax({
url: '../../cropper/demo/save.php',
type: 'POST',
data: {
data: result.toDataURL('image/jpeg'),
name: temp,
},
complete: function(data, status)
{
console.log(data.responseText);
if(status=='success')
{
$('#image').cropper("replace", temp);
}
else
{
alert('Error has been occurred');
}
}
});
}
break;
}
if ($.isPlainObject(result) && $target) {
try {
$target.val(JSON.stringify(result));
} catch (e) {
console.log(e.message);
}
}
}
});
save.php (To store the image on server)
<?php
$based64Image=substr($_POST['data'], strpos($_POST['data'], ',')+1);
$fileName='';
$fileName = substr($_POST['name'], 34);
$image = imagecreatefromstring(base64_decode($based64Image));
if($image != false)
{
if(!imagejpeg($image,"..\..\images\image\\".$fileName))
{
// fail;
}
}
else
{
// fail;
}
?>
Please Help Thanks
Add the following to your conf file
fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
For more details and understanding please read
https://gist.github.com/magnetikonline/11312172#determine-fastcgi-response-sizes
These results may not be accurate, so reading to ensure your proper configuration is advised

jQuery HTTP Post stopped working, only works when long strings are input

Quick background: Very new to web development. I have a bootstrap page with a form which users can fill out. There are four fields (two text boxes, one radio, one dropdown). The idea was to form a JSON using that input data and POST it to my HTTP server, but it doesn't seem to be working anymore.
Very strange, my code was working perfectly a few hours ago (have been testing with requestb.in).
Now all of a sudden it (1) only sends the POST if I have long values for the apiname and apiurl variables, and (2) no longer sees what I've chosen from the radio checkboxes (env1 - env3), and instead always thinks I've chosen 'Dev,' regardless of what was actually selected.
I'm assuming my issues are caused by the jQuery in my code and not the HTML, so I've attached that here:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$("button").click(function(){
var env1 = document.getElementById("seldevid");
var env2 = document.getElementById("selstageid");
var env3 = document.getElementById("selprodid");
var apiname = $("#apinameid").val();
var apiurl = $("#apiurlid").val();
var actionvar;
$("#actionid").change(function() {
actionvar = $(this).val();
}).change();
if (env1.checked = true) {
var env = "Dev";
} else if (env2.checked = true) {
var env = "Stage";
} else if (env3.checked = true) {
var env = "Prod";
}
$.post("http://requestb.in/107fmof1",
{
apiName: apiname,
apiURL: apiurl,
environment: env,
action: actionvar
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
Thanks for the help!
First Question: Why Always "Dev"?
The issue is in your if statements you have used an assignment, rather than a boolean comparison. You need to use == to compare the two values for equality. Instead you are setting env1.checked = true, which evaluates to true, so env is always being set to "Dev".
if (env1.checked == true) {
var env = "Dev";
} else if (env2.checked == true) {
var env = "Stage";
} else if (env3.checked == true) {
var env = "Prod";
}
or even
var env;
if (env1.checked) {
env = "Dev";
} else if (env2.checked) {
env = "Stage";
} else if (env3.checked) {
env = "Prod";
}
Second Question: Why not posting?
You should try simplifying your code a bit:
$(document).ready(function(){
var env1 = document.getElementById("seldevid");
var env2 = document.getElementById("selstageid");
var env3 = document.getElementById("selprodid");
$("button").click(function(){
var env = "Dev";
if (env2.checked) {
env = "Stage";
} else if (env3.checked) {
env = "Prod";
}
$.post("http://requestb.in/107fmof1",
{
apiName: $("#apinameid").val(),
apiURL: $("#apiurlid").val(),
environment: env,
action: $("#actionid").val()
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
}
);
});
});
Then using the browser Developer Tools to see what exactly is being POST'd, if anything.

How to check if page is published

to check if page is published using server side code i should use this snippet:
PublishingPageCollection pages = PublishingWeb.GetPublishingWeb(web).GetPublishingPages();
foreach (PublishingPage page in pages)
{
if(!page.ListItem.File.Level == SPFileLevel.Published)
return;
// logic
}
How could i do the same but using Javascript in SharePoint?
According to SP.Publishing.PublishingWeb Methods the method GetPublishingPages is not supported in JSOM API.
But you could consider the following example to determine whether page is published or not using JSOM API
function getPublishingPages(success,error)
{
var ctx = SP.ClientContext.get_current();
var list = ctx.get_web().get_lists().getByTitle('Pages');
var items = list.getItems(SP.CamlQuery.createAllItemsQuery());
ctx.load(items,'Include(File)');
ctx.executeQueryAsync(function() {
success(items);
},
error);
}
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function() {
getPublishingPages(printPagesInfo,logError);
});
function printPagesInfo(pages)
{
pages.get_data().forEach(function(item){
var file = item.get_file();
var pageStatus = file.get_level() === SP.FileLevel.published ? 'published' : 'not published';
console.log(String.format('Page {0} is {1}', file.get_name(),pageStatus));
});
}
function logError(sender,args){
console.log('An error occured: ' + args.get_message());
}

asynchronous HTTP (ajax) request works in script tag but not in js file

I have this ajax call here in a script tag at the bottom of my page. Everything works fine! I can set a breakpoint inside the 'updatestatus' action method in my controller. My server gets posted too and the method gets called great! But when I put the javascript inside a js file the ajax call doesn't hit my server. All other code inside runs though, just not the ajax post call to the studentcontroller updatestatus method.
<script>
$(document).ready(function () {
console.log("ready!");
alert("entered student profile page");
});
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById("enumstatus");
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
</script>
Now I put this at the bottom of my page now.
#section Scripts {
#Scripts.Render("~/bundles/studentprofile")
}
and inside my bundle.config file it looks like this
bundles.Add(new ScriptBundle("~/bundles/studentprofile").Include(
"~/Scripts/submitstatus.js"));
and submitstatus.js looks like this. I know it enters and runs this code because it I see the alert message and the background color changes. So the code is running. Its just not posting back to my server.
$(document).ready(function () {
console.log("ready!");
alert("submit status entered");
var statusdropdown = document.getElementById('enumstatus');
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById('enumstatus');
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
});
In the console window I'm getting this error message.
POST https://localhost:44301/Student/#Url.Action(%22UpdateStatus%22,%20%22Student%22) 404 (Not Found)
Razor code is not parsed in external files so using var id = "#Model.StudentId"; in the main view will result in (say) var id = 236;, in the external script file it will result in var id = '#Model.StudentId'; (the value is not parsed)
You can either declare the variables in the main view
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
and the external file will be able to access the values (remove the above 2 lines fro the external script file), or add them as data- attributes of the element, for example (I'm assuming enumstatus is a dropdownlist?)
#Html.DropDownListFor(m => m.enumStatus, yourSelectList, "Please select", new { data_id = Model.StudentId, data_url = Url.Action("UpdateStatus", "Student") })
which will render something like
<select id="enumStatus" name="enumStatus" data-id="236" data-url="/Student/UpdateStatus">
Then in the external file script you can access the values
var statusbubble = $('#statusbubble'); // cache this element
$('#enumStatus').change(function() {
var id = $(this).data('id');
var url = $(this).data('url');
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
....
});
// suggest you add/remove class names instead, but if you want inline styles then
if (status == someValue) { // the value of the first option?
statusbubble.css('backgroundColor', '#3fb34f');
} else {
statusbubble.css('backgroundColor', '#b23f42');
};
});

Categories