Display data from a php file in sencha touch2 - sencha-touch-2

How can I display data from a php file using sencha touch2 ?

You have several ways to achieve it but for me I will make use of json and Ext.ajax.request
For example my example.php look simple like this:
$array = array(
"go" => true,
"message" => "Thank you for your message",
);
As I have said, I'm using json so I will need to encode the $array to retrieve it in view later
echo json_encode($array);
Then in your view you can get the data from php file using Ext.util.JSONP.request() but here I will handle it by Ext.Ajax.request() so:
Ext.Ajax.request({
values : paramValues // values that you want to pass to example.php
url: 'example.php',
success: function(response) {
//Here you need to decode the json data
var data = Ext.decode(response.responseText)
go = data.go,
message = data.message;
console.log(message); //Thank you for your message
}
failure: function(response) {
console.log(response.responseText);
}
});
This maybe not the best way and possible have mistakes but at least I hope that it will be useful :)

create a JSON store and set url to php file. In the php file echo the response using json_encode();

Related

Get a JSON file from an AppScript backend, using an AppScript front end, without getting a CORS error?

I'm trying to build a an API-driven front end in Google AppsScript that calls a REST API hosted on AppScript to make some database queries.
I am currently simply trying to retrieve a JSON file with a GET request.
Everything I try, I get "CORS Missing Allow Origin".
My understand of CORS is that I might experience this with POST request (but maybe there's some people who have phrased their requests to get work this?)
I have a sense that the situation has changed over time, and what has worked in previous SO threads, doesn't seem to work for me now.
Sigh. I feel like Google's Documentation Team would benefit from a dedicated article to explaining how this is supposed to work.
If anyone can shed light on how I can get this to work, I've be most grateful:
client side code:
useEffect(() => {
fetch('https://script.google.com/macros/s/AKfycbz3_hgjZe0E35ZI2mw7aNs3ASkYCct77qIzL_WTOQMu_ZZeax9WpHpPIwm-MFPhZAW77g/exec/get/all', {
redirect: "follow",
headers: {
"Content-Type": "text/plain",
},
})
.then(result => result.json())
.then(rowData => setRowData(rowData))
}, []);
Server side code:
export function doGet(e) {
if (e.pathInfo.startsWith('get/all')) {
return getAllRecords(e);
}
else if (e.pathInfo.startsWith('get')) {
return getRecord(e);
}
else {
return getAllRecords(e);
//return HtmlService.createHtmlOutput('Error: invalid path- ' + e.pathInfo + '\n\n' + e.parameter + e);
}
}
function getAllRecords(e) {
// Connect to the MySQL database using the JDBC connector
const conn = Jdbc.getConnection(url, username, password);
// Construct the SELECT statement
const sql = `SELECT * FROM cars LIMIT 100`;
// Execute the INSERT statement
const stmt = conn.prepareStatement(sql);
const results = stmt.executeQuery();
// Return the inserted record with the generated id
const records = [];
while (results.next()) {
const record = {
id: results.getInt('id'),
name: results.getString('name'),
make: results.getString('make'),
price: results.getInt('price')
};
records.push(record);
}
return ContentService.createTextOutput(JSON.stringify(records)).setMimeType(ContentService.MimeType.TEXT);
// return ContentService.createTextOutput(JSON.stringify(records)).setMimeType(ContentService.MimeType.JAVASCRIPT);
}
I've tried various combination of MIME Type, and request headers and I'll try any combinations people suggest.
In order to use pathInfo, in this case, it is required to use the access token. I thought that this might be the reason for your current issue. But, when the access token is used, I'm worried that is might not be useful for your actual situation. So, in this answer, I would like to propose the following 2 patterns.
Pattern 1:
In this pattern, your script is modified using the access token. In this case, please modify your Javascript as follows.
From:
fetch('https://script.google.com/macros/s/AKfycbz3_hgjZe0E35ZI2mw7aNs3ASkYCct77qIzL_WTOQMu_ZZeax9WpHpPIwm-MFPhZAW77g/exec/get/all', {
redirect: "follow",
headers: {
"Content-Type": "text/plain",
},
})
.then(result => result.json())
.then(rowData => setRowData(rowData))
To:
const accessToken = "###"; // Please set your access token.
fetch('https://script.google.com/macros/s/AKfycbz3_hgjZe0E35ZI2mw7aNs3ASkYCct77qIzL_WTOQMu_ZZeax9WpHpPIwm-MFPhZAW77g/exec/get/all?access_token=' + accessToken)
.then(result => result.json())
.then(rowData => setRowData(rowData))
When you use the access token, please include the scopes of Drive API. Please be careful about this.
Pattern 2:
In this pattern, I would like to propose the modification without using the access token. When the access token cannot be used, unfortunately, pathInfo cannot be used. So, in this pattern, the query parameter is used instead of pathInfo.
Please modify your Javascript as follows.
From:
fetch('https://script.google.com/macros/s/AKfycbz3_hgjZe0E35ZI2mw7aNs3ASkYCct77qIzL_WTOQMu_ZZeax9WpHpPIwm-MFPhZAW77g/exec/get/all', {
redirect: "follow",
headers: {
"Content-Type": "text/plain",
},
})
.then(result => result.json())
.then(rowData => setRowData(rowData))
To:
fetch('https://script.google.com/macros/s/AKfycbz3_hgjZe0E35ZI2mw7aNs3ASkYCct77qIzL_WTOQMu_ZZeax9WpHpPIwm-MFPhZAW77g/exec?value=get%2Fall') // or ?value=get
.then(result => result.json())
.then(rowData => setRowData(rowData))
And also, please modify doGet of your Google Apps Script as follows.
Modified script:
function doGet(e) {
if (e.parameter.value == "get/all") {
return getAllRecords(e);
} else if (e.parameter.value = "get") {
return getRecord(e);
} else {
return getAllRecords(e);
}
}
Note:
In this modification, it supposes that your getAllRecords(e) works fine. Please be careful about this.
And, in this modification, it supposes that your Web Apps is deployed as Execute as: Me and Who has access to the app: Anyone. Please be careful about this.
When you modified the Google Apps Script of Web Apps, please modify the deployment as a new version. By this, the modified script is reflected in Web Apps. Please be careful about this.
You can see the detail of this in my report "Redeploying Web Apps without Changing URL of Web Apps for new IDE (Author: me)".
Thit is a sample modification. So, please modify this for your actual situation.
Reference:
Taking advantage of Web Apps with Google Apps Script (Author: me)

Apps Script PUT API

My goal is to update an API using Apps Script but I cannot work out how to do it. For simplicity sake here is my code:
let APIkey = "...";
let url = "..."
newData = {"stock_status": "instock"}
//Update API
The problem is I do not know how to get any further. I have read the relevant docs to this API but to no avail and I couldn't find anything about put requests in the Apps Script docs.
Answer:
You need to use UrlFetchApp.
Example:
I don't know how your API accepts authentication, but assuming it accepts the key as a URL parameter then you can do something like:
let APIkey = "..."
let url = "..."
const newData = {
"stock_status": "instock"
}
var options = {
'method' : 'PUT',
'contentType': 'application/json',
'payload' : JSON.stringify(newData)
}
UrlFetchApp.fetch(`${url}?key=${APIkey}`, options);
You can read the full documentation on fetch here

Requesting parameters are not sent over API in ionic 2

I am trying to send the the parameters using a post request but the parameters are not reaching to provide back the desired result and printing null as a result in console. here is my code
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded' );
let options = new RequestOptions({ headers: headers });
let postParams = {
acesscode: 'XXXXXXXXXXX',
productCode:'XXXXXXXXXX'
};
this.http.post("http://www.ebiebook.com/drmapi/v1/details", JSON.stringify(postParams), options)
.subscribe(data => {
console.log(data['_body']);
}, error => {
console.log(error);// Error getting the data
});
}
and the output screen is attached, It shows API is hitting well but the parameters data is unable to reach to provide the corresponding result. Please suggest.
This print you have attached does not show what is being sent by the request, instead it shows only the response your browser received from the server.
You better take a look at this thread here to see in this thread more about. You have to check the 'Headers' tab from Chrome's console -> Network.

How to POST to a url? (create an issue using JIRA api)

I have found this answer in how to create an issue in jira via rest api?
POST to this URL
https://<JIRA_HOST>/rest/api/2/issue/
This data:
{
"fields": {
"project":
{
"key": "<PROJECT_KEY>"
},
"summary": "REST EXAMPLE",
"description": "Creating an issue via REST API",
"issuetype": {
"name": "Bug"
}
}
}
In received answer will be ID and key of your ISSUE:
{"id":"83336","key":"PROJECT_KEY-4","self":"https://<JIRA_HOST>/rest/api/2/issue/83336"}
Don't forget about authorization. I used HTTP-Basic one.
Which I believe describes how to create an issue via posting to a url.
The problem is, I have no clue how this is actually implemented.
How does one POST to a url?
Is this the same as PHP post?
Where is the data kept?
What language is this all written in?
Sorry for such a vague question, This is all just so brand new to me I don't even know where to start researching this >_< Any sort of concrete example would be really really helpful!
Thank you!
The data section is written in JSON format, which is simply a text representation of a data structure. It is indented for readability, but really could be shown as:
{"fields":{"project":{"key": ""},"summary": "REST EXAMPLE","description":"Creating an issue via REST API","issuetype":{"name": "Bug"}}}
To POST to a URL and create an issue, you need a server-side mechanism to first authenticate aginst Jira, then send the data using HTTP POST.
In PHP, you can use cURL to POST or GET, or file_get_contents() to GET.
PHP cURL doc is here:
http://php.net/manual/en/book.curl.php
For example, here's a PHP function to create a Jira issue (after authentication):
public function createIssue(){
/*
Issue types:
1: Bug
3: Task
5: Sub-task
*/
$out = false;
$this->method = "POST";
$this->url = "http://10.50.25.64:8080/rest/api/2/issue/";
$this->data = array(
"fields" => array(
"project" => array("key" => $this->projectKey),
"summary" => $this->summary,
"environment" => $this->environment,
"description" => $this->description,
"issuetype" => array("id" => $this->issueType),
)
);
if (!empty($this->assignee)) $this->data['fields']['assignee'] = $this->assignee;
if (!empty($this->labels)) $this->data['fields']['labels'] = $this->labels;
foreach($this->customFields as $key => $val){
$this->data['fields'][$key] = $val;
}
$issue = $this->execCURL();
return $issue;
}
The function execCURL() takes the PHP array ($this->data) and sends it using PHP cURL.
Hope any of this helps!

Angularjs and Nodejs express

I'm trying to upload images through angularjs (client side) and Nodejs express (server side). I perfer not to use forms because my company does not work with it.
this is part of my controller-
$scope.uploadPhotoToServer = function () {
console.log('will upload to album ' + this.albumName + ' file ' + this.userPhoto);
var fd = new FormData();
//Take the first selected file
fd.append("file", this.userPhoto);
fd.append("album", this.albumName);
$http.post('/upload', fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
});
}]);
I wish if you could explain to me how this works and how I could continue
Thanks in advance :)
I'm not sure what you want to know, or what part you don't understand, but this basically just creates a $scope member function that adds the userPhoto and albumName to the FormData object (fd), which represents the form.The function then sends that object to the server using $http. You can think of the $http as a typical ajax command that just sends data to the server. (It actually uses the same XMLhttpRequest object that ajax does.
if you need it, here is a reference to the FormData() being used:
https://developer.mozilla.org/en-US/docs/Web/API/FormData