Problem displaying error to the user from AJAX - html

Am using AJAX code whereby I handle errors form the backend code.. All is working well except that I want to alert the errors individually to the user in a numbered list
Expected Output
1. Please insert a valid phone number
2. Please insert your email
3. Please insert a valid passport number
AJAX code handling errors
error: function(data) {
//Unblock the spinner
$.unblockUI();
var errors = '';
for(datos in data.responseJSON){
errors += data.responseJSON[datos] + '<br>';
}
//Alert each error individually
alert(errors);
}

I would recommended that you should be using a for loop instead of for in. See why here
error: function(data) {
//Unblock the spinner
$.unblockUI();
var errors = '';
for(var i = 0; i < data.responseJSON.length; i++){
// Remove the "(i+1) + '. ' + " if your json response already contains that part.
errors += (i+1) + '. ' + data.responseJSON[i] + '\n'; // <-- Notice how the br tag is changed to a new line
}
alert(errors)
}
I also changed the <br> tag to a \n as alerts don't support html tags.

It is not clear to me from the question, whether you want a
multiline alert message or
multiple alert dialogs as the
output,
but in case 1) is true, you should use newline ("\n") instead of br tag - see New line in JavaScript alert box and the code could look like:
var i = 1,
errors = '';
for(datos in data.responseJSON){
errors += i + '. ' + data.responseJSON[datos] + '\n';
i++;
}
//Alert each error individually
alert(errors);
If 2) is what you need, you should call alert() for each error message

Related

How to program a URL? (For search query)

A co-worker of mine shared an autohotkey script (it's actually an exe file that runs on the background). Anyways, when I click the hotkeys it opens up a company webiste and creates a shared query for whatever's on the clipboard. I was wondering how this is done and how I can make my own.
I'm specially curious about the "URL" modification that includes all these search options:
https://<COMPANYWEBSITE>/GotoDocumentSearch.do
That's the URL where I can search (sorry it's restricted and even if I link it you cant access it).
Anyways, after I set up all my options and stuff and click the search button I get the following URL:
https://<COMPANYWEBSITE>/DocumentSearch.do
I inspected the website source and this is the function that's called when I press the search button:
function preSubmitSearch(docPress) {
document.pressed = docPress;
// setup local doc types for submit by lopping over multi selects and building json data string
var localDocTypesJson = "{";
var sep = "";
jQuery(".localTypeSel").each(function (i) {
var selLocalTypes = jQuery(this).multiselect("getChecked");
// get doc type code from id ex. 'localTypeSel_PD'
//window.console.log("this.id=" + this.id);
var tmpArr = this.id.split("_");
var docTypeCode = tmpArr[1];
var selLocalTypesCnt = selLocalTypes.length;
if (selLocalTypesCnt > 0) {
var localTypes = "";
var sep2 = "";
for (var i2 = 0; i2 < selLocalTypesCnt; i2++) {
localTypes += sep2 + "\"" + selLocalTypes[i2].value + "\"";
sep2 = ",";
}
localDocTypesJson += sep + "\"" + docTypeCode + "\": [" + localTypes + "]";
sep = ",";
}
});
localDocTypesJson += "}";
jQuery("#localDocTypesJson").val(localDocTypesJson);
}
HOWEVER, the working code that was shared with me (that was written ages ago by some employee who's not here anymore). Has the following URL when I use the autohotkey:
https://<COMPANYWEBSITE>/DocumentSearch.do?searchType=all&localDocTypesJson=7D&formAction=search&formInitialized=true&searchResultsView=default&btn_search=Search&docName=*<CLIPBOARD>*&wildcards=on&docRevision=&latestRevOnly=true&docProjectNumber=&docEngChangeOrder=&docLocation=&findLimit=500&docTypes=Customer+Drawing&docTypes=Production+Drawing&docTypes=Manufacturing+Process+Document&docTypes=Specification+Or+Standard
Note: replaced text with "CLIPBOARD" for clarification.
I was wondering if that's a type of "URL-programming" or how can I make a direct URL that prompts for the search results from the website? is that Javascript? or how is that programmed? (I know Swift and some Java, but have never really used Javascript).
It doesn't seem like you are asking an AutoHotKey (AHK) question, but to give you an AHK example you can copy, here is how I would use AHK to use Google.com to search for whatever is in my clipboard:
wb := ComObjCreate("InternetExplorer.Application")
wb.Visible := true
wb.Navigate("https://www.google.com/search?q=" . StrReplace(Clipboard, " ", "+") . "", "")
Note, the URL format includes the query ("?q=whatever+you+had+in+Clipboard") in it with spaces replaced by "+"s.
Hth,

Trouble Adding Array output to an Dynamically Generated HTML String in GAS Google Script

I am trying to automate my businesses blog. I want to create a dynamic html string to use as a wordpress blog description. I am pulling text data from email body's in my gmail account to use as information. I parse the email body using the first function below.
I have everything working properly except for the for loop (in the second code block) creating the description of the post. I have searched for hours and tried dozens of different techniques but I cant figure it out for the life of me.
Here is how I am reading the text values into an array:
function getMatches(string, regex, index) {
index || (index = 1); // default to the first capturing group
var matches = [];
var match;
while (match = regex.exec(string)) {
matches.push(match[index]);
}
return matches;
}
This is how I am trying to dynamically output the text arrays to create a basic HTML blogpost description (which I pass to xmlrpc to post):
var1 = getMatches(string, regex expression, 1);
var2 = getMatches(string, regex expression, 1);
var3 = getMatches(string, regex expression, 1);
var3 = getMatches(string, regex expression, 1);
var fulldesc = "<center>";
var text = "";
for (var k=0; k<var1.length; k++) {
text = "<u><b>Var 1:</u></b> " + var1[k] + ", <u><b>Var 2:</u></b> " + var2[k] + ", <u><b>Var 3:</u></b> " + var3[k] + ", <u><b>Var 4:</u></b> " + var4[k] + ", <br><br>";
fulldesc += text;
}
fulldesc += "</center>";
Lastly here is the blog post description code (using GAS XMLRPC library):
var fullBlog = "<b><u>Headline:</u> " + sub + "</b><br><br>" + fulldesc + "<br><br>General Description: " + desc;
var blogPost = {
post_type: 'post',
post_status: 'publish', // Set to draft or publish
title: 'Ticker: ' + sub, //sub is from gmail subject and works fine
categories: cat, //cat is defined elsewhere and works fine
date_created_gmt: pubdate2, //defined elsewhere (not working but thats another topic)
mt_allow_comments: 'closed',
description: fullBlog
};
request.addParam(blogPost);
If there's only one value in the var1,2,3,4 arrays all works as it should. But any more than 1 value and I get no output at all from the "fulldesc" var. All other text variables work as they should and the blog still gets posted (just minus some very important information). I'm pretty sure the problem lies in my for loop which adds the HTML description to text var.
Any suggestions would be greatly appreciated, I'm burned out trying to get the answer! I am a self taught programmer (just from reading this forum) so please go easy on me if I missed something stupid :)
Figured it out: It wasnt the html/text loop at all. My blogpost title had to be a variable or text, but not both.
Not working:
title: 'Ticker: ' + sub, //sub is from gmail subject and works fine
Working:
var test = 'Ticker: ' + sub;
//
title:test,

How to deal with information received in two packets

This is the case. I want to make a game, client being made in flash and server on java. From server side, the first byte i write on the stream is the protocol id, like this:
try
{
Output.writeByte(LOGIN);
Output.writeByte((byte)ID);
Output.writeByte(new_position.x);
Output.writeByte(new_position.y);
Output.flush();
}
After the 'onResponse' event is triggered, the socket is read like this:
type:int = socket_client.readByte();
if (type == 0x1)
FP.console.log("You are logged as " + socket_client.readByte() + " in x:" + socket_client.readByte() + " y:" + socket_client.readByte() );
else if (type == 0x2)
FP.console.log("You are now in x:" + socket_client.readByte() + " y:" + socket_client.readByte());
As you probably have guessed by now, this gives me some problems. Sometimes, server sends the information split in two, so the above code throws an EOF exception. Tracing the following code gives me sometimes this result:
trace("SIZE: " + socket_client.bytesAvailable);
//var type:int = socket_client.readByte();
var values:String = "";
while (socket_client.bytesAvailable > 0)
values += socket_client.readByte() + " ";
trace(values);`
Values:
SIZE: 1
2
SIZE: 2
2 6
The first '2' is the protocol id, the second and the third stands for x and y values.
Now, the question is, how can i prevent this to happen? How could i 'wait' until i have all the information needed?
Btw, on java this never happens, but i have no more control than on as3.
Add BufferedOutputStream in output initialization like this:
Output = new DataOutputStream(new BufferedOutputStream(connection.getOutputStream()));
Basically you need to switch your message format from [type, data] to [type, length, data]. Then, wait to process the data until bytesAvailable >= length, otherwise put it into a buffer.
Here is an example SOCKET_DATA handler that uses this logic:
https://github.com/magicalhobo/Flash-CS5-mobile-proxy/blob/master/com/magicalhobo/mobile/proxy/MobileClient.as#L110

"CalendarApp: Mismatch: etags" when adding reminders - Google Apps Scripts

I have a small Google Apps Script that processes a date column in a spreadsheet and generates entries in a Calendar (birthdays).
Work is fine, but when adding reminders to the (recently-created) CalendarEvent, an error is thrown :
Service error: CalendarApp: Mismatch: etags = ["GUQKRgBAfip7JGA6WhJb"], version = [63489901413]
I've tried to perform 1 second sleep after creating event (wait for changes to be done in calendar), but no luck on this...
BTW, events are created succesfully, only reminders cannot be added.
PD: the calendar is one I own, but not my primary calendar.
Here is part of the code:
try
{
birthday = new Date(Data[i][BirthColumn]);
birthday.setFullYear(today.getFullYear());
birthday.setUTCHours(12);
birthlist += Data[i][NameColumn] + " --> " + birthday + "\n";
calendarevent = cal.createAllDayEventSeries("¡Cumpleaños " + Data[i][NameColumn] + "!", birthday, CalendarApp.newRecurrence().addYearlyRule().times(YearsInAdvance));
if (calendarevent == null)
success = false;
else
{
//This sentence fails every single time.
calendarevent.addEmailReminder(0);
calendarevent.addPopupReminder(0);
calendarevent.addSmsReminder(0);
}
}
catch (ee)
{
var row = i + 1;
success = false;
errlist += "Error on row " + row + ": check name and birth date. Exception Error: " + ee.message + "\n";
}
This is the portion of the code I finally change to make it work, as Serge insas suggest me before:
if (calendarevent == null)
success = false;
else
{
cal.getEventSeriesById(calendarevent.getId()).addEmailReminder(0);
cal.getEventSeriesById(calendarevent.getId()).addPopupReminder(0);
cal.getEventSeriesById(calendarevent.getId()).addSmsReminder(0);
}
This is a known issue
See comment nr 67 for a working workaround : the trick is to re-call the event for every item you want to add (reminder, popup...) using cal.getEventSeriesById(eventID) after you get the Id simply with .getId()
I use it in some scripts and it solved the issue for me.

Regarding formatting of the query

I have made an application in which I have put the sql queries in java method as below..
private static String getSaleTransactionsQuery(final String currentTradingDate){
final String query =
" SELECT '990' line_code, " +
" sum(toti_wag.TTIW_CUST_CNT) amount " +
" FROM total_till_wag toti_wag " +
" where toti_wag.TOTI_TRADING_DATE = '" + currentTradingDate + "' ";
return query;
}
Now when I want to filter out sql queries then I have to copy this query on the sql file and have to manually remove the quotes("") and the plus(+) sign in order to make them as pure sql and then have to execute them to see the query output , is there any other tool which will format all these means remove the quotes and the plus sign ,please advise
You could make a simple script to help you.
http://jsfiddle.net/GFhFg/7/
I found it pretty easy to throw something together in JavaScript that does the job.
function cleanIt(txt) {
var result = "";
// remove semi-colon at the end
txt = txt.replace(/\;$/m, '');
var lines = txt.split('\n');
for(var i=0; i<lines.length; i++) {
var line = lines[i];
// trim whitespace
line = line.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
// remove + from beginning or end of line
line = line.replace(/^\+\s*/, '').replace(/\s*\+$/, '');
// remove quotes
line = line.replace(/"/g, '');
// remove the +'s around parameters/variables
line = line.replace(/('?\s*\+\s*)([^\s\+']+)(\s*\+\s*'?)/g, '$2')
result += line + '\n';
}
return result;
}
Obviously it hasn't be exhaustively tested, but it should give you a base to start from.
There is no automated way. You may write some generic custom function to do it for you.
One good proactive is to log the required details in log files. If you do and log your query then you will see your query without quotes and plus signs in the log file.