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();
}
Related
here my simple form:
<form id="myform">
Name:<input type="text" name="name"><br>
Email:<input type="text" name="email">
<a class="btn btn-primary" id="click_btn">Submit</a>
</form>
I want to submit the form with Ajax, that bit is okay so far, and submitting.
Here is my jquery code:
$(document).ready(function() {
$('#click_btn').on('click', function() {
$.ajax({
url: $('myform').attr('action'),
data: $('myform').serialize(),
method: 'post',
success: function(data) {
//success meseg then redirct
alert('success');
var data = $('#myform').serializeArray();
var dataObj = {};
$(data).each(function(i, field) {
dataObj[field.name] = field.value;
window.location.href = 'next_page.php';
});
}
})
});
})
next_page.php is where I want to access, example:
<?php echo document.write(dataObj["email"]); ?>
I want to access these form values that I have submitted on next page after the form is submitted. I have created a data object with all the values using jQuery after submit, but still, I cannot access on the next page. Is there any concept related to the session in jquery for storing that array.
I think you're getting a couple of concepts confused here; I don't mean that in a condescending way, just trying to be helpful.
jQuery, and all JavaScript, exists only on the client-side (for practical purposes - there are exceptions where some client-side code might be rendered or compiled on the server-side for whatever reason but that's another matter). PHP, like any other server-side language, exists on the server-side. These two can't directly access each other's scope - which is why AJAX is useful to transfer data between the front and back ends.
Basically what you appear to be doing here is loading the data in the client-side, but not submitting anything to the server-side. You aren't actually doing any AJAX queries. When you redirect the user via window.location.href =..., no data is actually being transmitted - it simply instructs the browser to issue a new GET request to next_page.php (or wherever you instruct it to go).
There are a couple of options to do what you're trying to achieve:
Actually submit an AJAX query, using the methods outlined here http://api.jquery.com/jquery.ajax/. You can then use next_page.php to grab the data and store it in a session and recall it when the user arrives on the page.
Store the data in a client-side cookie.
Use the standard HTML <form method="next_page.php"...><input type="submit"> to cause the browser to forward the form data to the next_page.php script.
A number of other options but I think those are the simplest.
You can totally use sessionStorage ! (Here is documentation)
If user direct to next page in same tab, sessionStorage can easily save you data and reuse in next page.
// set in page A
window.sessionStorage.setItem('youdata', 'youdata');
// or window.sessionStorage['youdata'] = 'youdata';
// get in page B
var youdata = window.sessionStorage.getItem('youdata');
// or var youdata = window.sessionStorage['youdata'];
That's it! very simple!
If you'll open a new tab, you can use localStorage. (Here is documentation)
The usage of localStorage is like the way of sessionStorage.
While do saving information for other pages, these two method only need browsers' support.
<?php echo document.write(dataObj["email"]); ?>
This is unreasoned! echo is a PHP command, but document.write is a JavaScript command.
If the secound page is PHP, why not send data with a simple POST submit from HTML Form?
You can also use localStorage:
var data = '123';
localStorage['stuff'] = data;
Use localStorage.clear(); to remove all data if you want to write it again or for specific item use localStorage.removeItem('stuff');
List of some possible solutions are as follows:
1. Post the data using AJAX request and the get it in next page by doing DB call (Advisable)
2. Using Local storage you can store the data in the browser to push it to next_page.php https://www.w3schools.com/Html/html5_webstorage.asp
2a. In the first page
<script>
localStorage.setItem("name", "John");
localStorage.setItem("email", "John#test.com");
</script>
2b. In second Page
<script>
var name = localStorage.getItem("name");
var emaeil = localStorage.getItem("email");
</script>
3. Using browser session storage https://www.w3schools.com/jsref/prop_win_sessionstorage.asp
3a. In the first page
<script>
sessionStorage.setItem("name", "John");
sessionStorage.setItem("email", "John#test.com");
</script>
3b. In second Page
<script>
var name = sessionStorage.getItem("name");
var emaeil = sessionStorage.getItem("email");
</script>
I need some advise handling a form submit and page redirect. I have two pages, where the first is a landing page with a simple form, when user select a criteria and submits it, he is redirected to page2 that displays tabular data and some query related info.
When Submiting Page1 Form, data is passed in the url :
for ( var key in dataArray )
{
if ( dataArray[key] )
{
if (queryStr != "")
{
queryStr += "&" ;
}
queryStr += key + "=" + dataArray[key];
}
}
var url = "page2.html?" + queryStr;
window.location.href = url;
On the other hand, I am handling this POST using $_GET['xxx']), then build a query accordingly.The issue is not handling POST & GET requests but handling errors..
I dont like is that if the user types something in the url www.site.com/page2.html?Q1=red -> www.site.com/page2.html?Q1=red545454 it will logically not pass the server side validation and therefore just display an empty page template without data, which kind o bothers me.. Also if the user tries to load page2.html without any posted data(querystring).
I would like upon page2.html load event, check if there are any posted values, if not redirect back.. Is this the correct way of handling it? Thanks
You doesn't submit form through POST method because "on submitting" you usewindow.location.href (redirect) with param Q1 in query string.
If you want see only url like www.site.com/page2.html do next: set action to your form as action="www.site.com/page2.html",instead adding variable to QUERY_STRING dynamically insert Q1 in any hidden element like:
document.getElementById('Q1_ID').value = dataArray[key];
After call like document.forms[0].submit();. Now variable Q1 in $_POST['Q1'] and url look as www.site.com/page2.html.
An elegant way to handle this would be to submit your form using Ajax and respond with validation errors or success message. In case of errors, show them on the current page otherwise redirect user to whatever page you want.
When I save payment detail in CIM hosted popup form after saving data massage display like
'your information has been saved', I need to call at that time my java-script function, Is it possible?
This JavaScript should do the trick:
AuthorizeNetPopup.options.onPopupClosed = function() {
// your JavaScript code here
};
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.
I am writing a simple form submit function for a specific site.
The script fills the specific form on the current page and submits the form. It MUST also fill the second form which appears after the first form is submitted and submit this form too.
That is there are 2 forms that must be filled and submitted.
Problem however, is that on a normal page the script fills and 1st form and submits it. After submission however, the script stops working! I want to continue execution!
I've done it by mistake on a page that had 2 frames! most pages don't have frames!
function FillFirstForm(){
doc=document;
//Some code removed from above...Fill Values
doc.forms[0].name.value = answerarray[1];
doc.forms[0].address.value = answerarray[2];
doc.forms[0].phone.value = answerarray[3];
doc.forms[0].username.value = answerarray[4];
//And Press Button
doc.forms[0].submit.click();
iTimer=setInterval(FillSecondForm,5000);
return true;
}
function FillSecondForm(){
clearInterval(iTimer);
doc.forms[0].tags.value = answerarray[5];
doc.forms[0].reference.value = answerarray[6];
document.forms[0].submit.click();
return true;
}
The basic rule is that a classical form submission halts all execution of scripts of the page, and loads the next page. No way to do anything about that.
You may have to switch to sending your form's contents using Ajax. That will leave the current page alive, and allow you to do as many submits as you want to.
A very easy way to achieve this is the jQuery form plugin. It takes much of the manual hassle out of the process.
Can you call FillSecondForm() function on body load of second form, once first form submitted.
You could POST the first form with AJAX, and then submit the second form after receving the response for the first form.
Something like this perhaps:
function FillFirstForm() {
var post_data = 'name='+escape(answerarray[1]);
post_data += '&address='+escape(answerarray[2]);
post_data += '&phone='+escape(answerarray[3]);
post_data += '&username='+escape(answerarray[4]);
// TODO: make this cross browser :)
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if ( req.readyState == 4 ) { // The request has finished
if ( req.status == 200 ) {
FillSecondForm();
}
else {
// Deal with errors here
}
}
};
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.open('POST', '/submit_url', true);
req.send(post_data);
}
W3 schools has a tutorial on AJAX here: http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp, and there are many more on the web.