Input field is not recognizing dynamic data - javascript

I have a reverse geolocation code which returns a formatted address to which i then dynamically add to a google map address field which should automatically update the map. The problem is that the only way the google map will update is if I add a space bar or any type of input in the input field as if it does not recognize the data i am dynamically adding via document.getElementById.('address').value=
I have tried to simulate key events to the input field to make it believe there was data added, I have tried to use the google api to just manually refresh the map which had no effect, I have tried to split the string being added after it was added to see if it recognizes a change, I have also tried to set the length of the input field to + 1 to see if that worked. I really have no clue what to do at this point. Here is my current attempt to make the input field recognize there is a value.
<span class="findme" id="find1"><i class="fa fa-compass" style="font-size:33px;color:green;"></i></span>
<script>
var find1 = document.getElementById("find1");
var info = document.getElementById("info");
var selector = [];
find1.addEventListener("click", function() {
selector.push("jform_fulladdress");
getLocation();
}, false);
function putInDom(address){
if(selector.length == 1){
//one field for address
var field = document.getElementById(selector[0]);
field.value = address;
}
}
function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(getAddress);
} else{
info.innerHTML="Geolocation is not supported by this browser.";
}
}
function getAddress(position){
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var apiurl = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+lat+','+lon+'&sensor=true';
var url = 'ba-simple-proxy.php?url='+encodeURIComponent(apiurl);
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = function() {
if(this.status==200 && JSON.parse(xhr.responseText).contents.results.length > 0){
var result = JSON.parse(xhr.responseText).contents.results[0].formatted_address;
putInDom(result);
} else {
info.innerHTML = "Could not find your location.";
}
}
xhr.send();
}
jQuery('form').change(function() {
var splAd = document.getElementById('jform_fulladdress').value;
splAd = splAd.split(',').slice(0, 2).join(',');
document.getElementById('jform_maps_search').value= splAd;
document.getElementById('jform_fulladdress').value= splAd;
jQuery('jform_fulladdress')
.trigger({
type: 'keypress',
which: character.charCodeAt(49)
});
}).click(function() {
var splAd = document.getElementById('jform_fulladdress').value;
splAd = splAd.split(',').slice(0, 2).join(',');
document.getElementById('jform_maps_search').value= splAd;
document.getElementById('jform_fulladdress').value= splAd;
jQuery('jform_fulladdress')
.trigger({
type: 'keypress',
which: character.charCodeAt(49)
});
});
</script>

Related

How do i access a filemaker script with javascript in Web Viewer using Apple Mapkit?

I have Filemaker 18 with a Web Viewer using Apple Maps. When I move a pin on the map I want to send the coordinates to a filemaker script that writes to 2 fields. The problem is I can not trigger the script. The database is hosted on a FM Server 18. I have tried these 3 approaches but I am not even able to run a simple "Hello" script. The database name is WEBMAP.fmp12 . Here is how I have tried to run the script. I get no response:
1)
var theURL = "fmp://$/" & Get ( FileName ) & "?script=Hello&param=" + lat +"|"+ long;
window.location = theURL;
2)
var theURL ="fmnet://ip_address_of_server/WEBMAP.fmp12?script=Hello&param=" + lat +"|"+ long;
window.location = theURL;
3)
var theURL = "window.location = "fmp://$/WEBMAP.fmp12?script=Hello&param=" + lat +"|"+ long;
window.location = theURL;
In fact I notice that when I have anything after showing a popup (then I want to run the script) the map is blank whatever I add like "alert("hello").
Here is my js file in Filemaker 18:
var message = document.getElementById("message");
var center = new mapkit.Coordinate(x,y); //
mapkit.init({
authorizationCallback: done => {
done(
"<<$$JWT.TOKEN>>"
);
}
}); //alert("<<$$JWT.TOKEN>>");
var map = new mapkit.Map("map", {
showsScale: mapkit.FeatureVisibility.Visible,
center: center
});
var marker = new mapkit.MarkerAnnotation(map.center, {
draggable: true,
selected: true,
title: "Dra meg og slipp!"
});
marker.addEventListener("drag-start", function(event) {
// No need to show "Drag me" message once user has dragged
// event.target.title = "";
// Hide message
message.style.display = "none";
});
marker.addEventListener("drag-end", function() {
// center map to marker when moved
map.setCenterAnimated(marker.coordinate);
// hide message after seconds
window.setTimeout(function () {
message.style.display = "none";
}, 3550);
// message to show after move
var lat = marker.coordinate.latitude;
var long = marker.coordinate.longitude;
var message = document.getElementById('message');
message.innerHTML = "<p>Vi har lagret posisjonen</p>Latitude: " + lat + " <br />Longitude: " + long;
message.style.display = "block";
//alert("Hello"); ** this alert works!! **
//var test = ‘Hello World!’; alert(test); ** this line gives me a blank map just adding a "var statement" **
var theURL = "fmp://$/" & Get ( FileName ) & "?script=Testaccess&param=" + lat +"|"+ long;
window.location = theURL;
// alert(theURL) here gives me blank map
}); // END drag-end
map.addAnnotation(marker);
var lat = marker.coordinate.latitude;
var long = marker.coordinate.longitude;
var borchbio = new mapkit.CoordinateRegion(
new mapkit.Coordinate(lat,long),
new mapkit.CoordinateSpan(0.002, 0.002)
);
map.region = mymap;
map.mapType = "hybrid";map.setCenterAnimated(new mapkit.Coordinate(x,y), true);
The solution was to set "fmurlscript" rights. Thanks to #michael.hor257k and more detailed help from #paul_tuckey at the Claris Community. His answer here.
File-->Manage-->Security-->Advanced Settings-->Extended Privileges,
Select fmurlscript
Click Edit,
Add the Privilege set that is aligned to your Account Name to the selected fmurlscript
With this code I am able to run a FM script from javascript. Here is the code that triggers the script. Notice that when my database is "WEBMAP.fmp12" I only use "WEBMAP" as the name. I am sending the lat and long to the script that does stuff with it (converts it and writes to the post). The "fmp18://" targets specific version 18.
var theURL = "fmp18://$/WEBMAP?script=My_FM_Script_Name&param=" + lat +"|"+ long;
window.location = theURL;

How to assign input id to variable for concat with url api call

I'm loading data from api into html table and would like to use user input field to change api call.
<input id="stockInput" value="AAPL"></input>
<br/>
<button id="submit">Submit</button>
const stocksBody = document.querySelector("#stocks-table > tbody
#data");
var input = $("#stockInput").val();
var url = "https://api.iextrading.com/1.0//stock";
var quote = "/quote";
function setup() {
var button = select("#submit");
button.mousePressed(loadData);
}
function loadData(){
const request = new XMLHttpRequest();
request.open("get", url + input.val() + quote);
request.onload = () => {
try {
var response = JSON.parse(request.responseText);
console.log(response);
populateData(response);x
} catch (e) {
console.warn("Could not load data!");
}
};
request.send();
I expect stock symbol entered by user to return stock data.
You are calling .val() twice.
Change this line:
request.open("get", url + input.val() + quote);
// ^^^^^^ - remove

How to insert form into mysql without leaving the page (javascript+html)

I'm trying to insert a new user into mysql. I have tried to use jQuery, but it doesn't seem to be working. I tried to use pure javascript, but it's the same. It has no response after I click on the button. What's wrong?
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var shop = document.getElementById("shop");
var http = new XMLHttpRequest();
http.open("POST", "http://xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "ac=" + acR + "&pw1="+pw1 "&shop="+ shop;
http.send(params);
http.onload = function() {
alert(http.responseText);
};
}
There's a quite a few problems in your JS code, I've tidied it up here and run it locally to a page called xyz.php, so that'll get the AJAX call to work but you'll need to post your PHP code to get any help with your DB queries
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var http = new XMLHttpRequest();
// removed the http:// protocol, assuming you're going for a local AJAX call
http.open("POST", "xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// get values of the form fields, don't submit the full element
// also added the plus (+) character before the final pw1
var params = "ac=" + acR.value + "&pw1=" + pw1.value;
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I've attached a screen shot showing Chrome Dev Tools happily recording successful AJAX requests
Try to use a JQuery post.
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
$.post( "xyz.php", { ac: acR, pw1: pw1 })
.done(function( data ) {
alert( "Data inserted: " + data );
});
Backend handles this post and then implement the insert action for example in NodeJs(express)
app.post("/xyz", function(req, res, next) {
var obj = {};
obj[acR] = body.ac;
obj[pw1] = body.pw1;
mysql.insert(obj);
});

Load a JavaScript event the last in CRM form

I have one image saved in Notes with every form in my CRM Online 2013 custom entity. I am using the following code to query the image and show it in an Image tag in a Web Resource on the form. For debugging purposes I was calling the following code through a button, but I want this process of querying the Notes and displaying the image in the web resource to be automatic when the form load. Here is my code:
<html><head><meta charset="utf-8"></head>
<body>
<img id="image" src="nothing.jpg" style="width: 25%; height: auto;" />
<script type="text/javascript">
$(windows).load(function()
{
var recordId = window.parent.Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
var ODATA_ENDPOINT = "XRMServices/2011/OrganizationData.svc";
var objAnnotation = new Object();
ODataPath= serverUrl+ODATA_ENDPOINT;
var temp= "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
var result =serverUrl + ODATA_ENDPOINT + temp;
var retrieveRecordsReq = new XMLHttpRequest();
retrieveRecordsReq.open('GET', ODataPath + temp, false);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.onreadystatechange = function ()
{
if (this.readyState == 4 /* complete */)
{
if (this.status == 200)
{
this.onreadystatechange = null; //avoids memory leaks
var data = JSON.parse(this.responseText, SDK.REST._dateReviver);
if (data && data.d && data.d.results)
{
SuccessFunc(JSON.parse(this.responseText, SDK.REST._dateReviver).d.results);
}
}
else
{
alert(SDK.REST._errorHandler(this));
}
}
};
var x = new XMLHttpRequest();
x.open("GET", result, true);
x.onreadystatechange = function ()
{
if (x.readyState == 4 && x.status == 200)
{
var doc = x.responseXML;
var title = doc.getElementsByTagName("feed")[0].getElementsByTagName("entry")[0].getElementsByTagName("content")[0].getElementsByTagName("m:properties")[0].getElementsByTagName("d:DocumentBody")[0].textContent;
document.getElementById('image').src ="data:image/png;base64,"+title;
}
};
x.send(null);
});
</script>
</body></html>
I have removed the button tag..now I want this the query to happen on page Load, but nothing happens when I refresh the form. In my opinion the function loads before the annotation loads. Is there a way to make it wait and load the last?
If you want to wait for the parent window to load I think $(windows).load(myFunction); should do the trick.
Maybe $ is undefined because you did not add jQuery to your webressource.
There are also a few little mistakes and unattractive things:
First:
You will get a wrong server url.
If you want to access the Xrm-object in a webresource you always have to use window.parent.Xrm or you put it in a variable var Xrm = window.parent.Xrm;
For example:
var Xrm = window.parent.Xrm;
var recordId = Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
Second:
The ODataPath variable is not declared. Use var ODataPath= serverUrl+ODATA_ENDPOINT; instead. By the way the value of the ODataPath has nothing to do with OData. It is more the REST-Endpoint of Dynamics CRM.
My script would look like this:
var Xrm, recordId, serverUrl, restEndpointUrl, odataQuery, fullRequestUrl, xmlRequest;
Xrm = window.parent.Xrm;
recordId = Xrm.Page.data.entity.getId();
serverUrl = Xrm.Page.context.getServerUrl().toString();
restEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc";
^ I think a '/' was missing there
odataQuery = "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
fullRequestUrl = restEndpointUrl + odataQuery;
I also dont understand why you use the second HttpRequest.
All of this code is not tested.

Can't pull up user info right after entered in indexedDB

I have a register form with an indexedDB. I have resgister/log in working. I've been trying different things to get a new register to login as soon as they register but im not sure what's going. It won't work. The localStorage sets like it should but it won't bring up the user's data.
JS:
function addObject(){
if(confirm('Are you sure you want to resgister?')){
fName = document.getElementById('fName').value;
lName = document.getElementById('lName').value;
userName = document.getElementById('uName').value;
pass = document.getElementById('password').value;
email = document.getElementById('email').value;
dob = document.getElementById('dob').value;
tel = document.getElementById('tel').value;
bio = document.getElementById('bio').value;
terms = document.getElementById('terms').value;
school = document.getElementById('school').value;
//Need loop to find radio button values
radios = document.getElementsByName('gender');
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
gender=radios[i].value;
}
}
//set up transaction
var mytransaction = db.transaction(['users'], "readwrite");
//get object store
var myusers = mytransaction.objectStore('users');
//Add item
var request = myusers.put(new getUser(userName,fName,lName,pass,email,dob,tel,bio,terms,school,gender));
}
// Show all results.
if(document.URL.indexOf('admin.html') > -1){
mytransaction.addEventListener('complete', showUsers);
}
//Log in new users
loginCheck(userName,pass);
/*newLocal('user',user); */
//Reset Form Fields
resetForm();
}
This is the functions I use when someone logs in.
function loginCheck(user,pass){
db.transaction("users").objectStore("users").get(user).onsuccess = function(e) {
var loggedUser = e.target.result;
if(!loggedUser){
alert('Sorry, Username does not exist. Please try again.');
}else if(pass !== loggedUser.pw ){
alert('Incorrect log in combination. Please try again.');
}else{
loggedIn(loggedUser);
populateFields(loggedUser);
loginStyle(loggedUser)
}
}
}
function loggedIn(loggedUser){
var u=loggedUser;
alert('Welcome '+u.fn+' '+u.ln+' to Macroplay');
//Set localStorage
var signedin = 'user';
var username = u.userName;
newLocal(signedin,username);
}
function getValues(){
db.transaction("users").objectStore("users").get(localStorage.user).onsuccess = function(e) {
populateFields(e.target.result);
loginStyle(e.target.result)
};
;
}
From what I can see the first part adds the user to the DB and the second portion should behave as is I was just logging normally. But it won't pull up the info from the DB.
I've tried setting the new user to localStorage which is how I recognize a user currently loggedin but that also had no effect.
This is my site: http://www3.carleton.ca/clubs/sissa/html5
It looks like you're using the onsuccess handler in the loginCheck method, but you're not when calling put on the db. My guess would be that you're checking to see if the user exists before it's actually had a chance to be added. Try this:
//Add item
var request = myusers.put(new getUser(userName,fName,lName,pass,email,dob,tel,bio,terms,school,gender));
request.onsuccess = function () {
// Show all results.
if(document.URL.indexOf('admin.html') > -1){
mytransaction.addEventListener('complete', showUsers);
}
//Log in new users
loginCheck(userName,pass);
/*newLocal('user',user); */
//Reset Form Fields
resetForm();
}

Categories