Saving array to MySQL in specific format - javascript

I have a form that submits data to a MySQL table. Specifically, it's using Gravity Forms, a plugin for WordPress, but this isn't really specifically related to either that plugin or WP. I'm just trying to figure out how to format my data so it gets stored in the right format in MySQL.
I'm using the Google Maps Javascript API to look at a specific field, perform Google Maps' auto-complete to retrieve a place, and then take the name of that place (which is what the API returns) and use the Google Maps Geocoding API to add the latitude and longitude.
I know that I need the information stored in the database like this:
a:3:{s:7:"address";s:12:"101 First St";s:3:"lat";s:10:"25.8018672";s:3:"lng";s:18:"-80.12885949999998";}
So I'm trying to create a value for the input by combining the dynamic stuff I am successfully getting, such as the actual street address, lat and longitude, in a variable like this:
place_shebang = 'a:3:{s:7:"address";s:' + place_name_length + ':"' + theplacename + '";s:3:"lat";s:' + place_lat_length + ':"' + theplacelat + '";s:3:"lng";s:' + place_lng_length + ':"' + theplacelng + '";}';
But that saves the data like so when I view it in MySQL:
s:117:"a:3:{s:7:"address";s:12:"101 First St";s:3:"lat";s:undefined:"40.528263";s:3:"lng";s:undefined:"-78.86381770000003";}";
So my question is, what should I do with place_shebang to get it to store in the proper format?

Instead of creating a serialized string, recreate the object and have that saved.
$place_shebang = [
"address" => $theplacename,
"lat" => $theplacelat,
"lng" => $theplacelng,
];

Related

How to get information on hidden rows from Google Sheet API without Google Apps Script

I am using the Google Sheets API V4 to retrieve its data in JSON like below. That includes all rows, even the ones currently not shown in the Spreadsheet UI because of a filtering in one of the columns.
Is there a way to get only the shown rows or information whether a row is hidden or not?
The Google Apps Script allows such data retrieval using i.e. the .hiddenByFilter Method (see https://cloud.google.com/blog/products/application-development/using-google-sheets-filters-in-add-ons ). However, I am not able to include that in my API Query whatsoever.
$.getJSON("https://sheets.googleapis.com/v4/spreadsheets/" + SpreadsheetID + "/values/Color1!A2:Q?key=<MY_API_KEY>", function(data) {
// data.values contains the array of rows from the spreadsheet. Each row is also an array of cell values.
$(data.values).each(function() {
var location = {};
location.title = this[2];
location.latitude = parseFloat(this[10]);
location.longitude = parseFloat(this[9]);
location.institution = this[3];
//location.hidden = <?>;
locations.push(location);
});
Is there any workaround?
You can use Spreadsheets.get endpoint. Then filter sheets/data/rowData/values using sheets/data/rowMetadata/hiddenByUser field client side.

How do I make a query to Google Places API?

I'm trying to make a client-side jquery request on an HTML page (in my Spring project) to the Google Places API so I can determine the ratings of a particular business type within a radius of x,y. At the moment I'm trying to do it like so:
function getCafe(){
$(document).ready(function(){
$('.search_latitude').val(marker.getPosition().lat());
$('.search_longitude').val(marker.getPosition().lng());
// These are lat long values calculated by the user's searched location on a google map on the client side
var Lat = marker.getPosition().lat();
console.log(Lat);
var Long = marker.getPosition().lng();
console.log(Long);
var cafeRatings = [];
// Ive disclosed my API Key
var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=" + Lat + "," + Long + "&radius=500&type=restaurant&keyword=cruise&key=MY_API_KEY";
$.ajax({
type: "GET",
dataType: "xml",
url: url,
success: function(xml) {
$(xml).find('results').each(function(){
$(this).find("rating").each(function(){
var rating = $(this).text();
cafeRatings.push(rating);
});
});
//This is a simple debug to display the contents of the rating array to ensure the parse worked correctly
alert(cafeRatings.join("\n"));
}
});
});
}
However Michael Geary's answer to this question Google's Places API and JQuery request - Origin http://localhost is not allowed by Access-Control-Allow-Origin has lead me to believe I cannot use an Ajax jquery to access the API this way and I have to "use the Places Library from the Maps API V3. (As I) can't just hit a URL directly from JavaScript or jQuery code."
With that being said I've found the documentation to do this to be quite broad and resources online seem to be quite limited. Has anyone any experience on how to simply get the rating elements from the API stored into an array in JS so I can calculate the average and display it in a text box?
In case it's needed this how the XML formatted API looks
<PlaceSearchResponse>
<status>OK</status>
<result>
<name>Sydney Showboats</name>
<vicinity>32 The Promenade, Sydney</vicinity>
<type>travel_agency</type>
<type>restaurant</type>
<type>food</type>
<type>point_of_interest</type>
<type>establishment</type>
<geometry>
<location>
<lat>-33.8675570</lat>
<lng>151.2015270</lng>
</location>
<viewport>
<southwest>
<lat>-33.8689120</lat>
<lng>151.2001126</lng>
</southwest>
<northeast>
<lat>-33.8662141</lat>
<lng>151.2028105</lng>
</northeast>
</viewport>
</geometry>
<rating>3.8</rating> <------ This is the element im trying to ad to the array
<icon>
https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png
</icon>
<reference>
CmRSAAAALItuCtuLapozzsjq3dmKqj7NDik149XsgUwHD3ob5AWfHYlZtykuJbQa0cq0GMqX8dRgucTCmitnXgV-ekE3GfV7910rzHhx3ZuadVYNuWMzLDVZDCj2G1yiBw8r_hhgEhCPDXsniaZ2ZrkvYyXFfmQrGhSzdmkAEz4stXNx2qFe-GqAlldzgw
</reference>
<id>ce4ffe228ab7ad49bb050defe68b3d28cc879c4a</id>
<opening_hours>
<open_now>false</open_now>
</opening_hours>
<photo>
<photo_reference>
CmRaAAAAh4dP9hsZ_6515QNxouVnuYFYKemmf8BE01rcaOvkFlILQiwGNe_OAX0ikmobMmWZJvyjsFEsn7j1TFhauHSrek8nY5GsW24_6nwJsqEwHTUC10SL5gQITHhkdam50G1PEhCP-C7Of2mkjqJCTYFeYGWuGhQjVoWASHiGSp3WHm26Bh2sYOglZw
</photo_reference>
<width>2048</width>
<height>1152</height>
<html_attribution>
Sydney Showboats
</html_attribution>
</photo>
<place_id>ChIJjRuIiTiuEmsRCHhYnrWiSok</place_id>
<scope>GOOGLE</scope>
</result>
........
</PlaceSearchResponse>
My previous advice remains the same: you can't use the server-oriented web service version of the Places API. You have to use the JavaScript client library. It is much easier to use than the web service API (even if you were allowed to use that), because you don't have to parse any XML, just access the object properties that the client library provides.
There are several examples in the Places Library documentation. The Place Search example is fairly close to what you are doing. It looks like you want to access the rating for a place, and that is easy with the JavaScript library; simply use the rating property of your place object (or whatever name you give that variable).
I took the Place Search example and updated the fiddle to illustrate accessing the rating property. Try it out and see if it helps answer your question.
In any case, the bottom line is unchanged: you can't use the web service API, you need to use the JavaScript client library, but that is a Good Thing, as the client library does most of the work for you.
If the question is how to compute the average rating for the places you receive back from the API, that is simple: write a loop and do the arithmetic. If you look at the fiddle you will see where it has a loop that iterates over the results variable that the API callback receives. The loop in the fiddle creates a marker for each element of results, but you can do whatever you want there. Just add up all the rating values and divide the total by results.length and you have your average. Of course check that the length is nonzero, so you don't divide by zero.
For example, if you have a results variable with the array of places results, you could do:
var totalRating = 0;
results.forEach( function( place ) {
totalRating += place.rating;
});
var averageRating = results.length == 0 ? 0 : totalRating / results.length;

Send json data as url parameters

I m trying to pass json data
var data = JSON.parse("[" + detail + "]"))
or the results of var detail = $('#grid-table').getCell(rowid, '11')
results as parameters of the url vers another jsp (a modal).
In the same page, all is good (the jqgrid table is full normally).
Now I want to fill by the same data another jqgrid but in another jsp (in my case is a bootstrap modal) but it displays anything.
var iframeSrc = '<%=request.getContextPath()%>/subgridtable_Device_Modal.html?'+ data + '&' + detail ;)
I saw the below sample of data when I receive the detail variable in the second page :
{%22A%22:%223%22,%22B%22:%222SC2I%22,%22C%22:%223%22,%22D%22:%222SC2I%22,%22E%22:%2245%22,%22F%22:%22PTS3S40510009246%22,%22G
Also I tried to parse the detail to json data in the second page but no results .
Any one have any idea please.
When you pass a variable as a part of a URL it will always be URL-encoded. When receiving such a parameter most server side programming languages will automatically decode it again for you. When that's not the case, you have to manually decode it. I don't know which server side language you're using though. Or if you use JavaScript to receive that parameter, use decodeURI().

How to pass parameters to URL and retrieve with PHP?

I noticed that there are a lot of these questions but I can't find something that relates to my particular project. I am building a Instagram and Google maps app. What I'm trying to do is I'm pulling all JSON format endpoints from Instagram with PHP. With Google maps, I'm adding the longitude and latitude coordinates that this certain API call passes through so you can see where the user has taken the photo at the time it was created. What I'm working on is using Google's event methods I am able to center longitude and latitude coordinates to the URL using the function parent.location.hash.
google.maps.event.addListener(map, 'center_changed', function(){
var control_center = map.getCenter();
var lng = control_center.lng();
var lat = control_center.lat();
parent.location.hash="&lng="+lng +"&lat="+lat;
$('.lng').append(lng);
console.log(map.getCenter());
console.log(lng +', ' +lat);
});
The issue I'm now running into is when I tried to retrieve lng and lat with PHP $_GET it was not working. I found out because it's a fragment and it never gets sent to the server. I found other tips and tricks like parse_url but that echos one string. Here is a snippet of what the current URL looks like when someone has done a search and moving Google maps around in the viewport -> api.php?location=houston#&lng=-95.34908043923292&lat=29.74942788453117.
The concept behind this API mashup is you have a search box, and you type in Houston, TX. Google maps will load and a feed from Instagram with display that have coordinates that are within Houston, Tx. The map will show where exactly where those photos taken. You move the map and we want more Instagram photos to show up but I can't pass the lng and lat variables to instagrams api. This is a bit of a long one, sorry.
Pastebin
can you try this and let me know,
$url=parse_url("http://domain.com/api.php?location=houston#&lng=-95.34908043923292&lat=29.74942788453117");
$myurl = $url["fragment"];
echo $myurl;
Update, to get individual variables
$url=parse_url("http://domain.com/api.php?location=houston#&lng=-95.34908043923292&lat=29.74942788453117");
$myurl = $url["fragment"];
echo $myurl.'<br>';
parse_str($myurl);
echo $lng.'<br>';
echo $lat;

Using $.get() to send data to servlet and insert into mysql

Recently I use $.getJSON to send request to flickr api to get some photo info (I got 100 data totally)
and in $.getJSON()'s callback function, I use $.each() and $.get('myServlet.do') to send data to servlet then insert into MySQL database.
I think it should be no problems, but I found that my database would have duplicated data if I use the method above, does anyone know what is the problem?
the data is duplicated when servlet received, btw.
it would be very appreciated if someone can give me some advice...
this is my code that how I using $.get() :
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select id,title,location.latitude,location.longitude,dates.taken,farm,server,secret from flickr.photos.info where photo_id in' + '(select id from flickr.photos.search(0) where text=\"' + queryText + '\" and has_geo=1 and lat=22.993299484253 and lon=120.20359802246 and content_type=1 and radius=20 and api_key=\"' + appid + '\" limit 100 ) and api_key=\"' + appid + '\"&format=json',
function (data) {
var clientTime = $('#clientTime').html();
$.each(data.query.results.photo,
function () {
console.log(this.id + " " + this.title + " " + this.farm + " " + this.server + " " + this.dates.taken);
$.post('insertphotoinfo.do', {
id: encodeURI(this.id),
title: encodeURI(this.title),
farm: encodeURI(this.farm),
server: encodeURI(this.server),
secret: encodeURI(this.secret),
takendate: encodeURI(this.dates.taken),
latitude: encodeURI(this.location.latitude),
longitude: encodeURI(this.location.longitude),
clientTime: encodeURI(clientTime)
},
function (Result) {
});
});
I'm afraid I know nothing about servlets, but I can address this from a MySQL perspective.
At a very simple level, if you are picking up the same data from Flickr each time, and then inserting all that data into a database, you will end up with duplicate data.
An INSERT command, however it is wrapped up, adds a row of data. It does not check to see if that data already exists.
In abstract, there are three solutions to your problem.
1) Write something that checks if an item already exists and then run UPDATE or INSERT as appropriate.
2) If you always collect a full set of data, and you have nothing that is dependent on an ID column, you could remove all the existing data before you insert the new data. If it is the only data in the table, you can use TRUNCATE.
3) Mark an appropriate column in MySQL as being UNIQUE. This will prevent another row being added with the same data - but your servlet may not like being passed an error.
The simplest is solution 2.
You will have to figure out yourself how any of these solutions is achieved with servlets, but armed with the right concepts you should be able to find something.

Categories