Calling JS Function on Form Submit - javascript

I have created a JS function which executes fine when it's included an the 'onclick' action of standard HTML link tag as follows:
test
However where I really want to use this function is on the 'onsubmit' action of a form but when I include it as follows the function no longer seems to be executing:
<form action="page.pl" id="disable-submit" name="status-form" method="POST" onsubmit="return fb_CheckPermission('publish_stream');">
What the 'fb_CheckPermission()' JS function basically does is use Facebook Connect to check to make sure the user has granted us a specific permission and if not it tells Facebook Connect to prompt the user to grant the permission. Here is the code for the JS function:
1. function fb_checkPermission(permission) {
2. FB.ensureInit(function() {
3. FB.Facebook.apiClient.users_hasAppPermission(permission, function (hasPermissions) {
4. if(!hasPermissions){
5. FB.Connect.showPermissionDialog(permission,function (status){
6. if(!status) {
7. if(permission == 'offline_access') {
8. // save session
9. }
10. }
11. });
12. }
13. });
14. });
15.}
What this code does is as follows:
Line 2: Make sure Facebook Connect JS library is loaded
Line 3: Checks to see if the current Facebook Connect user has granted a specific permission
Line 5: If the permission hasn't been granted then prompt the user with the permission dialog
Line 7: In the case of the 'offline_access' permission save the session key once granted
The user experience I'm trying to achieve is that when a user submits the form I'll check to see if they have granted a specific permission and if not prompt them for the permission before submitting the form. If the user has already granted the permission the form should just submit. For those users who are prompted the form should submit after they either choose to grant the permission or if the deny the request which I believe the fb_checkPermission() JS function is handling correctly right now. What I'm not sure is if there is some kind of JavaScript issue with how this works on form submission.
As I mentioned, this JS function works perfectly as an onclick action but fails as an onsubmit action so I'm pretty sure that this has something to do with how JavaScript treats onsubmit actions.
I'm stuck so I really appreciate your help in figuring out how to change the JS function to produce my desired user experience. Thanks in advance for your help!

The reason your "click on anchor" works is because it does not change your page (location) while all of the Facebook asynchronous calls finish.
When you attach the same function to the submit handler the function returns before Facebook stuff gets actually executed, and it does without returning "false" causing the form to proceed with submission earlier than you want it to.
What you need to do is return "false" at the end of your onSubmit function to prevent submission and give time to Facebook stuff to finish and then manually submit form at places you want it to be submitted by calling:
document.getElementById('disable-submit').submit();
(The handler will not be called if submittion is triggered from the script.)
Unfortunately I don't have Facebook SDK at hand so I can't write the code that I'm sure works 100%, but it's something along these lines:
function onSubmit () {
doStuffAsynchronously(function () {
if (everythingIsOK) {
// proceed with submission
document.getElementById('formId').submit();
}
});
return false;
}

Try putting the javascript call on the input you are using to initiate the submit.

I think basically that your browser tends to use default validation form (page.pl / method POST) instead of doing what you think it does
Try this
<form action="page.pl" id="disable-submit" name="status-form"
method="POST" onsubmit="returnFbChPermissionAndPreventDefaultAction();">
<script type="text/javascript">
var returnFbChPermissionAndPreventDefaultAction = function(){
//prevent default
if (event.preventDefault) {
event.preventDefault();
}
//specific for IE
valueOfreturn = fb_CheckPermission('publish_stream');
event.returnValue = valueOfreturn;
return event.returnValue ;
}
</script>

Related

HTML form with PHP - submitting and staying on same page [duplicate]

This question already has answers here:
PHP form - on submit stay on same page
(11 answers)
Closed 5 years ago.
I have a form on a website (www.mywebsite.com). I have a PHP script that sends me an e-mail with information when somebody submits a form on my website. But with action="submitform.php" in the form, it updates the site to the URL www.mywebsite.com/submitform.php. I would like it to stay on the main site (index).
The solution for this: I added header("Location: http://mywebsite.com"); die(); to my PHP code. In this way, users will be redirected to the main site when they have submitted code.
However, this pose a new problem.
Whenever someone submit the form, I would like to display a message such as "Mail has been sent". To make this work, I tried to have a small JavaScript code, basically
document.getElementById("message").innerHTML = "Mail has been sent."
... and <div id="message"></div> to my HTML code. Which works...... However, due to my PHP script redirecting me to my website (with header) when someone is submitting the form, the message will only be displayed for like half a second or something.
Anyone know any workarounds for this? Thanks in advance. I can provide more detail if needed, but my problem should be clear from this. Hope anybody is able to spot my mistake...
I use javascript and ajax for most of my form post. Works wonderful.
Ajax can grab the form information in a form object or pass it as an array. URL is your php proc page, there it will come back with whatever you "print/echo" in a data object that is passed into the success function.
Use this in your HTML,
<input type="button" onclick="submitForm();" value="Submit">
Javascript,
function submitForm(){
//Validate INPUT first. Then grab the form.
form = new FormData($('#frmIdHere')[0]);
$.ajax ({
type: 'POST',
dataType: 'text',
url: url,
data: form,
success:data => {
//Success message here.
//clear form here.
},
error: () => {
// error message here.
}
});
}
php process file use,
$inputFromForm = (isset($_REQUEST["NameOfInputFromForm"])) ? strip_tags($_REQUEST["NameOfInputFromForm"]) : "-";
Without using Ajax (which means you can send the form without refreshing the page), you have two options. Either send the form to a different file, process it, and redirect back - but with a GET parameter to indicate success or failure. Alternatively, just post to the same page (so the handling of the form happens in the same page - I recommend the first alternative).
If you want to use the post-redirect-get pattern, you would use
header("Location: /?status=success");
exit;
when the form was successfully handled in your submitform.php file.
Then you just check what the message in $_GET['status'] was, and display the message accordingly in your index.php file.
if (isset($_GET['status']) && $_GET['status'] == 'success') {
echo "Your message was successfully sent!";
}
This logic can be developed further to have different parameters, to post messages for success and failure, if that's needed for the application.
assumption: you want the user to stay on the page with the form.
in that case you probably don't return false / stop event propagation in your calling code.
let's say, you call your ajax like this:
<form onsubmit="submitform(this);" ...>[form]</form>
onsubmit does the following, it executes anything that is in it's attribute value (submitform(this)) and if it returns some non-false value, it will actually do the action of the form, as if the onsubmit wouldn't have existed. I assume this is exactly what's happening in your case.
To avoid this:
<form onsubmit="submitform(this); return false">[form]</form>
the return false will stop the form from being submitted, after it was already submitted by ajax. this also has the benefit of still working, if the user has javascript disabled.
if my assumption is false however ...
if you want to refresh the page, don't even use ajax and just add a parameter to the url that triggers the message to show. or add the message to the session in php and clear it out of there after displaying.
To doing this, You can use a SESSION var to store message send type (success or failed) and test it everytime on main page, if exist, display message and unset $_SESSION var !
Like this :
MAIN
if(isset($_SESSION['message'])){
if($_SESSION['message'] == 'success'){
echo "Yeah !";
}else{
echo "Problem";
}
unset($_SESSION['message']);
}
MESSAGE
if(mail()){
$_SESSION['message']='success';
}else{
$_SESSION['message']='error';
}
You can set interval and then redirect them to desired page.
<script>
setInterval(function(){ window.location.href="http://mywebsite.com" }, 5000);
</script>

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();
}

How to find the URL of an external site's Javascript submit

I will do my best to try to explain this.
I am scraping a website for it's elements to then output in a different format. The problem that I am experiencing is the way that this site directs the user throughout the site is through a Javascript redirect.
When checking the 'a href' tag, this is the Javascript that shows up
javascript:doParamSubmit(2100, document.forms['studentFilteredListForm'], 'SSC000001MU9lI')
The SSC000001MU9lI changes for each element that it redirects to.
Is it possible to find a URL using this Javascript, so that I can reach the HTML page externally?
EDIT: Here is the doParamSubmit and doSubmit classes:
function doParamSubmit(event, form, parameter) {
form.userParam.value = parameter;
doSubmit(event, form);
}
function doSubmit(event, form)
{
// Make sure if something fails that the form can be resubmitted
try
{
// If this form has not been submitted yet... (except for IE)
if (allowSubmit == true && form != null && (submitted == false || isInternetExplorer6() || isInternetExplorer7()))
{
submitted = true;
form.userEvent.value = event;
// Fix for IE bug in which userEvent becomes a property array.
if (form.userEvent.length)
{
form.userEvent[0].value = event;
}
// Disable the form so the user can't accidentally resubmit the page
// (NOTE: this doesn't disable links (e.g. <a href="javascript:...">)
disableForm(form);
// If there is a populate form function, call it. If there are spell check fields on the
// page, populateForm is used to set hidden field values.
if (this.populateForm)
{
populateForm();
}
saveScrollCoordinates();
// resetSessionTimeout();
try
{
form.submit();
}
catch(e)
{
// Exceptions thrown here are only caused by canceling the submit in onbeforeunload, so ignore.
submitted = false;
}
}
if (allowSubmit == false)
{
alert(grabResource("message.pageLoading"));
}
}
catch(e)
{
submitted = false;
throw e;
}
}
I see 2 approaches.
You use a javascript enabled browser such as http://nrabinowitz.github.io/pjscrape/. I am not sure if you intend to just follow the links or instead grab the URL for some other use so your mileage may vary.
Find the doParamSumit() function in their page/scripts and analyze it to understand how it gets the URL - the one you have as an example looks like it grabs the action from a form perhaps? Once you know how the function work you might be able to harness that info in your scraping by using some regex to find URLs that match the doParamSubmit pattern and going from there. It's hard to say without seeing the function itself as well as the other links like it though.
Regardless of which method you choose I would begin by understanding the function - look for it in the code or loaded js files (you can also you things like javascript debuggers on most browsers to help you find it) and see what happens - it might be super obvious.
Also keep in mind that this might be a POST for a form - in which case the result of you following that link may not work if it expects valid form data.
Edit I see that you posted the function. It simply submits the form listed in the second parameter i.e. 'studentFilteredListForm'. While I don't think your scraping will go to far chasing forms you can still get the URL either with javascript if your scraper lets you (something like $('form[name=studentFilteredListForm]').attr('action') or using whatever language your are using for the scraper i.e. find the form and extract the action url (remembering that if there is no action it is probably posting back to the current URL)
But again... you might first manually get the URL of the form and see where that gets you. You might just get a page with form errors :)

simple javascript works in console but not greasemonkey

I'm just trying to submit the already-filled-out login form at this site:
http://portal.mypearson.com/mypearson-login.jsp
In firefox console, I can type this:
doSubmit();
and it works fine but it doesn't work in greasemonkey. By 'doesn't work' I mean nothing happens. I can do document.forms[0].submit() but the page comes back complaining that the user and pass variables aren't set correctly.
What do I need to do to get the script that works in console to work in greasemonkey?
Have you tried taking the functionality from the doSubmit() function and performing those actions?
A quick inspection of the code looks like this:
if (!validate(displayForm)) {return false;}
loginForm.loginname.value = displayForm.loginname.value;
loginForm.password.value = hex_md5(displayForm.password.value.toLowerCase());
loginForm.encPassword.value = 'Y';
loginForm.submit();
return true;
It looks like the form is actually just copying its values to another form and then submitting the other form.
You could first start by removing the onsubmit event by using:
displayForm.setAttribute("onsubmit", null)
Or you could just bypass the display form all together and go straight to the source. Your greasemonkey script would look something like this without all the extra steps:
// Setup your authentication values here
var username = "(Your user name)";
var password = "(Your password)";
// Add your variables to the submit form
loginForm.loginname.value = username;
loginForm.password.value = hex_md5(password.toLowerCase());
loginForm.encPassword.value = 'Y'
// submit the form
loginForm.submit();
That will bypass the form that is displayed to the user all together.
Hope that helps.

Javascript return issue

This problem has just become apparent in some historical code and seems to be an issue relating to IE8 + and FF4 +
I have a js file that validates a contact form, one particular section calls a function to open a new window with some info for the user. At this point the script seems to ignore my valid = false variable (which is flagged to stop form submission)
function showFormat() {
var myWindow;
myWindow = window.open("http://url/page.html","Postcode_Information","location=1,status=1,scrollbars=1,width=640,height=400");
myWindow.moveTo(50,50);
}
Above code is causing the issue. i've tried adding valid=false; return valid; to the end of the function but it is apparently being ignored. Adding this to the begining of the function means that the validity is correct and the form doesnt submit but obviously my new window doesnt open.
EDIT TO EXPLAIN IN MORE DETAIL
My js file has a series of validation functions (checking username, address, email address validity etc). A variable is initialised called valid which will always be true unless any user input does not validate, in which case valid = false.
If valid = false then an if statement is run which checks against a number of variables in order to determine which area of the validation has caused the problem and will flag up an appropriate prompt. Most of these are done via a message box (I inherited this code and am merely trying to get it working) but one prompt opens up a new window. If any of these prompts are called at all then the form should not be submitted.
The problem I am having is that when this new window opens (and this is the only prompt causing this issue) the form will still submit.
See code below for an example of when these prompts are called:
if (!valid) {
if (emailNoAddress == true) {
alert('You have requested to receive more information by email from other company(ies) but have not provided email address details – Please correct this below');
highlightEmail();
}
else {
if (contactDetails == false) {
alert('Please provide your email address details. We will not send you future correspondence and offers by email if you prefer us not to.');
highlightAddress();
highlightEmail();
}
else {
if (postcodeGiven == false) {
if (dataform.pcode.value == "") {
alert('Please enter a valid postcode');
}
else {
showFormat();
}
}
else {
if (questionsAnswered == false || countryGiven == false) {
alert('Please choose an answer from the options provided');
}
else {
//alert(checkstr);
alert('Could you please complete the questions missing details');
}
}
}
}
}
So you see, my function can only be called when !valid in which case the form should not submit but as soon as I execute the new window function showformat() it allows the form to be submitted.
EDIT - UPDATE
I've managed to narrow the problem down slightly in that after the new window opens, no more script is executed (i've tried adding a few alert messages to check the value of valid but they are not shown - I've also tried adding a breakpoint while debugging with Firebug but this is not hit) and the form submits regardless...
EDIT - UPDATE
Beacuse this was a time-critical issue, for the moment I have just put all the text from the pop-up window into an alert and call that instead of the function. When I have any more time to spend investigatin I will update.
Are you having the onsubmit event defined on the form tag? If so then add the keyword return in the onsubmit event like shown below
onsubmit = "return some_function" and in the function called u have to specify return false. Then u will be getting wat u want.
Hope this helps you.
Here is the SImple example which works as u need. Try this and correct ur code accordingly
<html>
<head>
<script type="text/javascript">
function validate()
{
if(document.forms[0].stext.value!="")
{
return showformat();
}
else
return false;
}
function showformat()
{
window.open("new.html","");
return false;
}
</script>
</head>
<body >
<form name="sample" action="onsel.html" method="post" onsubmit="return validate()">
<input type="text" name="stext" id="stext" value="" />
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Hope this helps you

Categories

Resources