Finding the distance between 2 points using Google Maps API - ajax

I am trying to find the distance between 2 points, one being from user input and the other an address from my database. I have put together the code below, which seems to work (I have test variables in place so no database pulls are being made for testing), however I have hit a wall; I cannot figure out why I need to click the button twice for the output to show?
Any help is much appreciated
CODE BELOW:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API Example: Extraction of Geocoding Data</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
<!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html -->
<script type="text/javascript">
//var globalAddr = new Array();
var globalName;
var xmlhttp;
var geocoder, location1, location2;
var distanceVal;
function initialize() {
geocoder = new GClientGeocoder();
}
function showLocation() {
geocoder.getLocations(document.getElementById("address1").value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the first address");
}
else
{
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
geocoder.getLocations(document.getElementById("address2").value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the second address");
}
else
{
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
calculateDistance();
}
});
}
});
}
function calculateDistance()
{
var glatlng1 = new GLatLng(location1.lat, location1.lon);
var glatlng2 = new GLatLng(location2.lat, location2.lon);
var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
var kmdistance = (miledistance * 1.609344).toFixed(1);
distanceVal = miledistance;
}
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function getData(str)
{
loadXMLDoc("getData.php?address="+str,function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x = xmlhttp.responseText;
var dnames = x.split("~~~");
var daddr = x.split("^^^");
daddr.shift();
dnames.pop();
var testArray = new Array('85281','18657','90210');
var shortest = 999999;
for(var i = 0; i <= testArray.length-1; i++)
{
document.getElementById("address2").value = testArray[i];//daddr[i];
showLocation();
//i get a blank alert 3 times here the first time, then I get the a value the 2nd time.. makes no sense!
alert(distanceVal);
if (shortest > distanceVal)
{
shortest = distanceVal;
globalName = dnames[i];
}
}
document.getElementById("results").innerHTML = globalName + " " + shortest;
}
})
}
</script>
</head>
<body onload="initialize()">
<form>
<p>
<input type="text" id="address1" name="address1" class="address_input" size="40" />
<input type="hidden" id="address2" name="address2" />
<input type="hidden" id="distance" name="distance" />
<input type="button" name="find" value="Search" onclick="getData(document.getElementsByName('address1')[0].value)"/>
</p>
</form>
<p id="results"></p>
</body>
</html>

When you call showLocation() in your getData() callback, that sets off two geocoder calls and if both are successful calls calculateDistance().
However, both those geocoder calls take time. The first getLocations() sets off a geocode request and lets it continue, to be dealt with in its callback. Within that function, there's another request which is dealt with in its own callback.
While those are waiting for results, the code execution has carried on and reached alert(distanceVal) even though calculateDistance() hasn't been called yet. Consequently distanceVal isn't set yet.
When you click the button again, the global distanceVal will have been populated through all the callback functions, so (even though the second set of geocodes/callbacks have not completed), it will have a value to display. However, if you change the values you are testing, you will find it's displaying the old value which is now incorrect.
Everything which depends on values found in a callback function must be processed within that callback function. If you move the display of data into calculateDistance() everything will be fine, because the data is available to that function.

Related

JQueryUI autocomplete search with Django not working

I am working on a project with Django, for a restaurant management system. I wanted to use an autocomplete feature to take orders at the table.
As far as I understand JQueryUI function autocomplete() is what I need.
However I cannot seem to get it to work.
Following is my my HTML code for the page. It works in such a way that once the number of people in the party is inserted the same number of form input fiels is inserted in the table by a Javascrip script.
addOrder.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script type="text/javascript" src={% static "js/jquery-3.3.1.min.js" %}></script>
<script src={% static "js/jquery-ui.min.js" %}></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script type="text/javascript" src={% static "js/createOrderIn.js" %}> </script>
<script type="text/javascript" src={% static "js/autocompleteDrink.js" %}></script>
<script type="text/javascript" src={% static "js/autocompleteMenu.js" %}></script>
<style>
.move {
margin: 30px;
}
</style>
<title>Add Order</title>
</head>
<body>
<div class="move">
<form action="/orders/addOrder" method="post" id="the-form" class="ui-widget">
<label> Party of </label>
<input type="text" id="people">
<input type="submit" class="btn btn-primary" value="Submit order">
</form>
</div>
</body>
</html>
This is the script I use to spawn new form input fields
createOrderIn.js
$(document).ready(function () {
var previous = 0;
var considered = 0;
$("#people").keyup(function ( ) {
var actual = this.value;
if(actual==null){
actual=1;
}
var toAdd = actual-previous;
previous = actual;
if(toAdd > 0){
for(var i=0; i<toAdd; i++){
considered+=1;
var htmlToAdd = $("<div class="+considered+"><input type=\"text\" name=\"menu_"+considered+"\" id=\"menu\"><input type=\"text\" name=\"drink_"+considered+"\" value=\"No drink\" id=\"drink\"><br></div>");
$("#the-form").append(htmlToAdd);
}
}
else{
for(var j=0; j<(-1*toAdd); j++) {
if (considered > 0) {
$("."+considered).remove();
considered -= 1;
}
}
}
});
});
The following are the relative Python/Django files
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.ordersIndex, name = "index"),
path('changeStatus/<int:pk>', views.changeStatus, name="changeStatus"),
path('addOrder', views.addOrder, name="addOrder"),
path('addOrderRender', views.addOrderRender, name="addOrderRender"),
path('getDrinks', views.getDrinks, name="getDrinks"),
path('getMenus', views.getMenus, name="getMenu"),
]
views.py (only function getMenus())
def getMenus(request):
print("I am called")
if request.is_ajax():
q = request.GET.get('term', '')
menus = Menu.objects.filter(name__contains=q)
results=[]
for menu in menus:
menu_json = {}
menu_json['name'] = menu.name
menu_json['n_courses'] = menu.number_of_courses
menu_json['price'] = menu.price
results.append(menu_json)
data = json.dump(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
And lastly this is the function that is supposed to use JQueryUI to make the ajax call and retrieve the possible menu's
autocompleteMenu.js
$(function() {
$("#menu").autocomplete({
source: "/orders/getMenus/",
});
});
As you can probably see from the getMenus() function in views.py I also print a check line ("I am called"), which sure enough does not get printed on console. Also even by switching the autocomplete() source parameter to a local array there is no result.
I do feel like I am doing some very naive mistake but I really cannot seem to figure it out (I am also pretty new with JQuery).
I think the error should be in the provided files, but I'll be happy to post edits in just in case
Thank you in advance!
I realized that the problem was due to the fact that I had to bind autocomplete to the id of the newly created id's (which I changed to classes). Also the JSON data must have a lable field, (and I had to use json.dumps(), not json.dump() :p).
The followings did the trick:
createOrderIn.js
$(document).ready(function () {
var previous = 0;
var considered = 0;
$("#people").keyup(function ( ) {
var actual = this.value;
if(actual==null){
actual=1;
}
var toAdd = actual-previous;
previous = actual;
if(toAdd > 0){
for(var i=0; i<toAdd; i++){
considered+=1;
var htmlToAdd = $("<div class="+considered+"><input type=\"text\" name=\"menu_"+considered+"\" class=\"menu\"><input type=\"text\" name=\"drink_"+considered+"\" value=\"No drink\" class=\"drink\"><br></div>");
$("#the-form").append(htmlToAdd);
$('#the-form').find('input[class=menu]:last').autocomplete({
source: "/orders/getMenus"
});
$('#the-form').find('input[class=drink]:last').autocomplete({
source: "/orders/getDrinks"
});
}
}
else{
for(var j=0; j<(-1*toAdd); j++) {
if (considered > 0) {
$("."+considered).remove();
considered -= 1;
}
}
}
});
});
views.py
def getDrinks(request):
if request.is_ajax():
q = request.GET.get('term', '')
drinks = Drink.objects.filter(name__contains=q)
results=[]
for drink in drinks:
drink_json = {}
drink_json['label'] = drink.name
results.append(drink_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
def getMenus(request):
if request.is_ajax():
q = request.GET.get('term', '')
menus = Menu.objects.filter(name__contains=q)
results=[]
for menu in menus:
menu_json = {}
menu_json['label'] = menu.name
menu_json['id'] = menu.number_of_courses
results.append(menu_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)

Display contents in text file using ajax

I am new to using ajax (I am retaking my web engineering class this semester) and I am able to pull a text file from the server and am able to get it to display. It is displaying on my HTML page like this:
New York 8,143,197 Los Angeles 3,844,829 Chicago 2,842,518 ...
but i want it do display the cities in one column, and the population in another.
What can I do? I have also not learned about jquery yet.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
// Get which country the user selected
var radioArray = document.myForm.countries;
var i;
var value;
for (i = 0; i < radioArray.length; i++) {
if (radioArray[i].checked) {
value = radioArray[i].value;
}
}
if (value == "usa") {
xmlhttp.open("GET","http://localhost/~ercanbracks/usa.txt",true);
}
if (value == "canada") {
xmlhttp.open("GET","http://localhost/~ercanbracks/canada.txt",true);
}
if (value == "mexico") {
xmlhttp.open("GET","http://localhost/~ercanbracks/mexico.txt",true);
}
if (value == "russia") {
xmlhttp.open("GET","http://localhost/~ercanbracks/russia.txt",true);
}
xmlhttp.send();
}
</script>
</head>
<body onload="loadXMLDoc()">
<h1>Most populated cities in the world!</h1>
<form name="myForm" action="">
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="usa" checked>USA
<br/>
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="canada">Canada
<br/>
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="mexico">Mexico
<br/>
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="russia">Russia
</form>
<div id="myDiv"></div>
</body>
</html>
You are assigning the whole response text to your element "myDiv" no matter what the response is. You need to first process the data from the response (xmlhttp.responseText) - in such way that you can separate city - population pairs, and based on how many rows of the pairs you get, you can for example create a new table element, and specify the rows and cells of the table.
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var dataToProcess = xmlhttp.responseText;
// process the data to get city-population pairs - assign them to an array for example
//...
// Create a new table element
var Table = document.createElement("Table");
// Foreach city-population pair, create one row and specify it's cells
for (var i = 0; i < YourArray.length; i++)
{
row = Table.insertRow(i);
cell1 = row.insertCell(0);
cell1.innerHTML = 'Your city value'; // YourArray[i]['City'];
cell2 = row.insertCell(1);
cell2.innerHTML = 'Your population value'; // YourArray[i]['Population'];
}
// Assign the table to a parent element
document.getElementById("your parent element").appendChild(Table);
// Be careful to which element you assign the new table element as a child, so that the page content don't need to be redrawn to make it visible
}
}
}

How to integrate svg-edit to ASP.NET MVC application

I am about to integrate svg-edit to an ASP.NET MVC project.
Is there anyone who has a recommendation or tutorial on how to begin with?
Thank you.
I am answering my own question.
After a research, I recommend deploying the whole SVG-EDIT lib into mvc architecture, then modify the embed api as following:
This is my Partial View and JS file that call the embed api and put it into the iframe within the partial view:
document.write("<script type='text/javascript' src='~/Scripts/svg-edit/embedapi.js'></script>");
// Make sure to add the embedapi into the html file, becuase the intialization function runs actually in that file, all this call does is basically to take the iframe from html and inialize the api within that tag.
$(document).ready(function () {
// jquery selectro
$("#LoadSVG").click(function () {
$("#svg").append($('<iframe src="/Scripts/svg-edit/svg-editor.html" width="900px" height="600px" id="svgedit"></iframe>'));
});
});
#Scripts.Render("~/bundles/KSage")
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<header>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</header>
<input id="LoadSVG" type="button" value="LoadSVG" />
<input id="CloseSVG" type="button" value="CloseSVG" />
<input id="save" type="button" value="save" onclick="save()">
<input id="Add" type="button" value="AddNewTag!" onclick="AddNewElemnt()" />
<input id="LoadExample" type="button" value ="LoadExample" onclick="LoadExample()"/>
<body id ="mainBody">
<p id="svg"></p>
<p id="DivData"></p>
<p id="TestId"></p>
<p id="SavedData"></p>
</body>
</html>
Here I have a save and load functions ready for the module: There is so much work to do in order to perfect the algorithm, but since this was just a test project to figure out the possibility of integrating the module into the environment I put enough effort to understand that share the knowledge with the community:
Here is my cshtml file:
#Scripts.Render("~/bundles/KSage")
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<header>
</header>
<input id="LoadSVG" type="button" value="LoadSVG" />
<input id="CloseSVG" type="button" value="CloseSVG" />
<input id="save" type="button" value="save" onclick="save()">
<input id="Add" type="button" value="AddNewTag!" onclick="AddNewElemnt()" />
<input id="LoadExample" type="button" value ="LoadExample" onclick="LoadExample()"/>
<body id ="mainBody">
<p id="svg"></p>
<p id="DivData"></p>
<p id="TestId"></p>
<p id="SavedData"></p>
</body>
</html>
Here is the js file:
document.write("<script type='text/javascript' src='~/Scripts/svg-edit/embedapi.js'></script>");
document.write("<script src='~/Scripts/jquery-1.10.2.js'></script>");
$(document).ready(function () {
// jquery selectro
$("#LoadSVG").click(function () {
$("#svg").append($('<iframe src="/Scripts/svg-edit/svg-editor.html" width="900px" height="600px" id="svgedit"></iframe>'));
});
});
$(document).ready(function () {
// jquery selectro
$("#save1").click(function () {
$("#DivData").append("<b>Appended text</b>");
});
});
$(document).ready(function(){
$("#CloseSVG").click(function () {
$("#svg").hide();
});
});
function HandleSvgData(data,error) {
if (error) {
alert('Error:' + error);
} else {
$('#DivData').append(data);
alert(data);
}
}
function handleSvgData(data, error) {
alert("handling Data");
if (error) {
alert('error ' + error);
} else {
alert('Congratulations. Your SVG string is back in the host page, do with it what you will\n\n' + data);
}
}
function save1() {
alert("saving");
// svgCanvas.getSvgString()(handleSvgData);
$("#svgedit").append($('This is the test classed appended after DivDat'));
}
function AddNewElemnt()
{
var newElement = document.createElement("Test");
var newNode = document.createTextNode("This is my new node!");
newElement.appendChild(newNode);
var referenceElement = document.getElementById("mainBody");
var tagInsert = document.getElementById("TestId");
referenceElement.insertBefore(newElement, tagInsert);
// alert("added");
}
function Postt(data) {
}
function Post(data) {
var mainBody = document.getElementById("mainBody");
var SvgDataId = prompt("give me primary id");
var SvgUser = prompt("give me UserName");
var form = document.createElement("form");
form.setAttribute("id", "PostData");
form.setAttribute("action", "/SvgDatas/Create");
form.setAttribute("method", "post");
mainBody.appendChild(form);
var PostData = document.getElementById("PostData");
var InputSvgDataId = document.createElement("input");
InputSvgDataId.setAttribute("name", "SvgDataId");
InputSvgDataId.setAttribute("value", SvgDataId);
PostData.appendChild(InputSvgDataId);
var InputSvgUser = document.createElement("input");
InputSvgUser.setAttribute("name", "SvgUser");
InputSvgUser.setAttribute("value", SvgUser);
PostData.appendChild(InputSvgUser);
var InputData = document.createElement("input");
InputData.setAttribute("name", "Data");
InputData.setAttribute("value", data);
PostData.appendChild(InputData);
form.submit();
}
function save() {
var doc, mainButton,
frame = document.getElementById('svgedit');
svgCanvas = new EmbeddedSVGEdit(frame);
// Hide main button, as we will be controlling new, load, save, etc. from the host document
doc = frame.contentDocument || frame.contentWindow.document;
mainButton = doc.getElementById('main_button');
mainButton.style.display = 'none';
// get data
svgCanvas.getSvgString()(function handleSvgData(data, error) {
if (error) {
alert('error ' + error);
} else {
alert('Congratulations. Your SVG string is back in the host page, do with it what you will\n\n' + data);
Post(data);
}
});
}
/*
function BuidUrl(SVGUser) {
var uri = prompt("Give me url where the serach function lives, if empty then I will use Razor syntax to call within MVC architescture");
if (uri)
return uri;
else {
var urlHelper = ('http://localhost:53546/SvgDatas/Search?id='+SVGUser);
return urlHelper;
}
}
*/
function returnedData_IntializeEditor(data, status) {
if ((data != null) && (status == "success")) {
var frame = document.getElementById('svgedit');
svgCanvas = new EmbeddedSVGEdit(frame);
doc = frame.contentDocument || frame.contentWindow.document;
mainButton = doc.getElementById('main_button');
tool_Bottum = doc.getElementById("#tool_button");
mainButton.style.display = 'none';
// Open Data into the frame
// var svgexample = '<svg width="640" height="480" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><g><title>Layer 1<\/title><rect stroke-width="5" stroke="#000000" fill="#FF0000" id="svg_1" height="35" width="51" y="35" x="32"/><ellipse ry="15" rx="24" stroke-width="5" stroke="#000000" fill="#0000ff" id="svg_2" cy="60" cx="66"/><\/g><\/svg>';
svgCanvas.setSvgString(data.Data);
} else {
$("#svg").append("<li>There is not such a data available in the database!</li>");
}
}
function LoadExample() {
var SVGUser = prompt("Enter the SVG ID");
$.getJSON("http://localhost:53546/SvgDatas/Search?id=" + SVGUser, returnedData_IntializeEditor );
}
This is the model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace IntegrationOfSVG.Models
{
public class SvgData
{
public string SvgDataId { get; set; }
public string SvgUser { get; set; }
public string Data { get; set; }
}
}
Thank you SVG-EDIT community for the great tool.
Next I am planning to add a view mode to this module that opens the data from a sequal server and if the mode is admin, lets the user to edit the existing data. I will keep this posted updated.
1- One way is to remove the tools from the client side, but it has a certain limitation that is the fact that css does not adjust a
function RemoveTools() {
var frame = document.getElementsByClassName("iFrameHtmlTag")[0];
doc = frame.contentWindow.document;
if (doc != null) {
var Tools = [
'tools_top', 'tools_left', 'tools_bottom', 'sidepanels', 'main_icon', 'rulers', 'sidepanels', 'canvashadow'];
for (i=0; i<Tools.length;i++)
{
doc.getElementById(Tools[i]).style.display = "none";
}
} else
alert("Doc was null");
};
$(document).ready(function () {
$("#hide").click(function () {
RemoveTools();
});
});
It is an effective way, but there should be a better method to view the object with few parameters also to readjust the size of the window. I will continue with that topic too.

How to Upload image and text to remote server using cordova/phonegap on android

Please I am working on a project that needs to get photo from phone camera and fill two text boxes and upload them to remote server using cordova/phonegap. I have tried this for weeks now without luck. I'm building on android platform. thanks in advance.
Create two functions you can call separately. One function for just getting the image, and another function to upload the image.
You can do something like below.
<!DOCTYPE html>
<html>
<head>
<title>Submit form</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
//
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
//
function onDeviceReady() {
pictureSource = navigator.camera.PictureSourceType;
destinationType = navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Show the selected image
var smallImage = document.getElementById('smallImage');
smallImage.style.display = 'block';
smallImage.src = imageURI;
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
function uploadPhoto() {
//selected photo URI is in the src attribute (we set this on getPhoto)
var imageURI = document.getElementById('smallImage').getAttribute("src");
if (!imageURI) {
alert('Please select an image first.');
return;
}
//set upload options
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType = "image/jpeg";
// this will get value of text field
options.params = {
firstname: document.getElementById("firstname").value,
lastname: document.getElementById("lastname").value,
workplace: document.getElementById("workplace").value
}
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI("http://some.server.com/upload.php"), win, fail, options);
}
// Called if something bad happens.
//
function onFail(message) {
console.log('Failed because: ' + message);
}
function win(r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
//alert("Response =" + r.response);
console.log("Sent = " + r.bytesSent);
}
function fail(error) {
alert("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}
</script>
</head>
<body>
<form id="regform">
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">Select Photo:</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
First Name: <input type="text" id="firstname" name="firstname"><br>
Last Name: <input type="text" id="lastname" name="lastname"><br>
Work Place: <input type="text" id="workplace" name="workPlace"><br>
<input type="button" id="btnSubmit" value="Submit" onclick="uploadPhoto();">
</form>
</body>
</html>
This code is working for me. Hope this helps.!
There is a file transfer plugin (which you may or may not be trying to use; you gave NO details) for such things. Or you can use straight javascript, ignoring cordova/phonegap completely. The details will depend a fair bit on how the service expects to be interacted with.

Permission Denied When using XMLHttpRequest.Open cross browser access

I am trying to access XMLHTTPRequest.open Method I have even included netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
but still its not working.
I am using javascript and HTML to access the WebService.
Any Help would be really great
Code
<html>
<Head>
<Title>Calling A WebService from HTML </Title>
</Head>
<Body onload='GetDataFrmWS()'>
<form name="Form1" id="Form1" runat="server" method="post">
<div id="DisplayData" > </div>
<div id="Menu2"></div>
</form>
<script language='javascript'>
var objHttp;
var objXmlDoc;
function GetDataFrmWS()
{
alert('I M Here');
var func = getDataFromWS();
}
function getDataFromWS()
{
if(window.ActiveXObject)
{
try
{
objHttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (ex)
{
objHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
}
else if (window.XMLHttpRequest)
{
objHttp = new window.XMLHttpRequest();
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
}
strEnvelope = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body>' +
' <HelloWorld xmlns="http://tempuri.org/">' +
' <Dummy xsi:type="xsd:string">Hello</Dummy>'+
' </HelloWorld>'+
'</soap:Body>' +
'</soap:Envelope>' ;
var szUrl;
szUrl = 'http://kamadhenu/Quoteme/GetCategories.asmx?op=HelloWorld';
objHttp.onreadystatechange = HandleResponse;
objHttp.open('POST', szUrl, true);
objHttp.setRequestHeader('Content-Type', 'text/xml');
objHttp.setRequestHeader('SOAPAction','http://tempuri.org/HelloWorld');
objHttp.send(strEnvelope);
}
function HandleResponse()
{
if (objHttp.readyState == 4)
{
if (window.ActiveXObject)
{
objXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
objXmlDoc.async="false";
objXmlDoc.loadXML(objHttp.responseText);
var nodeSelect = objXmlDoc.getElementsByTagName("Menu1").item(0);
var Menu2=objXmlDoc.getElementsByTagName("Menu2").item(0);
document.getElementById('DisplayData').innerHTML=nodeSelect.text;
document.getElementById('Menu2').innerHTML=Menu2.text;
}
else
{
var Text=objHttp.responseText;
var parser=new DOMParser();
objXmlDoc = parser.parseFromString(Text,'text/xml');
var Value=objXmlDoc.documentElement.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].nodeValue;
var Menu2=objXmlDoc.documentElement.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[1].childNodes[0].nodeValue;
var Menu3=objXmlDoc.documentElement.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[1].childNodes[1].nodeValue;
document.getElementById('DisplayData').innerHTML=Value;
document.getElementById('Menu2').innerHTML=Menu2;
document.getElementById('Menu2').innerHTML+=Menu3;
}
}
}
</script>
<input type='Button' Text='Click Me' onclick='GetDataFrmWS()' value="Click Me!"/>
°
</Body>
</HTML>
Browser Independent code for XML HTTPRequest
I use the following code to create an XML object. It has been designed to handle all browsers (esp. IE and non IE)
/* Function to create an XMLHTTP object for all browsers */
function getXMLHTTPObject(){
var xmlHttp;
try{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e){
// Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
/* End Function */
P.S. You code in the question is not readable. Pls format it
There is a pretty concise example here
Try making your URL http://recpushdata.cyndigo.com/Jobs.asmx/InsertXML
PS. Your code is unreadable in StackOverflow.
As far as I know, the XMLHTTP request must point to a page on the same subdomain of the html page for the various browsers permissions.
One trick is to make another page on the same server in your preferred language and make it handle the request with the server's network.
Example:
from your HTML page you make a ajax request to mydomain.com/externalrequest.php?url=www.google.com
and that page will connect (fsock/cURL etc) to "url" and return it
If you are TRYING to go cross-domain with XHR, you can look into the JSONP method. Check JQuery docs for that.
Would require you to accept JSON response but it does work across domains.

Resources