loading xml from a database to be used in multiple functions - php

I have a database where i'm using php to randomize the information by ID and send it out via xml. My issue is that I only want to grab the xml once and store it for use in at least 2 functions... one function that runs onload to grab the first line of xml, another that will run every time a button is pressed to access the next line of xml until the end. My 2 functions are loadfirst() and loadnext(). loadfirst() works perfectly, but I'm not sure how to pass the xml data to loadnext(). Right now I'm just using loadfirst() on pageload and loadfirst() on button press, but i end up creating new xml from the database each time which causes randomization issues and is incredibly inefficient. Any help would be appreciated.
var places;
var i = 0;
function loadXML(){
downloadUrl("places.php", function(data){
places = data.responseXML;
getFeatured(i);
});
}
function getFeatured(index){
var id = places[index].getAttribute("id");
var name = places[index].getAttribute("name");
var location = places[index].getAttribute("location");
var imgpath = places[index].getAttribute("imgpath");
var tags = places[index].getAttribute("tags");
}
function getPrev() {
i--;
getFeatured(i);
}
function getNext() {
i++;
getFeatured(i);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
loadnext() will be very similar to loadfirst(), I'm just running into issues with passing the xml data so that i can use it without having to access the database again. Thanks.

Set your xml and i in public scope. Then all you have to do is increment/decrement i and re-read data from XML. Something like this:
var xml;
var xml_idx = 0; // replaces your i counter
function loadXML() {
downloadUrl ("places.php", function(data) {
xml = data.responseXML;
)};
}
function loadItem(index) {
var id = xml[index].getAttribute("id");
var name = xml[index].getAttribute("name");
var location = xml[index].getAttribute("location");
var imgpath = xml[index].getAttribute("imgpath");
var tags = xml[index].getAttribute("tags");
// do something with this data
}
function loadCurrentItem() {
loadItem(xml_idx);
}
function loadNextItem() {
xml_idx++;
loadItem(xml_idx);
}
function loadPreviousItem() {
xml_idx--;
loadItem(xml_idx);
}
// usage
loadXML(); // do this first to populate xml variable
loadItem(xml_idx); // loads first item (i=0)
loadCurrentItem(); // loads i=0
loadNextItem(); // loads i=1
loadNextItem(); // loads i=2
loadPreviousItem(); // loads i=1
If you really want to get fancy (and keep the global namespace cleaner), you could easily make this into a class.

Use global variables (items - items array, iterator - counter) to store data available for all functions.
Try something like this:
items = false;
iterator = 0;
function loadfirst(){
downloadUrl ("places.php", function(data) {
var i = 0;
var xml = data.responseXML;
var places = xml.documentElement.getElementsByTagName("place");
var id = places[i].getAttribute("id");
var name = places[i].getAttribute("name");
var location = places[i].getAttribute("location");
var imgpath = places[i].getAttribute("imgpath");
var tags = places[i].getAttribute("tags");
items = places;
iterator++;
)};
}
function loadnext(){
var i = iterator;
var id = items[i].getAttribute("id");
var name = items[i].getAttribute("name");
var location = items[i].getAttribute("location");
var imgpath = items[i].getAttribute("imgpath");
var tags = items[i].getAttribute("tags");
iterator++;
}

You should wrap all this into a single object to control scope and data state. (Untested code below, which should just illustrate a possible pattern and interface to use.)
function PlacesScroller(url, callback) {
this.url = url;
this.data = null;
this._index = null;
this.length = 0;
var self = this;
downloadURL(this.url, function(result, status) {
if (Math.floor(status/100)===2) {
self.setData(result);
}
if (callback) {
callback(self, result);
}
});
}
PlacesScroller.prototype.setData(xmldom) {
this._index = 0;
// this may require changing; it depends on your xml structure
this.data = [];
var places = xmldom.getElementsByTagName('place');
for (var i=0; i<places.length; i++) {
this.data.push({
id : places[i].getAttribute('id'),
name : places[i].getAttribute('name')
// etc
});
}
}
PlacesScroller.prototype.getPlaceByIndex = function(index) {
if (this.data) {
return this.data[index];
} else {
return null;
}
}
PlacesScroller.prototype.getCurrentFeature = function() {
return this.getPlaceByIndex(this._index);
}
PlacesScroller.prototype.addToIndex(i) {
// This sets the index forward or back
// being careful not to fall off the end of the data
// You can change this to (e.g.) cycle instead
if (this.data===null) {
return null;
}
var newi = i+this._index;
newi = Math.min(newi, this.data.length);
newi = Math.max(0, newi);
this._index = newi;
return this._index;
}
PlacesScroller.prototype.getNextFeature = function() {
this.addToIndex(1);
return this.getCurrentFeature();
}
PlacesScroller.prototype.getPreviousFeature = function() {
this.addToIndex(-1);
return this.getCurrentFeature();
}
Then initialize it and use it like so:
var scroller = new PlacesScroller('places.php', function(scrollerobject, xmlresult){
// put any initialization code for your HTML here, so it can build after
// the scrollerobject gets its data.
// You can also register event handlers here
myNextButton.onclick = function(e){
var placedata = scrollerobject.getNextFeature();
myPictureDisplayingThing.update(placedata);
}
// etc
});

Related

how to get id from current url and make new url in ajax [duplicate]

I have seen lots of jQuery examples where parameter size and name are unknown.
My URL is only going to ever have 1 string:
http://example.com?sent=yes
I just want to detect:
Does sent exist?
Is it equal to "yes"?
Best solution here.
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
return false;
};
And this is how you can use this function assuming the URL is,
http://dummy.com/?technology=jquery&blog=jquerybyexample.
var tech = getUrlParameter('technology');
var blog = getUrlParameter('blog');
Solution from 2023
We have: http://example.com?sent=yes
let searchParams = new URLSearchParams(window.location.search)
Does sent exist?
searchParams.has('sent') // true
Is it equal to "yes"?
let param = searchParams.get('sent')
and then just compare it.
jQuery code snippet to get the dynamic variables stored in the url as parameters and store them as JavaScript variables ready for use with your scripts:
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results==null) {
return null;
}
return decodeURI(results[1]) || 0;
}
example.com?param1=name&param2=&id=6
$.urlParam('param1'); // name
$.urlParam('id'); // 6
$.urlParam('param2'); // null
example params with spaces
http://www.jquery4u.com?city=Gold Coast
console.log($.urlParam('city'));
//output: Gold%20Coast
console.log(decodeURIComponent($.urlParam('city')));
//output: Gold Coast
I always stick this as one line. Now params has the vars:
params={};location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){params[k]=v})
multi-lined:
var params={};
window.location.search
.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str,key,value) {
params[key] = value;
}
);
as a function
function getSearchParams(k){
var p={};
location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(s,k,v){p[k]=v})
return k?p[k]:p;
}
which you could use as:
getSearchParams() //returns {key1:val1, key2:val2}
or
getSearchParams("key1") //returns val1
Yet another alternative function...
function param(name) {
return (location.search.split(name + '=')[1] || '').split('&')[0];
}
Using URLSearchParams:
var params = new window.URLSearchParams(window.location.search);
console.log(params.get('name'));
Be careful about the compatibility (Mostly it's fine, but IE and Edge, may be different story, check this for compatible reference: https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
May be its too late. But this method is very easy and simple
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.url.js"></script>
<!-- URL: www.example.com/correct/?message=done&year=1990 -->
<script type="text/javascript">
$(function(){
$.url.attr('protocol') // --> Protocol: "http"
$.url.attr('path') // --> host: "www.example.com"
$.url.attr('query') // --> path: "/correct/"
$.url.attr('message') // --> query: "done"
$.url.attr('year') // --> query: "1990"
});
UPDATE
Requires the url plugin : plugins.jquery.com/url
Thanks -Ripounet
Or you can use this neat little function, because why overcomplicated solutions?
function getQueryParam(param, defaultValue = undefined) {
location.search.substr(1)
.split("&")
.some(function(item) { // returns first occurence and stops
return item.split("=")[0] == param && (defaultValue = item.split("=")[1], true)
})
return defaultValue
}
which looks even better when simplified and onelined:
tl;dr one-line solution
var queryDict = {};
location.search.substr(1).split("&").forEach(function(item) {queryDict[item.split("=")[0]] = item.split("=")[1]})
result:
queryDict['sent'] // undefined or 'value'
But what if you have got encoded characters or multivalued keys?
You better see this answer: How can I get query string values in JavaScript?
Sneak peak
"?a=1&b=2&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dståle%26car%3Dsaab"
> queryDict
a: ["1", "5", "t e x t"]
b: ["2"]
c: ["3"]
d: [undefined]
e: [undefined, "http://w3schools.com/my test.asp?name=ståle&car=saab"]
> queryDict["a"][1] // "5"
> queryDict.a[1] // "5"
This one is simple and worked for me
$.urlParam = function(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
so if your url is http://www.yoursite.com?city=4
try this
console.log($.urlParam('city'));
Perhaps you might want to give Dentist JS a look? (disclaimer: I wrote the code)
code:
document.URL == "http://helloworld.com/quotes?id=1337&author=kelvin&message=hello"
var currentURL = document.URL;
var params = currentURL.extract();
console.log(params.id); // 1337
console.log(params.author) // "kelvin"
console.log(params.message) // "hello"
with Dentist JS, you can basically call the extract() function on all strings (e.g., document.URL.extract() ) and you get back a HashMap of all parameters found. It's also customizable to deal with delimiters and all.
Minified version < 1kb
I hope this will help.
<script type="text/javascript">
function getParameters() {
var searchString = window.location.search.substring(1),
params = searchString.split("&"),
hash = {};
if (searchString == "") return {};
for (var i = 0; i < params.length; i++) {
var val = params[i].split("=");
hash[unescape(val[0])] = unescape(val[1]);
}
return hash;
}
$(window).load(function() {
var param = getParameters();
if (typeof param.sent !== "undefined") {
// Do something.
}
});
</script>
Try this working demo http://jsfiddle.net/xy7cX/
API:
inArray : http://api.jquery.com/jQuery.inArray/
This should help :)
code
var url = "http://myurl.com?sent=yes"
var pieces = url.split("?");
alert(pieces[1] + " ===== " + $.inArray("sent=yes", pieces));
This will give you a nice object to work with
function queryParameters () {
var result = {};
var params = window.location.search.split(/\?|\&/);
params.forEach( function(it) {
if (it) {
var param = it.split("=");
result[param[0]] = param[1];
}
});
return result;
}
And then;
if (queryParameters().sent === 'yes') { .....
This might be overkill, but there is a pretty popular library now available for parsing URIs, called URI.js.
Example
var uri = "http://example.org/foo.html?technology=jquery&technology=css&blog=stackoverflow";
var components = URI.parse(uri);
var query = URI.parseQuery(components['query']);
document.getElementById("result").innerHTML = "URI = " + uri;
document.getElementById("result").innerHTML += "<br>technology = " + query['technology'];
// If you look in your console, you will see that this library generates a JS array for multi-valued queries!
console.log(query['technology']);
console.log(query['blog']);
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.17.0/URI.min.js"></script>
<span id="result"></span>
function GetRequestParam(param)
{
var res = null;
try{
var qs = decodeURIComponent(window.location.search.substring(1));//get everything after then '?' in URI
var ar = qs.split('&');
$.each(ar, function(a, b){
var kv = b.split('=');
if(param === kv[0]){
res = kv[1];
return false;//break loop
}
});
}catch(e){}
return res;
}
So simple you can use any url and get value
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
Usage Example
// query string: ?first=value1&second=&value2
var foo = getParameterByName('first'); // "value1"
var bar = getParameterByName('second'); // "value2"
Note: If a parameter is present several times (?first=value1&second=value2), you will get the first value (value1) and second value as (value2).
There's this great library:
https://github.com/allmarkedup/purl
which allows you to do simply
url = 'http://example.com?sent=yes';
sent = $.url(url).param('sent');
if (typeof sent != 'undefined') { // sent exists
if (sent == 'yes') { // sent is equal to yes
// ...
}
}
The example is assuming you're using jQuery. You could also use it just as plain javascript, the syntax would then be a little different.
http://example.com?sent=yes
Best solution here.
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
With the function above, you can get individual parameter values:
getUrlParameter('sent');
This is based on Gazoris's answer, but URL decodes the parameters so they can be used when they contain data other than numbers and letters:
function urlParam(name){
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
// Need to decode the URL parameters, including putting in a fix for the plus sign
// https://stackoverflow.com/a/24417399
return results ? decodeURIComponent(results[1].replace(/\+/g, '%20')) : null;
}
There is another example with using URI.js library.
Example answers the questions exactly as asked.
var url = 'http://example.com?sent=yes';
var urlParams = new URI(url).search(true);
// 1. Does sent exist?
var sendExists = urlParams.sent !== undefined;
// 2. Is it equal to "yes"?
var sendIsEqualtToYes = urlParams.sent == 'yes';
// output results in readable form
// not required for production
if (sendExists) {
console.log('Url has "sent" param, its value is "' + urlParams.sent + '"');
if (urlParams.sent == 'yes') {
console.log('"Sent" param is equal to "yes"');
} else {
console.log('"Sent" param is not equal to "yes"');
}
} else {
console.log('Url hasn\'t "sent" param');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/URI.js/1.18.2/URI.min.js"></script>
Coffeescript version of Sameer's answer
getUrlParameter = (sParam) ->
sPageURL = window.location.search.substring(1)
sURLVariables = sPageURL.split('&')
i = 0
while i < sURLVariables.length
sParameterName = sURLVariables[i].split('=')
if sParameterName[0] == sParam
return sParameterName[1]
i++
A slight improvement to Sameer's answer, cache params into closure to avoid parsing and looping through all parameters each time calling
var getURLParam = (function() {
var paramStr = decodeURIComponent(window.location.search).substring(1);
var paramSegs = paramStr.split('&');
var params = [];
for(var i = 0; i < paramSegs.length; i++) {
var paramSeg = paramSegs[i].split('=');
params[paramSeg[0]] = paramSeg[1];
}
console.log(params);
return function(key) {
return params[key];
}
})();
I use this and it works.
http://codesheet.org/codesheet/NF246Tzs
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var first = getUrlVars()["id"];
With vanilla JavaScript, you could easily take the params (location.search), get the substring (without the ?) and turn it into an array, by splitting it by '&'.
As you iterate through urlParams, you could then split the string again with '=' and add it to the 'params' object as object[elmement[0]] = element[1]. Super simple and easy to access.
http://www.website.com/?error=userError&type=handwritten
var urlParams = location.search.substring(1).split('&'),
params = {};
urlParams.forEach(function(el){
var tmpArr = el.split('=');
params[tmpArr[0]] = tmpArr[1];
});
var error = params['error'];
var type = params['type'];
What if there is & in URL parameter like filename="p&g.html"&uid=66
In this case the 1st function will not work properly. So I modified the code
function getUrlParameter(sParam) {
var sURLVariables = window.location.search.substring(1).split('&'), sParameterName, i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
}
Admittedly I'm adding my answer to an over-answered question, but this has the advantages of:
-- Not depending on any outside libraries, including jQuery
-- Not polluting global function namespace, by extending 'String'
-- Not creating any global data and doing unnecessary processing after match found
-- Handling encoding issues, and accepting (assuming) non-encoded parameter name
-- Avoiding explicit for loops
String.prototype.urlParamValue = function() {
var desiredVal = null;
var paramName = this.valueOf();
window.location.search.substring(1).split('&').some(function(currentValue, _, _) {
var nameVal = currentValue.split('=');
if ( decodeURIComponent(nameVal[0]) === paramName ) {
desiredVal = decodeURIComponent(nameVal[1]);
return true;
}
return false;
});
return desiredVal;
};
Then you'd use it as:
var paramVal = "paramName".urlParamValue() // null if no match
If you want to find a specific parameter from a specific url:
function findParam(url, param){
var check = "" + param;
if(url.search(check )>=0){
return url.substring(url.search(check )).split('&')[0].split('=')[1];
}
}
var url = "http://www.yourdomain.com/example?id=1&order_no=114&invoice_no=254";
alert(findParam(url,"order_no"));
Another solution that uses jQuery and JSON, so you can access the parameter values through an object.
var loc = window.location.href;
var param = {};
if(loc.indexOf('?') > -1)
{
var params = loc.substr(loc.indexOf('?')+1, loc.length).split("&");
var stringJson = "{";
for(var i=0;i<params.length;i++)
{
var propVal = params[i].split("=");
var paramName = propVal[0];
var value = propVal[1];
stringJson += "\""+paramName+"\": \""+value+"\"";
if(i != params.length-1) stringJson += ",";
}
stringJson += "}";
// parse string with jQuery parseJSON
param = $.parseJSON(stringJson);
}
Assuming your URL is http://example.com/?search=hello+world&language=en&page=3
After that it's only a matter of using the parameters like this:
param.language
to return
en
The most useful usage of this is to run it at page load and make use of a global variable to use the parameters anywhere you might need them.
If your parameter contains numeric values then just parse the value.
parseInt(param.page)
If there are no parameters param will just be an empty object.
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}
use this
$.urlParam = function(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
return results[1] || 0;
}

WooCommerce webhook parsing

Trying to parse the input JSON from the Woocommerce Webhook to Google Spreadsheet via Google App Script.
Used this one :
function doPost(request) {
var json = request.postData.getDataAsString();
var obj = JSON.parse(json);
// getting some of the Woocommerce data just as an example
// Hook was fired after order.created
var id = obj.order.id;
var orderNumber = obj.order.order_number;
var payMethod = obj.order.payment_details.method_title;
// write data in a document, not useful, but straightforward for testing
var doc = DocumentApp.openById('myDocumentId');
doc.appendParagraph("Id: " + id);
doc.appendParagraph("orderNumber: " + orderNumber);
doc.appendParagraph("payMethod: " + payMethod);
}
But receive nothing into the Google Sheets.
And with this one:
function doPost(request) {
var content = JSON.parse(request.postData.contents);
var row = [];
for (var elem in content) {
row.push(content[elem]);
}
var ss = SpreadsheetApp.openById("SHEET ID")
var sheet = ss.getSheetByName("Sheet1");
sheet.appendRow(row);
var result = {"result":"ok"};
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON);
}
It's receiving data, but it's not parsed:
Is there anyway to fix this and make the data in sheet viewable?
Thanks in advance.
I have found the answer on my question at https://ru.stackoverflow.com/
thanks to Alexander Ivanov
The main thing why the woocommerce webhook not parsed is that the JSON is not valid when WC send it to the spreadsheet macros.
And sheet posting it as one element {order:{}}
so we need to edit the code like this :
var content = JSON.parse(request.postData.contents)[0];
or like this (in my case):
var content = JSON.parse(request.postData.contents)['order'];
in case we have no idea what data will be received, we may try to determine the value:
function doPost(request) {
var result = {
result: undefined
};
try {
var content = JSON.parse(request.postData.contents);
var row = [];
if (content.hasOwnProperty('order')) {
for (var elem in content['order']) {
row.push(content['order'][elem]);
}
} else {
row.push(request.postData.contents);
}
var ss = SpreadsheetApp.openById('SHEET ID')
var sheet = ss.getSheets()[0];
sheet.appendRow(row);
result.result = 'ok';
} catch (err) {
result.result = 'err';
}
return ContentService.createTextOutput(JSON.stringify(result))
.setMimeType(ContentService.MimeType.JSON);
}

How to Scroll to position of page using get method?

How to Scroll to position of page using get method ?
EG: mysite.com/index.php?positon=1
after load page it's will be Scroll to position id=1 of page
how can i do that ?
You could use this javascript function :
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value) {
vars[key] = value;
});
return vars;
}
For example when your url is : mysite.com/index.php?positon=1
You can get the value by doing : var position = getUrlVars()["position"];
Then to scroll you do :
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
window.scroll(0,findPos(document.getElementById(position)));
You have to use that after the DOM has loaded so write that just after </body> like this :
<script type="text/javascript">
(function() {
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,function(m,key,value) {
vars[key] = value;
});
return vars;
}
var position = getUrlVars()["position"];
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop;
} while (obj = obj.offsetParent);
return [curtop];
}
}
window.scroll(0,findPos(document.getElementById(position)));
})();
</script>
You can then reuse these functions for any variables you want
I can't show you on JSFiddle because the ?position=1 won't work on it
However here is a paste of a fully working html page which I used for testing : http://pastebin.com/tjj4fDK9
Paste it in a html file on your computer, open it with Chrome and add ?position=1 in the URL

How to add a PHP template to a dynamically generated Javascript code

I'm using Code Igniter and the Googlemaps library. This library generates a lot of Javascript code dynamically, including the contents of the InfoWindows for each new marker, but I'd like to keep that in a separate template file, like a regular View.
I have this Javascript code (from Googlemaps' library):
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var windowContent = "";
if( _new ) {
var newIW = new google.maps.InfoWindow( { content: windowContent } );
What I want to do is to load windowContent from a template file. I have already succeeded in dynamically generating a form for this variable and using lat and long variables defined just above, but how can I achieve this in Code Igniter? I can't use load->view because I'm not in a Controller's context. And I cannot use include() or readfile() either because of CI's security constraints.
Any hints?
Using pure javascript, get the lat and long, make a url with the lat and long in the query string, and use xhr to do the ajax call.
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var xhr;
var url = "http://myurl.to/script.php?lat="+lat+"&lng="+long;
if(typeof XMLHttpRequest !== 'undefined')
xhr = new XMLHttpRequest();
else {
//Get IE XHR object
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"];
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
}
}
xhr.onreadystatechange = function(){
//This function is called every so often with status updates
//It is complete when status is 200 and readystate is 4
if(xhr.status == 200 && xhr.readyState === 4) {
//Returned data from the script is in xhr.responseText
var windowContent = xhr.responseText;
//Create the info window
var newIW = new google.maps.InfoWindow( { content: windowContent } );
//Pass newIW to whatever other function to use it somewhere
}
};
xhr.open('GET', url, true);
xhr.send();
if using a library like jQuery it would be like
var lat = marker.getPosition().lat();
var long = marker.getPosition().lng();
var url = "http://myurl.to/script.php";
jQuery.ajax({
"url":url,
"data":{ //Get and Post data variables get put here
"lat":lat,
"lng":long
},
"dataType":"html", //The type of document you are getting, assuming html
//Could be json xml etc
"success":function(data) { //This is the callback when ajax is done and successful
//Returned data from the script is in data
var windowContent = data;
//Create the info window
var newIW = new google.maps.InfoWindow( { content: windowContent } );
//Pass newIW to whatever other function to use it somewhere
}
});

Can't load waypoints and routes on Google Maps api v3

I want to display multiple directions with dragable waypoints and save each waypoints.
On my project I can click on the map to create the routes, generating a wayA point and a wayB point and draw a route between them. So, I can make multiple routes.
I can also save them on the database.
The problem is load this points on the map again fetching them on the database and drawing all on the map.
I have two pages, on index.htm you can draw your routes and save them, and on loady.htm you can load them on the map.
I tried somethings but without sucess, I will post my try here.
This is my resumed index.htm
var map, ren, ser;
var data = {};
var wayA = [];
var wayB = [];
var directionResult = [];
function goma() <---Initialize
{
google.maps.event.addListener(map, "click", function(event) {
if (wayA.length == wayB.length) {
wayA.push(new google.maps.Marker({
draggable: true,
position: event.latLng,
map: map
}));
} else {
wayB.push(new google.maps.Marker({
draggable: true,
position: event.latLng,
map: map
}));
ren = new google.maps.DirectionsRenderer( {'draggable':true} );
ren.setMap(map);
ren.setPanel(document.getElementById("directionsPanel"));
ser = new google.maps.DirectionsService();
ser.route({ 'origin': wayA[wayA.length-1].getPosition(), 'destination': wayB[wayB.length-1].getPosition(), 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK') {
directionResult.push(res);
ren.setDirections(res);
} else {
directionResult.push(null);
} })
} }); }
function save_waypoints()
{
var w=[],wp;
var rleg = ren.directions.routes[0].legs[0];
data.start = {'lat': rleg.start_location.lat(), 'lng':rleg.start_location.lng()}
data.end = {'lat': rleg.end_location.lat(), 'lng':rleg.end_location.lng()}
var wp = rleg.via_waypoints
for(var i=0;i<wp.length;i++)w[i] = [wp[i].lat(),wp[i].lng()]
data.waypoints = w;
var str = JSON.stringify(data)
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=save&inventoresdegara='+str)
jax.onreadystatechange = function(){ if(jax.readyState==4) {
if(jax.responseText.indexOf('bien')+1)alert('Mapa Atualizado !');
else alert(jax.responseText)
}}
}
This is the resumed loady.htm with my try
var map, ren, ser;
var data = {};
var wayA = [];
var wayB = [];
var directionResult = [];
function goma() {
ren = new google.maps.DirectionsRenderer( {'draggable':true} );
ren.setMap(map);
ren.setPanel(document.getElementById("directionsPanel"));
ser = new google.maps.DirectionsService();
fetchdata();
function setroute(os)
{
var wp = [];
for(var i=0;i<os.waypoints.length;i++)
wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][3]),'stopover':false }
ser.route({ 'origin': wayA[wayA.length-1].setPosition(), 'destination': wayB[wayB.length-1].setPosition(), 'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK') {
directionResult.push(res);
ren.setDirections(res);
} else {
directionResult.push(null);
}
});
}
function fetchdata()
{
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch')
jax.onreadystatechange = function(){ if(jax.readyState==4) {
try { setroute( eval('(' + jax.responseText + ')') ); }
catch(e){ alert(e); }
}}
}
This is my php file:
<?
if($_REQUEST['command']=='save')
{
$query = "insert into inventoresdegara set value='$data'";
if(mysql_query($query))die('bien');
die(mysql_error());
}
if($_REQUEST['command']=='fetch')
{
//$query = "select value from inventoresdegara";
$query = "SELECT value FROM inventoresdegara";
if(!($res = mysql_query($query)));
$rs = mysql_fetch_array($res,1);
die($rs['value']);
}
?>
This is a image from my database to you know how the information are saved
The only thing that I need to do is load this values to the map, please help me =).
Thanks !
After my try, the loady.htm was this on ser.routes
ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
'waypoints': wp,
'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
}
If the reason to saving waypoints is to reproduce the route they came from, you're better off saving the entire route and then showing it on the map without re-requesting the route again. See Displaying results of google direction web service without using javascript api
Otherwise, if you just want to get a fresh route from A to B through waypoints, your current approach of calling ser.route() with them is correct.

Categories