Ajax send POST to two URLs - javascript

On my website I want to send POST data to two different URLs and slightly modify the data for each URL. One is infusion soft and the other is an API on another one of my websites.
NOTE #1: I will be replacing the URL to my personal API with example text.
NOTE #2: Is it imperative that I set the Content Types, or is there other headers/information I'm missing before I send the Form Data? If so, why the heck would this all run perfectly from desktop? This code used to all be in jQuery but was not working as well, so I tried to rewrite the entire thing in Vanilla JS just to get the idea of a dependency problem out of the way.
NOTE #3: No 'Access-Control-Allow-Origin' header is present on the requested resource.
^ This pertains to both Infusion Soft and my personal API. I'm assuming if it's not even set on Infusion Soft that it's not a problem, especially given the fact that everything works perfectly on desktop.
NOTE #4: Every and ALL selectors match an element. There are no typos and again, this works to 100% on desktop running
Windows 10 Home
Chrome Version 61.0.3163.100 (Official Build) (64-bit)
NOTE #5: The action on the form goes to Infusion Soft. I stop the default from happening so I can work with the data, then send it to our database. After that is done I work with the data again, then let the action attribute run for Infusion Soft - all you can see in the code.
My code is as follows:
<script>
var form = document.getElementById('RequestADemo');
document.getElementById('submitButton').addEventListener('click', processData);
function processData(e){
e.preventDefault();
var phone = document.getElementById('inf_field_Phone1').value;
var formData = new FormData(form);
formData.append('action', 'insertLead');
formData.append('inf_field_Phone', phone);
var oReq = new XMLHttpRequest();
oReq.open('POST', 'http://example.com/api.php', true);
oReq.send(formData);
var fullName = document.getElementById('inf_field_FirstName').value;
var fullNameSplitted = fullName.split(' ');
var firstName = fullNameSplitted[0];
if (fullNameSplitted.length > 1) {
var lastName = fullNameSplitted[1];
}
var formData2 = new FormData(form);
formData2.delete('inf_field_FirstName');
formData2.append('inf_field_FirstName', firstName);
formData2.append('inf_field_LastName', lastName);
var oReq2 = new XMLHttpRequest();
oReq2.open('POST', form.getAttribute('action'), true);
oReq2.send(formData2);
form.reset();
alert('Thanks! We will contact you shortly. Check your email for a confirmation.');
}
</script>
This code works perfect on desktop and submits to both my personal API and Infusion Soft.
In our API we take care of the first name and last name splitting and insert them into separate fields in the database.
However, for Infusion Soft we need to do this before we send the data since we can not control their API.
This is all working as planned on desktop.
On my iPhone7 in Safari, this code inserts into my personal database as planned, but does not even make it to Infusion Soft.
I tested some things with console.log(); and found that
var FormData2 = new FormData(form);
is the line where things break on mobile.
Everything before this line is running perfect on mobile.
Any ideas? I'd really appreciate it!
**UPDATE: **
Here are my new variables and code for the second Request sending to Infusion Soft:
var email = document.getElementById('inf_field_Email').value;
var company = document.getElementById('inf_field_Company').value;
var phone = document.getElementById('inf_field_Phone1').value;
var fullName = document.getElementById('inf_field_FirstName').value;
var fullNameSplitted = fullName.split(' ');
var firstName = fullNameSplitted[0];
if (fullNameSplitted.length > 1) {
var lastName = fullNameSplitted[1];
}
var formData2 = new FormData();
formData2.append('inf_field_FirstName', firstName);
formData2.append('inf_field_LastName', lastName);
formData2.append('inf_field_Email', email);
formData2.append('inf_field_Company', company);
formData2.append('inf_field_Phone1', phone);
var oReq2 = new XMLHttpRequest();
oReq2.open('POST', form.getAttribute('action'), true);
oReq2.send(formData2);
However, this is not working on desktop or mobile! :(
The final alert confirmation however is coming through.

SOLVED
As #Barmar mentioned in the comments, I had to create empty FormData and append all of the values manually. I did this and at first it was not working. What I figured out is that I was appending all the values I wanted to send to Infusion Soft, but the solution was to send ALL hidden fields Infusion Soft gives you in the unstyled HTML forms and their values as well.
I just had to make these appends which were 3 other hidden fields in the form:
formData2.append('inf_form_xid', xid);
formData2.append('inf_form_name', isFormName);
formData2.append('infusionsoft_version', isVersion);
Note that I had already set the variables to their values prior to this code block. Infusion Soft must not accept data unless it receives these values, which makes complete sense.

Related

Google Script to Fill out HTML Form

I have created a script in google scripts, to take a spreadsheet and fill out multiple google docs successfully. I am trying to apply this logic to filling out an HTML form, basically, we need user-generated info (in our google sheet) to fill out an HTML form on a web page.
How would I get the following function to not only open but write in the data?
This is where I am at (just using an example webpage):
function testNew(){
var js = " \
<script> \
window.open('https://colorlib.com/etc/cf/ContactFrom_v1/index.html', '_blank', 'width=800, height=600'); \
google.script.host.close(); \
</script> \
";
var html = HtmlService.createHtmlOutput(js)
.setHeight(10)
.setWidth(100);
SpreadsheetApp.getUi().showModalDialog(html, 'Now loading.'); // If you use this on Spreadsheet
// DocumentApp.getUi().showModalDialog(html, 'Now loading.'); // If you use this on Document
// SlidesApp.getUi().showModalDialog(html, 'Now loading.'); // If you use this on Slides
}
This is an example of what I did with the google docs, trying to replicate in forms:
function myFunction() {
var data = Sheets.Spreadsheets.Values.get('google sheet ID HERE', 'A2:R300');
// google doc template id, already got deal memo
var templateId = 'google doc ID HERE';
// loop through the values "i" is looping the rows, "#" is the column example: 0=a,1=b
for (var i = 0; i < data.values.length; i++) {
var date = data.values[i][0];
var email = data.values[i][1];
// grab the google doc template, create a copy, and generate the new id
var documentId = DriveApp.getFileById(templateId).makeCopy().getId();
// change the name of the new file
DriveApp.getFileById(documentId).setName(companyName+ '-' + projectName+ '-' + 'Insurance Report');
// get the document body as a variable
var body = DocumentApp.openById(documentId).getBody();
// replace values with google sheet data
body.replaceText('##Date##', date);
body.replaceText('##Email##', email);
I have many functions that I have written that interact with a lot of third party forms and websites. Don't let it fool you that all that a form is, is a human-readable way to "POST" to a url. The easier way to do this is to use the UrlFetchApp.fetch(url, options) function in Google Apps script.
I use Chrome but other browsers have this functionality as well:
open Chrome, navigate to the form and then press F12 to open up the developers window.
Click on 'Network'
fill out the form manually and then review the traffic in the 'Network' window and find the POST that your browser sent to the site,
With that highlighted, you will see a couple other tabs for 'Headers','Preview','Response'
In the 'Headers' tab, scroll to the bottom and it will show you what the request looked like. Screen shot this and send these variables through the UrlFetchApp.fetch() to the website as the 'payload' and formatted like the function below.
Look at the 'Request URL' at the top of that same 'Headers' tab and you will use that as the URL below:
function senddatatoform() {
var url = 'http://theurlthattheformpoststohere.com'; // this is the 'request url' as shown in your browser (not always the url of the form).
var payload = {
datapoint1: datapoint1value,
datapoint2: datapoint2value,
... //continue with all required post data
}
var options = {
method: "POST",
payload: payload
}
var response = UrlFetchApp.fetch(url,options);
/*this is where what you need to do next might vary -- if you're looking for a 'success' page, you might write some code here to verify that the http response is correct based on your needs.
*/
}

Add attachment by url to Outlook mail

The context
There is a button on the homepage of each document set in a document library on a SharePoint Online environment. When the button is clicked, an Outlook window opens with the title and body set and all the files in the document set should be added as the attachments.
The code
Here's the code I have so far:
var olApp = new ActiveXObject("Outlook.Application");
var olNs = olApp.GetNameSpace("MAPI");
var olItem = olApp.CreateItem(0);
var signature = olItem.HTMLBody;
signature.Importance = 2;
olItem.To = "";
olItem.Cc = "";
olItem.Bcc = "";
olItem.Subject = "Pre filled title";
olItem.HTMLBody =
"<span style='font-size:11pt;'>" +
"<p>Pre filled body</p>" +
"</span>";
olItem.HTMLBody += signature;
olItem.Display();
olItem.GetInspector.WindowState = 2;
var docUrl = "https://path_to_site/Dossiers/13245_kort titel/New Microsoft Word Document.docx";
olItem.Attachments.Add(docUrl);
The Problem
When I run this code, an Outlook window opens with everything set correctly. But on the line where the attachment is added I get following very vague error message:
SCRIPT8: The operation failed.
I thought it could be the spaces in the url so I replaced them:
docUrl = docUrl.replace(/ /g, "%20");
Also didn't work (same error) and providing all parameters like this also didn't work:
olItem.Attachments.Add(docUrl, 1, 1, "NewDocument");
Passing a path to a local file (e.g. C:/folder/file.txt) or a publicly available url to an image does work. So my guess is it has something to do with permissions or security. Does anybody know how to solve this?
PS: I know using an ActiveX control is not the ideal way of working (browser limitations, security considerations, ...) but the situation is what it is and not in my power to change.
You cannot pass a url to MailItem.Attachments.Add in OOM (it does work in Redemption - I am its author - for RDOMail.Attachments.Add). Outlook Object Model only allows a fully qualified path to a local file or a pointer to another item (such as MailItem).

Removing Edit Access from a Sheet using email from a cell

I am trying to figure out how to remove someone from a spreadsheet using google app scripts.
Essentially, I have a central spreadsheet with information such as emails, names, UID's etc on it. I am trying to pull the email from this spreadsheet and use the removeEditor function to remove that email from another spreadsheet. You can view the code below.
var officerIDrow = officerID + 1;
var Tracker = SpreadsheetApp.getActive().getSheetByName('P_Tracker'); //the button is on the same sheet as this, this is why it is get active.
var PTBooking = SpreadsheetApp.openById("1JPS69ko99dQTEwjplF_l2l2G_T8RyHjxCyMxXd_AV_s"); //Referring to the other sheet where the email will be removed from editors.
var EmailAddressRange = "F" + officerIDrow; //This is the column where the emails are stored. The officer ID row refers to the user inputted value in a dialog. Don't worry about this, I have already checked to see if this is the issue,
var EmailAddress1 = Tracker.getRange(EmailAddressRange);
var EmailAddress2 = EmailAddress1.getValue();
var EmailAddress3 = Utilities.formatString(EmailAddress2); //In my desperation, I was trying to see if setting it as string would help.
PTBooking.removeEditor(EmailAddress3);
This isn't the full version of the code. If you'd like to see it, you can click here. But all that matters is above, everything else works fine.
The code above runs fine until it hits the last line where it tries to remove the email. The error message that appears says: "Invalid email: ". I'm assuming after the "email:" bit, it should display what has been pulled. But it doesn't! I have no idea why it isn't finding and using the email to remove people.
Can anyone spot any issues?
Thanks,
Shaun.
This basic test worked for me. It could read email address from the spreadsheet then remove editors from the external sheet. I tried to copy your example, but I don't know how the officerIDrow works, but I assume it's a number. So just stored a number as a var
function myTest() {
var ss = SpreadsheetApp.openById("ID HERE");
var idRow = 11;
var tracker = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("tracker");
var emailCell = "F"+idRow;
Logger.log(emailCell);
var emailAddress = tracker.getRange(emailCell).getValue();
Logger.log(emailAddress);
ss.removeEditor(emailAddress);
var editors = ss.getEditors();
Logger.log(editors);
}
I've left the Logger bits in as it will help point you at what script is doing at each point.
The email address in the cell must be plain, such as google#google.com

Calling a website and getting JSON information back

I am not too experienced in javascript on using API's and how to call websites and get information back. I have done this before in Java using HTTP objects and more. I am attempting to make an application where a user can type in a company stock name such as APPL and get back a ton of data like gains, losses, changes, etc. This shouldn't be that hard. I have a html/javascript file with an input textbox for the stock name. This part is easy. But after I tack on the stock name to the end of the URL by concatenation I don't know how to make the call and get the JSON information. There are examples of how to do this in other languages in the web page I am using but not for javascript. I am using this link as a tutorial:
http://digitalpbk.com/stock/google-finance-get-stock-quote-realtime
Here is my javascript code so far: Again this is probably really simple to do. Any help on this would be greatly appreciated and is good to know in the future.
script type="text/javascript">
var submitButton = document.getElementById("submitButton");
submitButton.addEventListener('click', actionPerformed, false);
function actionPerformed(e)
{
var textValue = document.getElementById("stockTextBox").value;
var urlEncoded = "http://finance.google.com/finance/info?client=ig&q=NASDAQ:" + textValue.toString();
for (var i = 0, len = urlEncoded.length; i < len; ++i) {
var object = urlEncoded[i];
confirm(object.toString());
}
}
</script>
I just found the following code for using HTTP GET and tried it out but nothing happens when I click the submit button. Any suggestions on what to do or what's wrong???
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
Wow, this is turning out to be a lot more work then I had anticipated. Here is the URL string I am using in my code for yahoo finance. I can navigate to it in the browser and it works like a charm. For the life of me I cannot understand why this isn't working.
var urlEncoded = "http://www.finance.yahoo.com/webservice/v1/symbols/" + textValue.toString() + "/quote?format=json";
You could try jQuery, google and download it.
It's a javascript framework that makes things allot simpler .
$.get( "http://yourur.com/file.php?parameter1=value1&parameter2=value2", function( data ) {
//data now contains whatever it loaded from server
console.log("Loaded from server :", data);
}, "json");

JavaScript to set field in Lotus Notes Web Form

I am trying to have a Wscript agent run when the web form starts in order to set a field with the machine name. I have tried adding this as pass through HTML at the bottom of the form as well as adding it to the onLoad event or the JS Header to no avail. I am a beginner at web enabling a form and adding JavaScript to it in Lotus. Any help would be fantastic. Below is the code:
Field Name: MachineName
{
var ax = new ActiveXObject("WScript.Network");
f.MachineName.value = ax.ComputerName;
}
I guess this is not the complete code. At least one line is missing that defines "f"
The curly brackets have no sense in your code...
In the onload- event of the form, this code should work:
var f=document.forms[0];
var ax = new ActiveXObject( "WScript.Network" );
f.MachineName.value = ax.ComputerName;
Of course this will only work in InternetExplorer as shown here

Categories

Resources