Send HTML through Ajax POST - html

I have this code which works with no errors when sending "simple text" through Ajax post.
But when I want to send "html" to the server, my code will fail sometimes.
var message = tinyMCE.activeEditor.getContent();
if(message.length > 0)
{
message = Base64.encode(message);
tinyMCE.activeEditor.setContent('');
var parameters = 'message=' + message;
var url = "ChatResponse.aspx";
ajaxPost.open("POST", url, true);
ajaxPost.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
ajaxPost.setRequestHeader("Content-Length", parameters.length);
ajaxPost.setRequestHeader("Connection", "close");
ajaxPost.send(parameters);
}
Will not fail for
asdasd<strong>asdasd</strong> [base64:]
YXNkYXNkPHN0cm9uZz5hc2Rhc2Q8L3N0cm9uZz4=
but will fail for
a<strong>a</strong> [base64:]
YTxzdHJvbmc+YTwvc3Ryb25nPg==
What is wrong?

It is not being encoded before being sent. I believe TinyMCE has a method that allows you to get the encoded content. You may also want to try taking the content from the textarea using the value property.

Related

How to login into the Fidelity website and navigate within it?

I would love to get some help in logging into the Fidelity website and navigate within it. My attempts so far have not led me to anywhere significant. So here is the code that I have written, after much consultation with answers around the web. The steps are:
Login to Fidelity
Check if response code not 200, but is 302 or 303 and my code passes this test (with a code of 302).
Then I check the number of cookies returned (there were 5) and for each cookie I try to navigate to a different web page within Fidelity (I do this five times, once for each cookie, simply because I do not know which subscript "j" of the variable "cookie" will work).
function loginToFidelity(){
var url = "https://www.fidelity.com";
var payload = {
"username":"*********",
"password":"*********"
};
var opt = {
"payload":payload,"method":"post","followRedirects" : false
};
var response = UrlFetchApp.fetch(encodeURI(url),opt);
if ( response.getResponseCode() == 200 ) {
Logger.log("Couldn't login.");
return
}
else if (response.getResponseCode() == 303 || response.getResponseCode() == 302) {
Logger.log("Logged in successfully. " + response.getResponseCode());
var cookie = response.getAllHeaders()['Set-Cookie']
for (j = 0; j < cookie.length; j++) {
var downloadPage = UrlFetchApp.fetch("https://oltx.fidelity.com/ftgw/fbc/oftop/portfolio#activity",
{"Cookie" : cookie[j],"method" : "post","followRedirects" : false,"payload":payload});
Logger.log(downloadPage.getResponseCode())
Logger.log(downloadPage.getContentText())
}
}
}
For each choice of the subscript "j", I get the same answer for the ResponseCode (always 302) as well as the same answer for ContentText. The answer for ContentText is obviously incorrect as it is not what it is supposed to be. The ContentText is shown below:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>302 Found</title>
</head><body>
<h1>Found</h1>
<p>The document has moved here.</p>
</body></html>
Based on this, I have two questions:
Have I logged into the Fidelity site correctly? If not, why do I get a response code of 302 in the login process? What do I need to do differently to login correctly?
Why am I getting such a strange and obviously incorrect answer for my ContentText while getting a perfectly reasonable ResponseCode of 302? What do I need to do differently, so that I can get the password-controlled page within Fidelity, whose url is "https://oltx.fidelity.com/ftgw/fbc/oftop/portfolio#activity"?
NOTE: Some other tests have been done in addition to the one stated above. Results from these tests are provided in the discussion below.
Here is something which worked for me. You may have found the solution already, not sure. Remember to fill in your loginid where the XXXX is and the pin number for YYYY.
I understand this is python code, not the google script, but you get the idea about the code flow.
import requests, sys, lxml.html
s = requests.Session()
r = s.get('https://login.fidelity.com')
payload = {
'DEVICE_PRINT' : 'version%3D3.5.2_2%26pm_fpua%3Dmozilla%2F5.0+(x11%3B+linux+x86_64%3B+rv%3A41.0)+gecko%2F20100101+firefox%2F41.0%7C5.0+(X11)%7CLinux+x86_64',
'SavedIdInd' : 'N',
'SSN' : 'XXXXX',
'PIN' : 'YYYYY'
}
r = s.post(login_url, data=payload, headers=dict(referer='https://login.fidelity.com'))
response = s.get('https://oltx.fidelity.com/ftgw/fbc/oftop/portfolio')
print response.content
mwahal, you left out the critical form action url (your login_url is undefined)
this works (if added to your python code)
login_url = 'https://login.fidelity.com/ftgw/Fas/Fidelity/RtlCust/Login/Response/dj.chf.ra'
btw here's the result of the print after the post showing successful login
{"status":
{
"result": "success",
"nextStep": "Finish",
"context": "RtlCust"
}
}
or adding some code:
if r.status_code == requests.codes.ok:
status = r.json().get('status')
print(status["result"])
gets you "success"
Unfortunately the answer from #mwahal doesn't work anymore - I've been trying to figure out why, will update if I do. One issue is that the login page now requires a cookie from the cfa.fidelity.com domain, which only gets set when one of the linked JavaScript files is loaded.
One alternative is to use selenium, if you just want to navigate the site, or seleniumrequests if you want to tap into Fidelity's internal APIs.
There is a hitch with seleniumreqeusts for the transactions API... the API requires Content-Type: application/json and seleniumrequests doesn't seem to support custom headers in requests. So I use selenium to log in, call one of the APIs that doesn't need that header, copy then edit the response's request header, and use regular requests to get the transactions:
from seleniumrequests import Chrome
import requests
# Log into Fidelity
driver = Chrome()
driver.get("https://www.fidelity.com")
driver.find_element_by_id("userId-input").send_keys(username)
driver.find_element_by_name("PIN").send_keys(password)
driver.find_element_by_id("fs-login-button").click()
r = driver.request('GET', 'https://digital.fidelity.com/ftgw/digital/rsc/api/profile-data')
headers = r.request.headers
headers['accept'] = "application/json, text/plain, */*"
headers['content-type'] = "application/json"
payload = '{"acctDetails":[{"acctNum":"<AcctId>"}],"searchCriteriaDetail":{"txnFromDate":1583639342,"txnToDate":1591411742}}'
api = "https://digital.fidelity.com/ftgw/digital/dc-history/api"
r = requests.post(api, headers=headers, data=payload)
transactions = r.json()

Google Translate free api assist

I am kind of new to javascript and building websites, I program c# most of the times.
I am trying to build something and I need to use google translate api, the problem that is cost money so I prefer use Free API so I found this.
https://ctrlq.org/code/19909-google-translate-api
so I changed it a bit and tried alone, because I wasn't sure what e type ment.
so this is my code:
function doGet(text) {
var sourceText = text;
var translatedText = LanguageApp.translate('en', 'iw', sourceText);
var urllog = "https://translate.googleapis.com/translate_a/single?client=gtx&sl="
+ "en" + "&tl=" + "iw" + "&dt=t&q=" + encodeURI(text);
var result = JSON.parse(UrlFetchApp.fetch(urllog).getContentText());
translatedText = result[0][0][0];
console.log(translatedText);
}
so the url is downloading me a text file called "f.txt" that include the translate code the problem is that I doesnt want it to download File,
I just need the translate inside the txt file its gives me,
also the problem is I am not sure how to get that info inside a javascript variable, And I doesnt want it to give me that file as well..
So how Can I read it?
how can I use the file without download it, and How can I push it to a string variable?
And How I can cancel the download and get only the translate?
THANKS!
By the way
and if anyone know the function doGet(e) that I showed on the link, what is "e"? what does the function wants?
I know I'm a year late but I came to same problem and fixed it using PHP. I have created this simple PHP function:
function translate($text, $from, $to) {
if($text == null)
echo "Please enter a text to translate.";
if($from == null)
$from = "auto";
if($to == null)
$to = "en";
$NEW_TEXT = preg_replace('/\s+/', '+', $text);
$API_URL = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" . $from . "&tl=" . $to . "&dt=t&q=" . $NEW_TEXT;
$OUTPUT = get_remote_data($API_URL);
$json = json_decode($OUTPUT, true); // decode the JSON into an associative array
$TRANSLATED_OUTPUT = $json[0][0][0];
echo $TRANSLATED_OUTPUT;
}
Example usage (English to Spanish):
translate("Hello", "en", "es"); //Output: Hola
/*
sourceLanguage: the 2-3 letter language code of the source language (English = "en")
targetLanguage: the 2-3 letter language code of the target language (Hebrew is "iw")
text: the text to translate
callback: the function to call once the request finishes*
* Javascript is much different from C# in that it is an asynchronous language, which
means it works on a system of events, where anything may happen at any time
(which makes sense when dealing with things on the web like sending requests to a
server). Because of this, Javascript allows you to pass entire
functions as parameters to other functions (called callbacks) that trigger when some
time-based event triggers. In this case, as seen below,
we use our callback function when the request to google translate finishes.
*/
const translate = function(sourceLanguage,targetLanguage,text,callback) {
// make a new HTTP request
const request = new XMLHttpRequest();
/*
when the request finishes, call the specified callback function with the
response data
*/
request.onload = function() {
// using JSON.parse to turn response text into a JSON object
callback(JSON.parse(request.responseText));
}
/*
set up HTTP GET request to translate.googleapis.com with the specified language
and translation text parameters
*/
request.open(
"GET",
"https://translate.googleapis.com/translate_a/single?client=gtx&sl=" +
sourceLanguage + "&tl=" + targetLanguage + "&dt=t&q=" + text,
true
);
// send the request
request.send();
}
/*
translate "This shouldn't download anything" from English to Hebrew
(when the request finishes, it will follow request.onload (specified above) and
call the anonymous
function we use below with the request response text)
*/
translate("en","iw","This shouldn't download anything!",function(translation) {
// output google's JSON object with the translation to the console
console.log(translation);
});

How to make Web page to not wait for a response after sending a GET request

I am trying to make this web site that resides in Google Drive control a LED(on/off) via esp8266 and arduino. Partially i've succeded in doing what i want by sending to the IP of the module that communicates with the arduino a GET request witch parses it and acts accordingly. ie GET /?LED1=on HTTP/1.1
Problem is that whenever i press a button in the web site it sends the GET request and then it waits for a response from the other end (arduino),and the browser keeps loading until eather I close the connection from the arduino or I reply something like HTTP/1.1 200 OK and then close the conection.
In the first case browser shows the message that was unable to load the page and in second case it simply shows a blank page.
<DOCTYPE html>
<html>
<head>
<title>LED Control</title>
</head>
<body>
<button>LED 1 On</button>
</body>
</html>
I just want to send that LED1=on string somehow without causing the page attempt to load anything back.
A reusable solution
Modify your HTML to be something like this:
<button class="get" data-url="http://78.87.xxx.xx:333/?LED1=on">LED 1 On</button>
Now add this JavaScript:
window.onload = function () {
Array.prototype.forEach.call(document.querySelectorAll('.get'), function(el) {
el.onclick = function () {
// Use this trick to perform CORS requests too
var req = new Image();
req.src = this.dataset.url;
// The following 7 lines are completely optional
req.onload = function () {
// Was successful
};
req.onerror = function (error) {
// Encountered an error
alert('An error occurred while performing the request. + ' error);
};
};
});
};
Now any element with the class "get" when clicked, will send a request to the URL. This won't change the page either. If

Chrome addon with my server interaction

its many days reading hundreds of ways to help me make what I really need. No success at all.
What I need is this:
1) Having a button which only works when the tab has a certain url.
2) After clicking it, must read page's source and then get some pieces of it to send them to my server page in order to check my database for recordcounts (I assume with AJAX & javascript). Then this page should send back to the extension its responses and populate the popup html.
Looks easy I know, but please I need the workflow if not the required codes for the extension.
Thank you so much!
ok so you can chceck selected tab and it's url with:
chrome.tabs.getSelected(null,function(tab) {
workWithUrl(tab.url);
});
...
function workWithUrl(url){
if (url == ...
...
}
To be able to chceck this you need to add permission for "tabs"
To process page source code, send it to web service and change popup.html:
var xhr = new XMLHttpRequest();
xhr.open("POST", "__server adress___", true);
//headers
xhr.setRequestHeader("Content-Type", "application/json");
//response
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
//response from service to popup.html
document.body.innerHTML = xhr.responseText;
}
}
//process page here
xhr.send(pageText);
You have to add permission for server adress to manifest as well and everything should be executed from popup.js (or html).

Get original message with headers when forwarding message before sending in EWS

I'm trying to provide a way to forward emails, just as we do in Outlook. When the user clicks forward, it opens a form with the original message and header information on top, giving the user an opportunity to modify the body. To get the message, I do the following.
var item = (EmailMessage)dataGridEmail.SelectedItem;
ResponseMessage forward = item.CreateForward();
textBlockForward.Text = forward.Body;
I get an ServiceObjectPropertyException with message "You must load or assign this property before you can read its value". If I try to load the value of the body property before accessing, I get NotSupportedException with message "Specified method is not supported". Is there a way to get the forwarding message before actually sending it?
Instead of using forward.Body, you should use item.Body to populate your textBlockForward control. See Forwarding Email Messages using EWS on MSDN for more details.
var item = (EmailMessage)dataGridEmail.SelectedItem;
ResponseMessage forward = item.CreateForward();
textBlockForward.Text = item.Body; // needs to come from original message source
forward.BodyPrefix = "new body contents"; // prepended body content
I am note sure if anyone could solve this. This is what i did.
ResponseMessage responseMessage = message.createForward();
// message is an EmailMessage object
responseMessage.setBodyPrefix(body);
responseMessage.save(WellKnownFolderName.Drafts);
EmailMessage saved = responseMessage.save();
saved.load(new
PropertySet(BasePropertySet.FirstClassProperties,ItemSchema.Body));
MessageBody messageBody = saved.getBody();
// do something with messageBody`enter code here`
//System.out.println(saved.getBody().toString());
saved.sendAndSaveCopy();