collect data from a form hosted on another site - javascript

We have a number of clients that have agreed to send us their form data once a form is submitted on their site. Is this possible and what is the best way to handle this? Our site is built in coldfusion while the client site varies.
I had the client add a script tag to include a javascript file from our server on their form page. Also had them add an onClick event to their form button so this javascript is called on submission of their form.
This is the javascript file:
function cpcshowElements(f) {
var formElements = "";
for (var n=0; n < f.elements.length; n++) {
box = f.elements[n];
formElements += box.name + ":" + f.elements[n].value + ",\n";
}
var track = new Image();
/*send data to us*/
track.src="http://XXX.net/form_record.cfm?form="+ formElements + "&self=" + this.location;
}
On form submission the cpcshowElements function is called, formats the form data, appends it to the end of the XXX.net/...and calls that url. The form_record.cfm page basically does some checks and inserts the data into a table.
This process does work, however not consistently. The data doesn't always make it into the database. That is the problem. Is there another way to do this that won't have data loss?

The data getting to the database is pretty deep down the chain. The first step is to figure out where the request isn't coming through. Find the weak link, and then fix that part.
Chances are, there are other issues causing the failure than this piece of javascript. Test each part of the process and figure out where the problem lies. Chances are, it isn't in the javascript.

Check whether the form on the serve is being submitted by method other than onClick. If the form can be submitted by hitting enter or tabbing and hitting enter or the spacebar, than you are missing some submits. Would work more consistently with onSubmit rather than onClick.
Example:
<form onsubmit="your_function_here">
Also, if the form is submitting and then moving on to another page, you javascript code may not have enough time to fire. In that case, put a delay into your function to allow the GET request for the image to be made before the page evaporates.

Related

Send javascript values to server before page load in asp.net

I'm currently using geolocation to get the clients browser location. Right now, I store the values in local storage and then send them when the user submits the form. I would like to send them before the page even loads however, so that I can run the required calculations when the page is first opened on the client side.
Here is the javascript I am using to get the location (which works well). It runs before the page is loaded.
navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
function foundLocation(position) {
if (isPostBack == true) {
return;
}
var lat = position.coords.latitude;
var long = position.coords.longitude;
this.localStorage.setItem("lat", Math.round(lat * 1000000) / 1000000);
this.localStorage.setItem("long", Math.round(long * 1000000) / 1000000);
}
I then use window.onload and call the values in storage to load them on the form automatically. The user then clicks a button and the form submits with the values.
How can I just send those values directly to the server? This would allow me to run the required location calculations without the user even having to click. I know I could just automate the submit button click after after the window.onload fires, but I don't want it to look like the form loads, submits then posts back if that makes sense.
I'm new to asp.net so I'm not even sure what question to ask here so my apologies if this is something simple I'm just looking over.
EDIT: The "possible duplicate" is regarding executing js before page load which I am already doing. My question is more on how to send the values back to the server before loads complete.
You can create an empty page as a first step. Then that page can perform that calculation and redirect to the final page sending that info through a POST or a GET.
window.location.href = "your-final-page.aspx?lat=" + lat + "&long=" + long;

Sending a form through PHP, autosaving with JS every ten minutes

The Environment
PHP: Symfony -> Twig, Bootstrap
Doctrine -> Mongodb
Jquery
The Project
The timer is working, counting the interval, and I can send the form. This is good, but once I get to the part where the form is sent I seem to be running into two problems:
interval counter working
form submitting automatically, then
The null fields do not get accepted
The form does not get validated
The form itself is setup through a custom built PHP graphical interface that allows you to set the simple things very easily: fields, fieldtypes, names and labels, etc.
This is cool, but it means that you can't go in and tinker very much with the form or at all really. The most you can change is aesthetics in the template. Although you could wrap each form element in another form element or some kind of html identifier, this is an option, but a tedious one...
On a valid check the form gets upserted and all is well the else catches the non-valid form and lets the user know that some fields are not filled in. I would post that code here, but I think it would be frowned upon. Hopefully you understand the PHP concept.
The part that I can share is the JS:
autoSaveForm = function() {
var form = $('form'),
inputs = form.find('input');
form.on('submit', function() {
inputs.each( function( input ) {
if (input.attr("disabled") === true){
input.removeAttr("disabled");
}
})
});
function counter(){
var present = $('.minutes').attr('id'),
past = present;
$('.minutes').text(past);
setInterval(function(){
past--;
if(past>=0){
$('.minutes').text(past);
}
if(past==0){
$('.minutes').text(present);
}
},1000);
}
function disableInputs(){
inputs.each( function( input ) {
if (input.val() === ""){
input.attr("disabled", true);
}
});
}
// Start
counter();
// Loop
setInterval(function(){
counter();
form.submit()
},10000);
};
This sets a counter on the page and counts through an interval, it's set to seconds right now for testing, but eventually will be 10 minutes.
Possible Solutions
disable the null fields before submit and remove the attribute after submit is accomplished
this needs to be done so that the user can do a final completed save at the end of the process
this doesn't actaully seem to be disabling the fields
Their were a few things I found about adding in novalidate to the html, but it wasn't supported in all browsers and it might get tricky with the static nature of the forms.
Post the form with ajax and append a save true variable to the end of the url, then redirect it in PHP Controller with a check on the URI var although:
then I still have the null fields
to solve this: set a random value or default value to the fields as they are being passed through. haven't tried this yet
Something kind of like what this question is addressing, although I have some questions still about the null fields - Autosaving Form with Jquery and PHP
Sending the form through ajax
Any input would be greatly appreciated. :) Thanks

CRM and iframe aspx page form submission

Scenario :
I have aspx page which I need to Iframe on CRM's Opportunity form. This aspx page has form which submits data into the other database.
Requirement :
I would like when user clicks save button on CRM opportunity form ,aspx page should store the data in external database and opportunity form should also save all the changes on CRM form.
My Efforts :
Till now I have Iframed aspx page on CRM form.I am also submitting the form using OnSave event.
But the only problem is the form gets submitted but by the time it executes the complete code CRM form gets refreshed . End result is that Data on aspx page does not get stored in the external database.
What can be the other possible way to achieve this functionality ?
Thanks for taking time to read. Thank you in advance.
Option 1: The better solution is to do this from an opportunity post event plug-in. This ensures data consistency between CRM and external data (if required). Also you could use WCF or a web service to transmit the data to external DB.
Option 2: If you must use javascript you could (1) bind to opportunity form OnSave, (2) Prevent the form from submitting , (3) submit the iframe and (4) wait until it comes back and then (5) do another save to complete the action. This however might cause inconsistencies between CRM and external DB if opportunity save fails.
Here is a pseudo code example
function OpportunityOnLoad() {
IFRAME.OnReadyStateChange = function() {
// (4) Check success if possible
// (5) unbind save event and complete the opportunity save
Form.RemoveOnSave(OpportunityOnSave)
Form.Save();
}
//OnLoad
Form.AddOnSave (OpportunityOnSave);
}
function OpportunityOnSave(context) {
//(1) Save clicked
//(2) Stop save
context.PreventDefault();
//(3) Submit iframe form
IFRAME.Submit();
}
EDIT:
Regarding Q1 : unfortunately not.
Regarding Q2 :
This is a rough translation of the concept above into Javascript and CRM client side API.
I didn’t test it but it should put you on the right track.
Change the Params to match the iframe id, url etc.
also since you’re using an aspx you might experience cross domain issue that could be easily overcome if you’re browsing IE and not so easily overcome if you’re using CROME for example.
var IFRAME, SaveMode;
var FORM = Xrm.Page.data.entity;
var UI = Xrm.Page.ui;
var SaveModes = {
1 : "save",
2 : "saveandclose",
59: "saveandnew"
}
var Params = {
IframeBaseUrl : "",
IframeId : "IFRAME_test",
IframeFormId : "form1"
}
function OpportunityOnLoad() {
var sUrlparams = "?"; //add required params after ?
var IframeUrl = Params.IframeBaseUrl + sUrlParams;
IFRAME = UI.controls.get(Params.IframeId);
IFRAME.setSrc(IframeUrl);
IFRAME.Dom = document.getElementById(Params.IframeId);
IFRAME.add_readyStateComplete(OnAfterIfameSave);
FORM.addOnSave(OpportunityOnSave);
}
function OnAfterIfameSave() {
//SubmitSuccess indicates that the form has reloaded after a
//successful submit. You'll need to set this variable inside your iframe.
if (IFRAME.contentWindow.SubmitSuccess) {
FORM.removeOnSave(OpportunityOnSave);
FORM.save(SaveModes[SaveMode]);
}
}
function OpportunityOnSave(execObj) {
var evArgs = execObj.getEventArgs();
evArgs.preventDefault();
SaveMode = evArgs.getSaveMode();
IFRAME.contentWindow.document
.getElementById(Params.IframeFormId)
.Submit();
}

Use POST to submit form, but change action?

I'm trying to submit a form with Java, which looks like this:
<form id="bForm" action="/a/b.php" method="POST"></form>
There are no <input type="hidden">, there are not even any <input> at all.
In the source, I see that this form is submitted when I click a link which
executes javascript code like this:
javascript:b(<k>,<v>)
where <k> and <v> is some key and value consisting of some numbers.
Now, the function b() in the source is this:
function b(value, key) {
var form = document.getElementById('bForm');
form.action = '/b/user/' + key + '/' + value + '.txt';
form.submit();
}
What I'm trying to receive is the .txt file send as response, but trying to directly open
http://<url>.com/b/user/<key>/<value>.txt
in a browser does not get me the .txt file, but a message saying it has to be accessed by using the POST method.
Now, I read about how to send requests via POST (also from trying to find a
solution here) and think I understood most. Still, I only read about mostly everything today, including what forms are, so excuse me if the solution is obvious.
The problem I have here is that there are no parameters I can pass to "let the URL know" which action to do upon submitting the form.
Now as I can probably not change the action of the form, what do I do?
Can I somehow "connect" to the URL which leads to the .txt file via "POST"?
Or do I need to execute the javascript somehow, and if so how?
Edit: I have solved the problem now, not sure if my explanation was not good enough, but the solution seemed pretty simple, I just didnt know enough about forms.
So, action=#myurl# means that the form is submitted to the #myurl#, not to the current page. And, although the target URL seems to point to some file which cannot do anything with the submitted form, this is not right. In fact, it points to a script, but the script is "hidden" in a way that we only see the path to the file we want to download in the URL.
So, I just did this:
URL url = new URL("http://myurl.com/b/user/" + key + "/" + value + ".txt");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
//set User-Agent, Cookie, etc. properties here
c.setRequestMethod("POST");
c.setInstanceFollowRedirects(false); //not sure if this is needed
InputStream in = c.getInputStream(); //this submits the parameter-less form
//now I can get the response with this stream, i.e. read & save the .txt file
All tested and running complete code now, so it works for sure.

Sending form variable data to another website on form submission

We have clients that we want to collect some of their form submission data for. A user will fill out a form on their site and when the form is submitted, the following javascript is called:
/* 4. Below script will get all field name/value pairs for given form */
function cpcshowElements(f) {
var formElements = "";
for (var n=0; n < f.elements.length; n++) {
box = f.elements[n];
if (!f.elements[n].value == ""){
formElements += box.name + ":" + f.elements[n].value + ",\n";
}
}
var track = new Image();
/*send data to us*/
track.src="https://www.xxx.com/form_record.cfm?form="+formElements;
//alert("The elements in the form '" + f.name + "' are:\n\n" + formElements);
}
This calls code on our end that should grab the data sent and save it. This works great, but doesn't work all of the time. When testing, we seem to not get the data consistently. I haven't been able to figure out why this works sometimes and not others. I'm not a javascript expert so I'm not sure if it's just the way javascript works. The only thing I've been able to think might be the issue is that once the clients website finishes processing the form on their end and the user is directed to another page, the script will stop running if it hasn't already finished and so we won't get the data. Anyone have any ideas? Am I on the right track here? Any ideas on how to make it so we will get the data every time?
You could you jQuery Framework with serialize function tosubmit the form and get it input's values.
$("#bottonId").click(function(){
imageObj.src ="http://www.mypage.com/mypage?" +$("#form's ID").serialize();
});

Categories

Resources