(XPages)Can use Javascript to connect ODBC data to show on XPages? - javascript

I have some data stored in ODBC, and those data look like this:
Does anyone use calculated fields or other functions to display ODBC data in XPages?
I need to display the data stored in ODBC in XPages, and then write other data to save back to ODBC.
Originally used ASP to write this function, the writing method is as follows:
Set conn = Server.CreateObject("ADODB.Connection")
conn.open b8_dsn
SQL = "SELECT PONUM as PONUM,COMP_NAME as Company,CASENAME AS Case_name,PRICE as Price"
SQL = SQL & " FROM CB4_AUCTION"
Set rs = conn.Execute(SQL)

Your best course of action is to encapsulate the ODBC (actually more JDBC) data into a managed bean. Design one property of the bean to be like
public List<SomeData> getRows();
and you can use beanName.rows directly in a repeat control as data source.
Design the SomeData as Java bean (which is fancy for: having getSomeValue(), setSomeValue(...) pairs of methods, so you can directly bind them to a form using beanInstanceName.someValue (where beanInstanceName is the variable name of your repeat control)
You can read about bean data binding here:
https://wissel.net/blog/2011/01/binding-controls-to-managed-beans.html
And how to save yourself some headache by creating and testing your bean outside of XPages first here:
https://wissel.net/blog/2013/06/managed-beans-xpages-and-testability.html
You want to use the extension library, which comes with ODBC/JDBC stuff and check related questions:
How do I access SQL from XPages
XPages JDBC connected to MS ACCESS DB, issue showing data in ViewPanel
Let us know what worked for you!

Related

How to solve syntax error or access violation for PHP Laravel project?

I have two tables which are claim table and claim_type table. Currently, I want to get the name of the claim inside the claim_type table. So, from the table Claim, we will get which type of claim (in the form of id) and after that, we can get the name of the type. I already have queried it inside MySQL workbench like this.
SELECT claim_types.name, count(*), sum(amount) FROM myteduh_v1.claims
join claim_types on claim_type_id = claim_types.id
group by claim_type_id;
When I post to the PHP, which to query it is like below. It turns out some error.
$ClaimsType = ClaimType::pluck('name')
->count()
->join('claim_types','claim_type_id','=', 'claim_types.id')
->groupBy('claim_type_id')
->get();
dd($ClaimsType);
$Claims_pie_chart = Charts::create('pie', 'highcharts')
->title('Total Claims Based On Type of Claims')
->labels(['$ClaimsType'])
->values([15,25,50])
->dimensions(1000,500)
->responsive(true);
After that, I want to insert the $ClaimsType into the labels variable to be pie chart labels. The question is, is it wrong the way I query the database inside the PHP controller?
If you want to use aggregation in one query, you should use DB:raw() in select
$ClaimsType = Claim::select(['claim_types.name', DB:raw('count(*)'), DB:raw('sum(amount)')])
->join('claim_types','claim_type_id','=', 'claim_types.id')
->groupBy('claim_type_id')
->get();
now you can use ->toSql() instad of ->get(), and you will see that query is same as yours raw query.

Laravel - Modifying data for API only for convenience

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.

Converting PHP object to JSON object using only Javascript

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!

Save dynamic data created using createElement(Javascript) to database

I am new to this forum as well as webpage designing. I am trying to design a profile management tool using JSP in which there are dynamically added(through javascript createElement) input fields to which names are assigned. I am able to save only one record to database and others are ignored.
My question is how to save all the data that is dynamically added?
Please help me on this.
Javascript code:Using the below function, I am able to get Javascript array
function addedu()
{
$(document).ready(function(){
$(".ed").each(function(input){
var value = $(this).val();
var id = $(this).attr('id');
t= id+' : '+ value;
arr.push(t);
});
});
var newinput1 = document.createElement("input");
newinput1.name="i1"
newinput1.className="ed"
newinput1.id="Education"
newinput1.innerHTML = "";
document.getElementById('edu').appendChild(newinput1);
}
JSP code:
String edu1=request.getParameter("i1");
Statement st1=con.createStatement();
String sql1="insert into education values('"+pno+"','"+edu1+"');
st1.executeUpdate(sql1);
On the client side you can use jQuery to dynamically add rows and read necessary values. To access the rows of the table you can use jQuery selectors. Then save the data in the JavaScript array, convert it to JSON and send it to the server side.
Here is an example (with using PHP, but in this case it doesn't matter):
Store HTML Table Values in a Javascript Array and Send to a PHP Script Using jQuery and Ajax
On the server side you'll need to make a lot of inserts via plain JDBC, use BATCH insert instead of hitting database once for each insert statement.
Here is an example:
Java: Insert multiple rows into MySQL with PreparedStatement
If you'll decide to use Spring, here is an example:
How to Insert multiple rows from web form into database using java spring framework

How to retrieve or display data on html page from db2 by sql adapter in ibm worklight? android hybrid apps development

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.

Categories

Resources