I am trying to replicate an app in Angular Material that I have had running for a couple years with HTTP/JavaScript etc. The app is what could be called a database type app with CRUD operations on a MySQL database on a remote server which uses PHP between the App and the Database.
Several of the tables which are returned from the server in JSON are range limited by a parameter sent from the JavaScript, and then received by the PHP, and used in the where clause of the Select statement like this code snippet:
$registration = $_POST['REGISTRATION'] ;
$query = "SELECT sysid, REGISTRATION, TYPE, COMPONENT, SERIAL, PART_NUMBER FROM status_hours WHERE REGISTRATION='$registration' ";
This HTTP/JavaScript/PHP code is working perfectly, however I would like to replicate the app in Angular Material.
With Angular Material I can retrieve recors in JSON perfectly, but the problem is that I can not send a parameter and get it working so that it can be used in the WHERE clause in the PHP.
Here is the Type Script code on the app which gets a table of rows from the server.
const url = 'http://mydatabase.com/angular/php/status_hours.php' ;
const options = { params: new HttpParams().set('REGISTRATION', this.REGISTRATION) } ;
this.http.get<Hours[]> (url, options)
.subscribe(hours =>
{
console.log(hours) ;
this.dataSource.data = hours ;
} ) ;
Here is the PHP code I have tried, to receive the parameter which is called REGISTRATION so that it can be used in the WHERE statement.
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$registration = $request->REGISTRATION;
The problem is either the parameter is not being sent by the Angular app, or it is not being received by the PHP so that it can be used in the WHERE clause.
I can hardcode for sumulation purposes, $registration = 'hardCodedData' ; and it will return valid JSON data.
Thank-you for your assistance.
Here is the answer to my question about proper procedure to pass parameters to PHP from Angular/TypeScript.
The PHP code must contain $registration = $_GET['REGISTRATION'] ; not $registration = $_POST['REGISTRATION'] ; which was working for me with HTML/JavaScript, and which I was using from published example code. Note, REGISTRATION is just the name of the parameter which was being sent by Angular.
Thanks for the assistance everyone!
Here is a link which I have used to enable me to pass multiple parameters. The same PHP code applies of course.
Angular 4 HttpClient Query Parameters
Related
I have created an UI5 Application to read a file and send it to a custom OData Service in the Backend.
onUploadFile: function() {
var oFileUpload =
this.getView().byId("fileUploaderFS");
var domRef = oFileUpload.getFocusDomRef();
var file = domRef.files[0];
var that = this;
var reader = new FileReader();
var ftype = file.type;
reader.readAsArrayBuffer(file);
reader.onload = function(evt) {
var vContent = evt.currentTarget.result
console.log(vContent);
var hex = that.buf2hex(vContent);
that.updateFile(hex, ftype);
}
},
buf2hex: function(buffer) {
return [...new Uint8Array(buffer)]
.map(x => x.toString(16).padStart(2, '0'))
.join('');
}
When I print the content of hex on the console before sending it to the backend, the data starts with 89504e470d0a1a0a0000000d49484 ....
Even before sending the data in the payload to Odata Service it shows the correct data
Here is the Odata Service
Inside the Create Stream the data when received, is getting converted into something else. As a result the image that has been saved is not opening.
I tried to change the Data Type of Content in SEGW to Binary and it did not work. I also tried to convert the data in the create_stream but in vain. At last I tried reading the data in UI5 in different formats but of no use.
This whole Odata service works perfectly fine when I load the data through Postman Application.
Please help me resolve this Issue. Thanks In Advance.
The sap.ui.unified.FileUploader has everything built in. No need for conversions from Buffer to hex.
Make sure that your FileUploader knows where to upload the file
<unified:FileUploader xmlns:unified="sap.ui.unified"
id="fileUploaderFS"
uploadUrl="/sap/opu/odata/sap/Z_TEST_SRV/FileSet"
/>
The attribute uploadUrl points to the media entity for which you implemented the create_stream method.
Then when the upload is triggered via button press, simply get the FileUploader, set the token (for security reasons when doing a POST request), and fire the upload method.
onUploadFile: function () {
const oFileUpload = this.getView().byId("fileUploaderFS");
const sToken = this.getModel("nameOfTheModel").getSecurityToken();
const oTokenParam = new FileUploaderParameter({
name: "x-csrf-token",
value: sToken
});
oFileUpload.removeAllHeaderParameters()
oFileUpload.addHeaderParameter(oTokenParam);
oFileUpload.upload();
}
To use FileUploaderParameter, make sure to import it at the beginning:
sap.ui.define([
// ...,
"sap/ui/unified/FileUploaderParameter"
], function (/*..., */FileUploaderParameter) {
// ...
Now about your File entity. When working with it via create_stream or read_stream, you don't use the entity structure but is_media_resource. This means your entity doesn't need a property content. Or most of the other properties (except a unique id and the mime type). All other properties would only be used if you want to do one of the CRUD methods (which happens almost never when dealing with streams).
We have a chat interface which we are using to request to dialogflow. Here the chat window is designed in php.
Now the chat can be initiated in any location, so when user connects we are also trying to capture timezone and send in the request to dialogflow. Based on the timeZone the results also differ.
Now i used the below code to append timezone, based on api considered from github in php.
GIT HUB link from where i have taken the code
https://github.com/GoogleCloudPlatform/php-docs-samples/blob/master/dialogflow/src/detect_intent_texts.php
The script taken from git hub is as follows
// Actual Script
// START dialogflow_detect_intent_text
//namespace Google\Cloud\Samples\Dialogflow;
use Google\Cloud\Dialogflow\V2\SessionsClient;
use Google\Cloud\Dialogflow\V2\TextInput;
use Google\Cloud\Dialogflow\V2\QueryInput;
use Google\Cloud\Dialogflow\V2\QueryParameters;
use Google\Cloud\Dialogflow\V2\SessionEntityTypesClient;
use Google\Cloud\Dialogflow\V2\EntityTypesClient;
use Google\Cloud\Dialogflow\V2\ContextsClient;
function detect_intent_texts($projectId, $texts, $sessionId, $languageCode = 'en-US')
{
$test = array('credentials' => 'apikey/test-cd4f0-XXXXX.json');
// new session
$sessionsClient = new SessionsClient($test);
$session = $sessionsClient->sessionName($projectId, $sessionId ?: uniqid());
printf('Session path: %s' . PHP_EOL, $session);
// query for each string in array
// create text input
$textInput = new TextInput();
$textInput->setText($text);
$textInput->setLanguageCode($languageCode);
// create query input
$queryInput = new QueryInput();
$queryInput->setText($textInput);
// get response and relevant info
$response = $sessionsClient->detectIntent($session, $queryInput);
$queryResult = $response->getQueryResult();
$queryText = $queryResult->getQueryText();
$intent = $queryResult->getIntent();
$displayName = $intent->getDisplayName();
$confidence = $queryResult->getIntentDetectionConfidence();
// output relevant info
$fulfilmentText = $queryResult->getFulfillmentText();
$sessionsClient->close();
}
echo detect_intent_texts('vehicle-test-cd4f0','text chat','123456','en-US','America/New_York');
// END dialogflow_detect_intent_text
Environment Details
OS : Linux
PHP 7.1
dialogflow v2
I have modified the script when sending data from detectIntent.
But my queryParams object returns me empty data, therefore the default timezone mentioned in the agent is considered. My main concern is to send TimeZone in the request. Which i am able to do with the online testing in google cloud interface https://cloud.google.com/dialogflow/docs/reference/rest/v2/projects.agent.sessions/detectIntent?apix=true. The same implementation is not working for me. What i am doing wrong? Please suggest.
/*
Modified script
All the other statements
*/
// I tried to add this code before the detectintent method to get timezone but the variable returns empty data.
// get response and relevant info
//queryParams optional adding new code before detectintent
$optionalArgs = new QueryParameters();
$optionalArgs->setTimeZone('America/New_York');
$optionalArgs->getTimeZone();
$optionArgs = (array)$optionalArgs;
$response = $sessionsClient->detectIntent($session, $queryInput, $optionArgs);// I have added $optionArgs for adding time zone
// other statements
//
// end of code
I'm trying to write a http rest client for my webservice and i need to send some PATCH requestes with data in the body.
I'm using the JUST library for sending requests ( https://github.com/JustHTTP/Just )
My express application just doesn't see the request.
Here's some code (i'm testing in playground, and everything went fine with other kind of requests like put, post...)
headers = ["accept":"application/json","content-type":"application/json","authorization":"key"] //key is ok
var data = ["id":3, "quantity":6]
var r = Just.patch("http://api.marketcloud.it/v0/carts/1233", headers:headers, data:data) //1233 is a cart Id
print(r)
print(r.json)
The method Just.patch returns an HTTPResult Object.
this says 'OPTIONS http://api.marketcloud.it/v0/carts/13234 200'
Also this object should contain a json, but it's 'nil'.
On the server-side, my express applications doesn't receive the request (it just logs an 'OPTION', but nothing else).
Could this be a playground-related problem? Or a just-related one?
Thanks for any suggestion
I managed to contact the library's author via twitter and he fixed the bug and answered me in less than 24h!
Here's the new release of the library.
https://github.com/JustHTTP/Just/releases
I have a ios device and a web service written in php. When the ios device send a request to the web service, the web service will response to that exact ios device. I don't know how can server send response to that device.
Thanks for your help!
You can research into each of these individual components:
1) App make a HTTP POST request to web service with a callback delegate method (ASIHttpRequest or AFNetworking)
2) Server receives request, parses it, then constructs a JSON response and return it back to the app automagically (use a web framework)
3) In your app's delegate callback method, you will parse the JSON data as a NSDictionary. You extract the JSON key-values using [yourDictionary valueForKey:#"name"];, [yourDictionary valueForKey:#"age"], [yourDictionary valueForKey:#"gender"], [yourDictionary valueForKey:#"email"] etc.
Then your app can either show the parsed data on the screen or do other things with it.
EDIT
Since you're using PHP as the web service language, I recommend using Symfony 2 web framework.
You'll write something like
// get request
$inputName = $_REQUEST['name'];
// ORM
$em = $this->getDoctrine()->getManager();
// find email based on name
$member = $em->getRepository('MyWebAppWebServiceBundle:Member')->findOneByName($inputName);
...
// construct JSON array
$json = array(
'id' => $member->getId(),
'name' => $member->getName(),
'email' => $member->getEmail()
);
// send the response back to the user as JSON data
$response = new Response(json_encode($json));
$response->headers->set('Content-Type', 'application/json');
return $response;
Alternatively, if you want scalable applications, you can use Node.js (server side Javascript)
If it's a mobile site or an app, you can use jquery ajax to query your webservice, which will yield a response if there is one.
I have a need to store files on Amazon AWS S3, but in order to isolate the user from the AWS authentication I want to go via an ASP page on my site, which the user will be logged into. So:
The application sends the file using the Delphi Indy library TidHTTP.Put (FileStream) routine to the ASP page, along with some authentication stuff (mine, not AWS) on the querystring.
The ASP page checks the auth details and then if OK stores the file on S3 using my Amazon account.
Problem I have is: how do I access the data coming in from the Indy PUT using JScript in the ASP page and pass it on to S3. I'm OK with AWS signing, etc, it's just the nuts and bolts of connecting the two bits (the incoming request and the outgoing AWS request) ...
TIA
R
A HTTP PUT will store the file at the given location in the HTTP header - it "requests that the enclosed entity be stored under the supplied Request-URI".
The disadvantage with the PUT method is that if you are on a shared hosting environment it may not be available to you.
So if the web server supports PUT, the file should be available at the given location in the the (virtual) file system. The PUT request will be handled by the server and not ASP:
In the case of PUT, the web server
handles the request itself: there is
no room for a CGI or ASP application
to step in.
The only way for your application to
capture a PUT is to operate on the
low-level, ISAPI filter level
http://www.15seconds.com/issue/981120.htm
Are you sure you need PUT and can not use a POST, which will send the file to a URL where your ASP script can read it from the request stream?
OK, Ive got a bit further with this. Code at the ASP end is:
var PostedDataSize = Request.TotalBytes ;
var PostedData = Request.BinaryRead (PostedDataSize) ;
var PostedDataStream = Server.CreateObject ("ADODB.Stream") ;
PostedDataStream.Open ;
PostedDataStream.Type = 1 ; // binary
PostedDataStream.Write (PostedData) ;
Response.Write ("PostedDataStream.Size = " + PostedDataStream.Size + "<br>") ;
var XML = AmazonAWSPUTRequest (BucketName, AWSDestinationFileID, PostedDataStream) ;
.....
function AmazonAWSPUTRequest (Bucket, Filename, InputStream)
{
....
XMLHttp.open ("PUT", URL + FRequest, false) ;
XMLHttp.setRequestHeader (....
XMLHttp.setRequestHeader (....
...
Response.Write ("InputStream.Size = " + InputStream.Size + "<br>") ;
XMLHttp.send (InputStream) ;
So I use BinaryRead, write it to a binary stream. If I write out the size of the stream I get the size of the file I POST'ed from my application, so I reckon the data is in there somewhere. I then call a routine (with the stream as a parameter) which sets up the AWS authentication/signing and does a PUT.
The AWS call returns no errors and a file of the correct name is created in the right place, but it has a size of zero! InputStream.Size has a value the same as the stream parameter passed to the routine - i.e. the size of the original file.
Any ideas?
POSTSCRIPT. Found the problem. It's caught me a few times with streams, this one. When you write data to a stream, don't forget to reset the stream position back to zero before trying to read from the stream again. I.e. just before the line:
XMLHttp.send (InputStream) ;
I needed to add:
InputStream.Position = 0 ;
My thanks for the interest and suggestions.