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

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;

Related

Sending data from javascript to php to generate a pdf but doesn't work

I am using JavaScript to take the info from a form completed by the user, then sending this data to PHP and generate a PDF with FPDF. The problem is I want the browser to ask the user to save the PDF or view it online but
I cannot figure out how. The PDF generates correctly but only when I save it directly to a certain path specified by me.
The question is how do you guys send data from JavaScript to PHP to generate a PDF file then the browser asks the user to open or download, Or how can I make a function where the user can retrieve this PDF.
The JavaScript:
function senddata() {//this activates when i push a button not a submit
var peticion = new XMLHttpRequest();
peticion.open('POST', 'generatepdf.php');
var nueva2 = {};
var key;
for (i = 0; i < 6; i++) {
key = document.forms[0].elements[i].id;
nueva2[key] = document.forms[0].elements[i].value;
}//here i take my data from the form and make an object
var json = JSON.stringify(nueva2);//here i tranform my object to json string so i can send it to my php
var parametros = "json_string=" + json;//here I do this so later I can easily transform the $_POST to an array in the form json_decode($_POST["json_string"],true);
peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
peticion.send(parametros);//it sends ok
}
The PHP with the FPDF class and things
<?php
require('fpdf/fpdf.php');
require('functions.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
$datos=json_decode($_POST["json_string"],true); //here i have my data in an array format so i can use the parameters to fill my pdf fields
//...lots of pdf things here...//
$pdf->Output('F',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this works but never ask the user
//$pdf->Output('D',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this should force a dowload or send to the browser but doesnt work
//$pdf->Output();//this should send to the browser but doesnt work
}
To view your PDF inline to the browser, you should use the I variable instead. View full documentation here.
Also I don't think outputting the file in two methods at the same time works. It might conflict each other. The best way to do that is to test each method and if it does conflict each other just simply add a condition for the user to decide whether he/she wants to download or view it in the browser. Hope this helps.

Checking if a sessions is empty, unsetting it, and then sending $_POST data onclick

I have two possible sets of information to export to another PHP page whenever i click a button.
One of them is a session. It's something like this:
$_SESSION['excel_name']['Main_'] = "Main_".date("y_m_d_Hi");
$_SESSION['excel_array']['Main_']['Plan1'] = array();
The post data sends the same information, but doesn't save it in a session to prevent conflict between too many sessions. So what i want to try, is to check if there is a session set. If there is, i'll unset it, and send the $_POST data. When there isn't, i'll set one. I have tried doing this:
session_start();
if(isset($_SESSION) && !empty($_SESSION)) {
unset($_SESSION['Main_']);
unset($_SESSION['Plan1']);
unset($_SESSION['excel_array']);
$_POST['excel_name']['Main_'] = "Main_".date("y_m_d_Hi");
$_POST['excel_array']['Main_']['Plan1'] = array();
} else {
$_SESSION['excel_name']['Main_'] = "Main_".date("y_m_d_Hi");
$_SESSION['excel_array']['Main_']['Plan1'] = array();
}
The logic might seem a little weird for some of you, but i'm almost certain it would work... But. I wanted to do this in a button. Reason being, whenever i click the button, I export the information to the next PHP page. I want to check for these conditions before sending the information, not in the moment i load the page.
Is it possible?
There is several way to do it, but before reading my answer, please note that javascript verification can be edited and exploited maliciously.
You could do an AJAX request to a php page that would implement your logic and return a code 200 or 401. Then you can act before the next page loads.

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

passing a value from one file to another javascript

I have a file called functions.js where I have the functiom sum which computes the score that a student takes at a test. I want that sum to be printed into a table in the file admin.php so that the administrator sees all the scores that each student has.
So how can I pass the sum variable to another file? I tried calling the function using the onlick action but that didn't work
I guess you probably want something like this
document.getElementById('saveScoreButton').onclick = {
var r = new XMLHttpRequest,
message = document.getElementById('message'),
score = sum();
message.innerHTML = 'Saving your score; please wait a second';
r.open('get', 'savescore.php?score=' + score, true);
r.send(null);
r.onreadystatechange = function () {
if (r.readyState == 4 && r.status == 200) {
message.innerHTML = 'Saved your score';
}
}
}
This passes the score to a PHP programme savescore.php when you click a button with id saveScoreButton. The PHP programme then has to retrieve it using $_GET["score"].
Note that this would be easy for the user to trick if they understand javascript and see what is happening. They could just type 'savescore.php?score=100' in the browser's address bar. If you want a secure solution the javascript should only pass the user's answers to the PHP programme, which would then mark the test and sum the results.
It is also possible to use the POST method instead of GET to pass a value:
...
r.open('post', 'savescore.php?score=' + score, true);
r.send('score=' + score);
...
Then pick it up in the PHP programme using $_POST["score"].
As mentioned in comments, if you want to compare/tabulate scores, then savescore.php will need to store the values in a database or file so that they can be retrieved by admin.php.
Javascript is ran client-sided, PHP is ran server-sided. Therefor, you have to code something in your javascript which alters the HTML page returned by the PHP script, displaying the result.
Once all of your files are loaded on the client, there isn't a concept of separate js files. The client (browser + javascript) and server (php) are 2 separate entities. When your data is one place the other has no clue it exists. Either research ajax as a method of communicating between the 2 locations or use a form and submit the page to the server.
Good overview of how the server and browser communicate: How does the communication between a browser and a web server take place?
Basics of Form submission: http://www.htmlgoodies.com/tutorials/forms/article.php/3479121/So-You-Want-A-Form-Huh.htm
Basics of Ajax: http://webdesign.about.com/od/ajax/a/aa101705.htm
Ajax with PHP: http://www.switchonthecode.com/tutorials/simple-ajax-php-and-javascript

collect data from a form hosted on another site

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.

Categories

Resources