Currently i am loading a carto Table containing polyogns to my map on a php file using catro.js and the key is visible in javascript. Example given below is to call the sql api.
var layerStyle = $('#landuse-style').text();
cartodb.createLayer(CartoDbLib.map, {
user_name: 'sandyjones',
type: 'cartodb',
sublayers: [{
sql: "SELECT * FROM master " + query,
cartocss: layerStyle,
}],
extra_params: {
map_key: "myAPiKey"
}
}
how to hide this api key on my server using proxy php file or a backend php file if you can suggest a code example that i can use.
sometime back i tried but i was stuck with a problem that in the url of images from carto server will contain the map key.
I'm afraid you would need to create your own proxy. Here is a node.js-based proxy as sample: https://github.com/CartoDB/cartodb-api-proxy , but this is not supported code and probably it is even outdated.
If your table data is anyway public (and it will be public - via proxy also), then I'd define the table as "Public" in Carto web, then your app does not need to put API key to the request at all.
Related
I need an advice from skilled Wordpress developers. My organization has internal MS Access database which contains numerous tables, reports and input forms. The structure of DB is not too complicated (persons information, events, third parties info and different relations between them). We woild like to show some portion of this info at our Wordpress site, which currently has only news section.
Because information in our DB updated each day, also we would like to make simple synchronization between MS Access DB and Wordpress (MySQL DB). Now I try to find the best way how to connect MS Access and Wordpress.
At present I see only these ways how to do this:
Make export requests and save to XML files.
Import to MySQL DB of Wordpress.
Show content on Wordpress site using Custom fields feature (or develop own plugin).
-OR-
Build own informational system on some very light PHP engine (for example CodeIgniter) on same domain as Wordpress site, which will actually show imported content.
These variants needs manual transfer info between DB each day. And I don't know possibilities of Wordpress to show custom data from DB. Would you suggest me what ways will you prefer to use in my case?
P.S. MS Access used is ver 2007+ (file .accdb). Name of fields, db's and content is on Russian language. In future we planning to add 2 new languages (English, Ukrainian). MS access DB also contains persons photos included.
---Updated info---
I was able to make semi-atomatic import/export operations using following technique:
Javascript library ACCESSdb (little bit modified for new DB format)
Internet Explorer 11 (for running ADODB ActiveX)
small VBS script for extracting attached files from MSAccess tables.
latest jQuery
Wordpress plugins for custom data (Advanced Custom Fields, Custom Post Type UI)
Wordpress Rest-API enabled (with plugins JSON Basic Authentication, ACF to REST API)
At first I've constructed data scheme at Wordpress site using custom post and custom fields technique. Then I locally run JS queries to MSAccess DB, received info I sending via jQuery to WP Rest-API endpoints. Whole transfer operation can be made with in 1 click.
But I can't upload files automatically via JS due to security limitations. This can be done in +1 click per file.
Your question is too broad.
It consist of two parts: 1. export from Access and 2. import to Wordpress. Since i'm not familiar with Wordpress I can only give you advice about 1 part. At least google shows that there is some plugins that able to import from CSV like this one:
https://ru.wordpress.org/plugins/wp-ultimate-csv-importer/
You can create a scheduled task that runs Access that runs macro that runs VBA function as described here:
Running Microsoft Access as a Scheduled Task
In that VBA function you can use ADODB.Stream object to create a UTF-8 CSV file with you data and make upload to FTP of your site.
OR
Personally i use a python script to do something similar. I prefer this way because it is more straitforward and reliable. There is my code. Notice, that i have two FTP servers: one of them is for testing only.
# -*- coding: utf-8 -*-
# 2018-10-31
# 2018-11-28
import os
import csv
from time import sleep
from ftplib import FTP_TLS
from datetime import datetime as dt
import msaccess
FTP_REAL = {'FTP_SERVER':r'your.site.com',
'FTP_USER':r'username',
'FTP_PW':r'Pa$$word'
}
FTP_WIP = {'FTP_SERVER':r'192.168.0.1',
'FTP_USER':r'just_test',
'FTP_PW':r'just_test'
}
def ftp_upload(fullpath:str, ftp_folder:str, real:bool):
''' Upload file to FTP '''
try:
if real:
ftp_set = FTP_REAL
else:
ftp_set = FTP_WIP
with FTP_TLS(ftp_set['FTP_SERVER']) as ftp:
ftp.login(user=ftp_set['FTP_USER'], passwd=ftp_set['FTP_PW'])
ftp.prot_p()
# Passive mode off otherwise there will be problem
# with another upload attempt
# my site doesn't allow active mode :(
ftp.set_pasv(ftp_set['FTP_SERVER'].find('selcdn') > 0)
ftp.cwd(ftp_folder)
i = 0
while i < 3:
sleep(i * 5)
i += 1
try:
with open(fullpath, 'br') as f:
ftp.storbinary(cmd='STOR ' + os.path.basename(fullpath),
fp=f)
except OSError as e:
if e.errno != 0:
print(f'ftp.storbinary error:\n\t{repr(e)}')
except Exception as e:
print(f'ftp.storbinary exception:\n\t{repr(e)}')
filename = os.path.basename(fullpath)
# Check if uploaded file size matches local file:
# IDK why but single ftp.size command sometimes returns None,
# run this first:
ftp.size(filename)
#input(f'overwrite it: {filename}')
ftp_size = ftp.size(os.path.basename(fullpath))
# import pdb; pdb.set_trace()
if ftp_size != None:
if ftp_size == os.stat(fullpath).st_size:
print(f'File \'{filename}\' successfully uploaded')
break
else:
print('Transfer failed')
# input('Press enter for another try...')
except OSError as e:
if e.errno != 0:
return False, repr(e)
except Exception as e:
return False, repr(e)
return True, None
def make_file(content:str):
''' Make CSV file in temp directory and return True and fullpath '''
fullpath = os.environ['tmp'] + f'\\{dt.now():%Y%m%d%H%M}.csv'
try:
with open(fullpath, 'wt', newline='', encoding='utf-8') as f:
try:
w = csv.writer(f, delimiter=';')
w.writerows(content)
except Exception as e:
return False, f'csv.writer fail:\n{repr(e)}'
except Exception as e:
return False, repr(e)
return True, fullpath
def query_upload(sql:str, real:bool, ftp_folder:str, no_del:bool=False):
''' Run query and upload to FTP '''
print(f'Real DB: {real}')
status, data = msaccess.run_query(sql, real=real, headers=False)
rec_num = len(data)
if not status:
print(f'run_query error:\n\t{data}')
return False, data
status, data = make_file(data)
if not status:
print(f'make_file error:\n\t{data}')
return False, data
fi = data
status, data = ftp_upload(fi, ftp_folder, real)
if not status:
print(f'ftp_upload error:\n\t{data}')
return False, data
print(f'Done: {rec_num} records')
if no_del: input('\n\nPress Enter to exit and delete file')
os.remove(fi)
return True, rec_num
Let's assume the following data that is exactly being returned like it's stored into database:
[
{
"user_name": "User 1",
"photo_file": "user1.jpg"
},
{
"user_name": "User 2",
"photo_file": "user2.jpg"
}
// ...
]
I want to use this data in a JavaScript application but I'd like to append a full path of the user's photo, like doing a treatment for the data before returning it to the API. How can I do that using Laravel?
I assume at present you're just converting the results of your query into JSON and returning that. This works, but it does mean the response is tightly coupled to your database structure, which is a bad idea. Ideally you should have a layer of abstraction to handle adding and formatting data, kind of like a view layer in MVC.
There are plenty of solutions for this. I use Fractal for my Laravel API's. It allows you to easily customise the output of a particular endpoint by specifying a transformer that will render that object for you. That way you can easily choose the data to display and format it how you wish.
Accessors are good for this.
Let's assume your data is stored in a model called Customer. I would write an accessor like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
protected $appends = ['photo_file']; // In order to see the new attribute in json dumps
public function getPhotoPathAttribute()
{
$name = $this->getAttribute('photo_file');
if(!isset($name))
return null;
return '/full/path/to/image/' . $name;
}
}
This way you can now call $customer->photo_path and it will return `/full/path/to/image/image_name.jpg' (or null if the attribute is not set).
Edit:
In order to show this attribute in jsons (without specifically calling $model->photo_path) you will also need to add protected $appends = ['photo_file'] to the model (updated).
I would recommend against overriding original name (so I leave photo_file attribute untouched).
If you are building Laravel API, sure, as Matthew said, go and check Fractal. But don't forget to Dingo, the best tool for building API at Laravel. And it uses Fractal too.
I am making a mobile app with Phonegap and using Wordpress as a backend. I am using Advanced Custom Fields with a Google Maps post field which returns a PHP object to the app using JSON API. My Wordpress backend sends a normal JSON object to the app, but inside that object is where a stringified PHP object is returned.
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress). I have looked at other answers that say to use json_encode for this but my problem is that the app is just HTML/Javascript and no PHP. Is there a way to use PHP code in the middle of a Javascript function to do this? Or would it be better to change the backend so that it returns a JSON object instead of a PHP object in the first place? If so, how do I do that?
My experience in PHP is still somewhat limited so any help is appreciated.
edit: To clarify a bit more, I am using Wordpress on a separate domain from my Phonegap app and only using the JSON API plugin on the Wordpress end. I am then using jQuery Ajax calls to retrieve data from the Wordpress backend.
Also the returned PHP object looks like this: a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}
Another way I just thought of as well, would it be possible to just leave it as a PHP object and still read out the values from it somehow? I don't NEED it to be a JSON array, I just need a way to read the individual elements in the array in one way or another.
Here is also a tiny snippet of the JSON returned to clarify what I'm talking about.
"custom_fields": {
"location": [
"a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}"
]
}
That of course isn't the entire JSON object but it gives you an idea of what I'm dealing with.
I know you have a solution that works on the front end, but I still think it'd be better to fix this on the server.
Based on our conversation in the comments, I've had a closer look the code in the WordPress forum. The problem seems to be that the location field is an array of strings, not just a string. maybe_unserialize (and is_serialized, which it uses) don't handle arrays. Here's the updated code, which you should be able to drop into your theme's functions.php. I did a quick test, and it works for me.
class unserialize_php_arrays_before_sending_json {
function __construct() {
add_action( 'json_api_import_wp_post',
array( $this, 'json_api_import_wp_post' ),
10,
2 );
}
function json_api_import_wp_post( $JSON_API_Post, $wp_post ) {
foreach ( $JSON_API_Post->custom_fields as $key => $custom_field ) {
if (is_array($custom_field)) {
$unserialized_array = array();
foreach($custom_field as $field_key => $field_value) {
$unserialized_array[$field_key] = maybe_unserialize( $field_value );
}
$JSON_API_Post->custom_fields->$key = $unserialized_array;
}
else {
$JSON_API_Post->custom_fields->$key = maybe_unserialize( $custom_field );
}
}
}
}
new unserialize_php_arrays_before_sending_json();
If you're using a JSON API to retrieve the data, then why don't you deliver the data in JSON format to your app? Otherwise you seem to remove much of the point of using an API in the first place... You could of course parse that string in JavaScript if you really want to but that's a very ugly and error prone solution.
The JSON API plugin does seem to use JSON:
https://wordpress.org/plugins/json-api/screenshots/
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress).
This bit here leaves me confused. You do not have PHP objects on the client-side, PHP is a back-end technology. What is returned to the client is a string which can be HTML, XML, JSON, plaintext on any other form of encoding.
That said, saying you have an object $obj in PHP, you could pass it to your front-end application creating an end-point retrieve_object.php and in there:
echo json_encode($obj);
So long as that is the only thing your are outputting, you lient-side app can make a request (Eg: AJAX) to retrieve_object.php and get the json object.
BUT , and this is important (!) in doing so you serialize object properties. You will lose any PHP object method. If any object property is an object itself (EG: A DB Connection) then this will be lost too.
Hope this helps!
How to retrieve or display data on html page from db2 by sql adapter in ibm worklight?
What are the codes for these?
How to Display data in a text box?
How to Display data in a label?
How to Display data in a drop down box?
How to select check box?
like automatically getting data from db2 for example
Interests:Technology,Science,etc. Now the user can update/change
data and save.
How to select radio/option button? like
automatically getting data from db2 for example Gender:Male or
Female. Now the user can update/change data and save.
like in jsp.
Is the codes are same in android hybrid apps development or not?
<body>
<center><h2>Your Account Details</h2></center>
<%
String usertype="general";
String email=(String)session.getAttribute("email");
String pwd=(String)session.getAttribute("pwd");
String sex=new String();
Connection con=null;
try
{
if(email==null)
out.println("<center>Please Login to view your account!!!");
//MS ACCESS
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:dsn1");
PreparedStatement pst=null;
pst=con.prepareStatement("select * from user1 where usertype=? and email=? and pwd=?");
//"select * from user1 where usertype='"+usertype+"' and email = '"+email+"' and pwd='"+pwd+"'"
synchronized(pst)
{
pst.setString(1, usertype);
pst.setString(2, email);
pst.setString(3, pwd);
}
ResultSet rs = pst.executeQuery();
while(rs.next())
{
//usertype=rs.getString(1);
email=rs.getString(2);
//pwd=rs.getString(3);
sex=rs.getString(4);
//out.println("<b>");
out.println ("<center><table>");
out.println("<tr>");
out.println("<td>");
out.println("<b>Email:</b> "+email);
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>");
out.println("<b>Sex:</b> "+sex);
out.println("</td>");
out.println("</tr>");
}
catch(Exception e)
{
e.printStackTrace();
}
//return false;
finally
{
con.close();
}
%>
</body>
My suggestion:
Read the tutorials provided by IBM to learn about Worklight adapters and how they work
Search Stack Overflow, as this has been asked many times...
What you need to do is adapt the JavaScript snippets provided in the questions below to place the value, instead of inside a table or UL elements, to a textfield or a Select. It is the same principle repeating itself.
Because this is a duplicate, there is no value in copying code to this question as well.
Please review the following:
IBM Worklight - Unable to display data retrieved using SQL adapter
Invoking Worklight Adapter and Displaying that JSON data in list view as strings
use resultset returned by WL.Server.invokeSQLStatement within sql adapter procedure
Insertion of values in database
How to retrieve images from existing database using sql/http adapter from worklight application
Understand that placing data into HTML elements is unrelated to Worklight, rather it is a standard technique in JavaScript. You need to grasp the concept of that.
You can do that by finding the ID of the HTML element and appending data to it, or replacing it completely, or dynamically insert into it. This is demonstrated in the questions above.
I have a Single Page App (SPA) built using Durandal, ASP.net MVC Web API, Breeze and knockout js.
I need to export a list to an Excel sheet that should be downloaded to the download folder on click of a button on the html page.
While I have successfully done that by converting the JSON data to csv format in javascript(on client side), it is taking too much time if the amount of data is large(3000 + rows or it can be around 12000).
I am having problem in sending the excel file as response type from the Web API call made through Breeze.js.
Is there a way to do this in a way which should be a bit fast as it might also be required on mobile devices?
EDIT
Below is the code I have written -
JavaScript code for binding -
function exportListToExcel() {
DataContext.exportListToExcel().then(function (data) {
//Do some stuff.
});
}
In the Data context file implemented in breeze, the code is returning the promise -
function exportListToExcel() {
function querySucceeded() {
//return data;
}
return util.sendRequest(config.baseApiPath + 'breeze/MyController/ExportListToExcel')
.then(querySucceeded)
.fail(queryFailed);
}
Below code is the request sent to the Web API. I don't know if it should be HttpPost or something else.
[HttpPost]
public HttpResponseMessage ExportListToExcel()
{
return ExportListToExcel();
}
And below is the back end code -
public static HttpResponseMessage ExportListToExcel()
{
//Method which returns table data. This is working fine though.
object listObject = GetListData();
Table listData = (Table)listObject;
string attachment = "attachment; filename=Report.xlsx";
HttpResponseMessage File = new HttpResponseMessage(HttpStatusCode.OK);
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", attachment);
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
StringBuilder str = new StringBuilder();
str.Append("<table border=`" + "1px" + "`b>");
str.Append("<tr>");
foreach (DataColumn dc in listData.Columns)
{
str.Append("<td><b><font face=Arial Narrow size=3>" + dc.ColumnName + "</font></b></td>");
}
str.Append("</tr>");
foreach (DataRow dr in listData.Rows)
{
str.Append("<tr>");
for (int i = 0; i < listData.Columns.Count; i++)
{
str.Append("<td><font face=Arial Narrow size=" + "14px" + ">" + dr[i].ToString() + "</font></td>");
}
str.Append("</tr>");
}
str.Append("</table>");
byte[] temp = System.Text.Encoding.UTF8.GetBytes(str.ToString());
//To write the table to the File content.
File.Content = new StringContent(temp.ToString());
return File;
}
This however is not working and in the data context file, queryFailed() method is executed.
I don't know where I am going wrong or what I am missing out here. Also, it would be much help to let me know how to handle the file/data which the promise returns.
My instinct is that BreezeJS is the wrong tool for this particular job ... and I say that as a co-author of BreezeJS.
The trouble begins with the paradigm. I'm having trouble thinking of spreadsheet rows as "entities" in the usual sense of business objects. They seem more like simple data to me.
In this example, we're very far from entity-thinking. You appear to be preparing a big chunk of HTML for display on the client. There is nothing "entity-like" about this.
I have no quarrel with your intent. But I think you should treat this as you would any other raw resource (e.g., images) and fetch it with simple AJAX using whatever component is available to you.
You may be building a hybrid app in which you have both raw data (or HTML) and an entity model. Breeze is a fine tool for the app as long as you apply it appropriately. Your Breeze app is already delegating to a low level AJAX component (e.g., jQuery.ajax or Angular's $http) and you should be able to find that component in your code base and use it directly for this particular csv task.