I would like to know what is the correct procedure for making a GET request inside the application code. I mean, not in the URL (is that a good practice?).
As always, I like to give you examples on what I'm looking for. So here it is:
HTML:
(...)
<div class="input-area">
<input type="text" value="SOME VALUE" id="text-field">
<input type="submit" value="Submit" id="button">
</div>
(...)
Let's assume that the #button action is "submitForm".
DART (it's incomplete):
void submitForm(Event e) {
e.preventDefault();
request = new HttpRequest();
request.onReadyStateChange.listen(dataIsReady);
request.open("GET", "http://127.0.0.1:8123");
(???)
}
What I would like to happen is the value on the text-field to be sent to the server as a parameter. Just to clarify, I'll be using that parameter to search for some entries in a MySQL database (and return some JSON data).
So how can I do that with Dart?
library x;
import 'dart:html';
void main() {
// you can create an URI and use the toString() method to create a
// String you can pass to the request
Map query = {
'xx': 'yy',
'zz': 'ss'
};
Uri uri =
new Uri(
path: "http://localhost:8080/myapp/signinService",
queryParameters: query);
print('URI: ${uri.toString()}');
querySelector("#signinForm")..onSubmit.listen(handle);
}
void handle(Event event) {
event.preventDefault();
// or you can use the form elements formdata
FormElement formElement = event.target as FormElement;
var url = "http://localhost:8080/myapp/signinService";
HttpRequest.request(
url,
method: formElement.method,
sendData: new FormData(formElement)).then(onDataLoaded);
}
void onDataLoaded(HttpRequest req) {
String response = req.responseText;
if (response == 1) {
window.alert("You are signed in!");
} else {
window.alert("Sign in failed. Check credentials.");
}
}
html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="packages/browser/dart.js"></script>
</head>
<body>
<h1>Alarm</h1>
<!-- I used a form element and set the request method here. It can be set in code too -->
<form id="signinForm" class="form-signin" method="GET">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="input-block-level" name="email" placeholder="Email address">
<input type="password" class="input-block-level" name="password" placeholder="Password">
<button class="btn btn-large btn-primary" id="signinBtn" type="submit">Sign in</button>
</form>
<script type="application/dart" src="alarm.dart"></script>
</body>
</html>
Related
I'm coding a search form to get some data from database
I don't know what am i doing wrong. The page just refreshes and nothing happens.
1- I have a form with a input called "term"
2- My route: Route.get('/telefone', 'TelefoneController.show')
MY CONTROLLER
async show ({ params, request, response, view }) {
const term = request.input('term');
const nome = await Telefone.query().where('atendente', 'LIKE',
'%'+term+'%').fetch()
console.log(nome);
return view.render('telefone', {
nome: nome,
})
}
MY HTML
<div class="container d-flex">
<form action="{{ route('/telefone')}}" method="get" class="col-sm-8">
<div class="form-group">
<label for="campotel">Buscar Nome</label>
<input type="text" name="term" class="form-control" id="campotel" placeholder="Digite o nome do funcionário">
</div>
<button type="submit" class="btn btn-success float-right">Buscar</button>
</form>
</div>
DB STRUCTURE
class TelefoneSchema extends Schema {
up () {
this.create('telefones', (table) => {
table.increments()
table.string('ramal')
table.string('voip')
table.string('atendente')
table.integer('id_departamento')
.unsigned()
.references('id')
.inTable('departamentos')
.onUpdate('CASCADE')
.onDelete('CASCADE')
table.integer('id_polo_telefone')
.unsigned()
.references('id')
.inTable('polos')
.onUpdate('CASCADE')
.onDelete('CASCADE')
table.timestamps()
})
}
down () {
this.drop('telefones')
}
}
module.exports = TelefoneSchema
page just refresh and nothing happens
I tried on my side without being able to reproduce the case.
But I have some information that might perhaps help you:
When the query returns no value the result is null. -> make sure your db have values
My test code (work fine):
My controller:
'use strict'
const Telefone = use('App/Models/Telefone')
class TelefoneController {
async show ({ params, request, response, view }) {
const term = request.input('term')
console.log(term)
const result = await Telefone.query().where('atendente', 'like',
'%'+term+'%').fetch()
const nome = result.toJSON()
console.log(nome) // Return JSON array
return view.render('welcome', {
nome: nome,
})
}
}
module.exports = TelefoneController
My schema (I don't use all your datas) :
class TelefoneSchema extends Schema {
up () {
this.create('telefones', (table) => {
table.increments()
table.string('ramal')
table.string('voip')
table.string('atendente')
table.timestamps()
})
}
down () {
this.drop('telefones')
}
}
My view :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Hello Adonis</title>
</head>
<body>
<h1>Ramal : {{ nome[0].ramal }}</h1>
<div class="container d-flex">
<form action="{{ route('/telefone')}}" method="get" class="col-sm-8">
<div class="form-group">
<label for="campotel">Buscar Nome</label>
<input type="text" name="term" class="form-control" id="campotel" placeholder="Digite o nome do funcionário">
</div>
<button type="submit" class="btn btn-success float-right">Buscar</button>
</form>
</div>
</body>
</html>
I hope it might help you a little bit.
I'm trying to implement FineUploader React library into my React app to upload files to my Azure Blob Storage.
Looks like for some reason, FineUploader is getting the blob storage URI wrong.
This is how I instanciate a FineUploader in my test component:
import React, { Component } from 'react';
import FineUploaderAzure from 'fine-uploader-wrappers/azure'
import Gallery from './gallery/index';
const uploader = new FineUploaderAzure({
options: {
cors: {
expected: true,
sendCredentials: true
},
signature: {
endpoint: 'https://myapp.com/api/getsas'
},
request: {
endpoint: 'https://myaccount.blob.core.windows.net/test-container'
},
uploadSuccess: {
endpoint: 'https://myapp.com/api/done'
}
}
})
class Index extends Component {
render() {
return (
<Gallery uploader={uploader} />
)
}
}
export default Index;
Here's the error I'm seeing in the console. Looks like FineUploader is using the wrong URI for the blob storage.
Any idea what may be causing this?
UPDATE:
As per #GauravMantri's suggestion, I changed endpoint to containerUrl in the options section but that didn't seem to help either. Here's what it looks like:
const uploader = new FineUploaderAzure({
options: {
cors: {
expected: true,
sendCredentials: true
},
signature: {
endpoint: 'https://myapp.com/api/getsas'
},
request: {
containerUrl: 'https://myaccount.blob.core.windows.net/test-container'
},
uploadSuccess: {
endpoint: 'https://myapp.com/api/done'
}
}
})
Here's the SAS I'm getting when I send a request through Postman:
The request I'm sending is:
http://example.com/api/files/get/sas?blobUri=https://myaccount.blob.core.windows.net/test-container/test.txt&_method=put
And here's the SAS I receive:
"?sv=2017-04-17&sr=b&sig=7pXTnI2r8uGyZms12T9cRvHg1XlLI53ZJtwPUwGElnY%3D&st=2017-12-28T14%3A02%3A56Z&se=2017-12-28T14%3A22%3A56Z&sp=w"
I was able to make it work. Basically there're a few things that one need to keep in mind:
In your FineUploader config, you will need endpoint attribute and that should have the URL of the blob container where you want to upload. This is how configuration looks like in my code:
var uploader = new qq.azure.FineUploader({
debug: true,
element: document.getElementById("uploader"),
cors: {
expected: true,
sendCredentials: false
},
signature: {
endpoint: 'http://localhost:63194/users/sas'
},
request: {
endpoint: 'https://account-name.blob.core.windows.net/container-name'
},
})
The API for getting Shared Access Signature (SAS) should return blob URL + SAS Token. The blobUrl parameter to the API should be the absolute URL of the blob. This is the code I used for API (please don't use this as is because the code below does not take into consideration the _method parameter):
[Route("sas")]
[HttpGet]
public async Task<HttpResponseMessage> Sas(string blobUri)
{
var credentials = new StorageCredentials("account-name", "account-key");
var blob = new CloudBlockBlob(new Uri(blobUri), credentials);
var sasParameters = new SharedAccessBlobPolicy()
{
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(1),
Permissions = SharedAccessBlobPermissions.Write
};
var sasToken = blob.GetSharedAccessSignature(sasParameters);
var returnValue = blob.Uri.AbsoluteUri + sasToken;
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(returnValue, System.Text.Encoding.UTF8, "text/plain");
return resp;
}
I downloaded Fine Uploader Azure related files from here: https://fineuploader.com/customize.html and used it to create a simple HTML page to test it. Here's what my HTML page looks like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="fine-uploader-gallery.min.css" rel="stylesheet">
<script src="azure.fine-uploader.min.js""></script>
<script type="text/template" id="qq-template">
<div class="qq-uploader-selector qq-uploader qq-gallery" qq-drop-area-text="Drop files here">
<div class="qq-total-progress-bar-container-selector qq-total-progress-bar-container">
<div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-total-progress-bar-selector qq-progress-bar qq-total-progress-bar"></div>
</div>
<div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
<span class="qq-upload-drop-area-text-selector"></span>
</div>
<div class="qq-upload-button-selector qq-upload-button">
<div>Upload a file</div>
</div>
<span class="qq-drop-processing-selector qq-drop-processing">
<span>Processing dropped files...</span>
<span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
</span>
<ul class="qq-upload-list-selector qq-upload-list" role="region" aria-live="polite" aria-relevant="additions removals">
<li>
<span role="status" class="qq-upload-status-text-selector qq-upload-status-text"></span>
<div class="qq-progress-bar-container-selector qq-progress-bar-container">
<div role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" class="qq-progress-bar-selector qq-progress-bar"></div>
</div>
<span class="qq-upload-spinner-selector qq-upload-spinner"></span>
<div class="qq-thumbnail-wrapper">
<img class="qq-thumbnail-selector" qq-max-size="120" qq-server-scale>
</div>
<button type="button" class="qq-upload-cancel-selector qq-upload-cancel">X</button>
<button type="button" class="qq-upload-retry-selector qq-upload-retry">
<span class="qq-btn qq-retry-icon" aria-label="Retry"></span>
Retry
</button>
<div class="qq-file-info">
<div class="qq-file-name">
<span class="qq-upload-file-selector qq-upload-file"></span>
<span class="qq-edit-filename-icon-selector qq-btn qq-edit-filename-icon" aria-label="Edit filename"></span>
</div>
<input class="qq-edit-filename-selector qq-edit-filename" tabindex="0" type="text">
<span class="qq-upload-size-selector qq-upload-size"></span>
<button type="button" class="qq-btn qq-upload-delete-selector qq-upload-delete">
<span class="qq-btn qq-delete-icon" aria-label="Delete"></span>
</button>
<button type="button" class="qq-btn qq-upload-pause-selector qq-upload-pause">
<span class="qq-btn qq-pause-icon" aria-label="Pause"></span>
</button>
<button type="button" class="qq-btn qq-upload-continue-selector qq-upload-continue">
<span class="qq-btn qq-continue-icon" aria-label="Continue"></span>
</button>
</div>
</li>
</ul>
<dialog class="qq-alert-dialog-selector">
<div class="qq-dialog-message-selector"></div>
<div class="qq-dialog-buttons">
<button type="button" class="qq-cancel-button-selector">Close</button>
</div>
</dialog>
<dialog class="qq-confirm-dialog-selector">
<div class="qq-dialog-message-selector"></div>
<div class="qq-dialog-buttons">
<button type="button" class="qq-cancel-button-selector">No</button>
<button type="button" class="qq-ok-button-selector">Yes</button>
</div>
</dialog>
<dialog class="qq-prompt-dialog-selector">
<div class="qq-dialog-message-selector"></div>
<input type="text">
<div class="qq-dialog-buttons">
<button type="button" class="qq-cancel-button-selector">Cancel</button>
<button type="button" class="qq-ok-button-selector">Ok</button>
</div>
</dialog>
</div>
</script>
<title>Fine Uploader Gallery UI</title>
</head>
<body>
<div id="uploader"></div>
<script>
// Some options to pass to the uploader are discussed on the next page
var uploader = new qq.azure.FineUploader({
debug: true,
element: document.getElementById("uploader"),
cors: {
expected: true,
sendCredentials: false
},
signature: {
endpoint: 'http://localhost:63194/users/sas'
},
request: {
endpoint: 'https://account-name.blob.core.windows.net/container-name'
},
})
</script>
</body>
</html>
Once I ran this code, I was able to upload files in my blob container without any problems.
I am using ADAL.js(which calls Azure Active Directory) as javascript library for verifying the user. I am using the following code for this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.15/js/adal.min.js"></script>
<script>
var endpoints = {
"https://management.core.windows.net": "https://management.core.windows.net"
};
var config = {
clientId: 'e333d3fe-a73a-4476-8121-8a57f9a972ca',
endpoints: endpoints,
};
var authContext = new AuthenticationContext(config);
authContext.handleWindowCallback();
function onSuccessLogin(error, token, msg) {
console.log("Inside Call back");
if (!!token) {
console.log("Log-in to Azure successfully done", token);
}
else {
console.log("Error while log-in to Azure", error);
}
if (!!authContext._user) {
console.log("You are connected to Azure ")
}
}
function login() {
authContext.popUp = true;
authContext.callback = onSuccessLogin;
authContext.login();
// authContext.handleWindowCallback();
var user = authContext.getCachedUser();
console.log(user);
};
function logout () {
authContext.logout();
};
</script>
<input id="Button1" type="button" value="clickme" onclick="clickme()" />
<input id="Button3" type="button" value="login" onclick="login()" />
<input id="Button2" type="button" value="logout" onclick="logout()" />
// These are the text-boxes whose value I want to retain.
First name:<br>
<input id=fname" type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input id="lname" type="text" name="lastname" value="Mouse">
</body>
</html>
These are few issue with this code in Edge, although everything is working fine in chrome:
Why the onSuccessLogin() is not always called on edge?
Why the pop window for log-in is not appearing always?
Sometime after entering the credential the pop won't close.
What worked for me is:
set the config.callback and popUp=true before calling AuthenticationContext(config)
Also you should not call handleWindowCallback() if the URL does not contain a #. The code should be:
if (authenticationContext.isCallback(window.location.hash)) {
authenticationContext.handleWindowCallback();
I suggest that you have a look and adapt the following sample I tested and worked in Edge (and of course Chrome) in both cases (with and without popup):
https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof-ca/blob/master/TodoListSPA/app.js
(the configuration is in https://github.com/Azure-Samples/active-directory-dotnet-webapi-onbehalfof-ca/blob/master/TodoListSPA/appconfig.js)
Trying to implement Worldpay integration. The docs at https://online.worldpay.com/docs/take-card-details-templates mention a token. I have tested the page and I dont get any token. Wandering how i can get this token.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="payment2.aspx.cs" Inherits="payment2" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src= "https://cdn.worldpay.com/v1/worldpay.js">
</script>
<script type='text/javascript'>
window.onload = function () {
Worldpay.setClientKey('T_C_a453a70e-c5e6-4618-9c7b-96f787f0fa04');
Worldpay.reusable = false;
Worldpay.useTemplate('payment-form', 'my_payment_section', 'inline');
}
</script>
</head>
<body>
<form action="/complete" id="payment-form" method="post">
<!— all other fields you want to collect, e.g. name
and shipping address -->
<div id='my_payment_section'></div>
<div>
<input type="submit" value="Place Order" />
</div>
</form>
</body>
</html>
When the window.onload executes, it puts the WorldPay card capture form on your page. By the looks of it, you haven't disabled their Save Payment button, so are you trying to use your own submit button?? If you are trying to use your submit button, then you should add the onclick attribute to submit the worldpay template.
<input type="submit" value="Place Order" />
<form action="/complete" id="payment-form" method="post">
<div id="my_payment_section"></div>
<div>
<input id="submitCard" onclick="Worldpay.submitTemplateForm()" value="Confirm Payment" />
</div>
</form>
Once the form submits, worldpay.js takes over, and it will handle the sensitive card information, validate it and if all is ok, it will replace the cardDetails div with a single hidden input field which is the token.
If that all happens correctly, with no errors, after the token input has been placed in the DOM, the form will submit to your action "/complete", and the token will be part of the submitted values of the form.
Hope that helps.
Your script is missing the callback to generate the token in useTemplate()
See: https://developer.worldpay.com/jsonapi/docs/template-form
The callback generates the hidden input with the token value for you which posts to worldpay.
your script should be:
<script type='text/javascript'>
window.onload = function() {
Worldpay.useTemplateForm({
'clientKey':'T_C_a453a70e-c5e6-4618-9c7b-96f787f0fa04',
'form':'paymentForm',
'paymentSection':'paymentSection',
'display':'inline',
'reusable':false,
'callback': function(obj) {
if (obj && obj.token) {
var _el = document.createElement('input');
_el.value = obj.token;
_el.type = 'hidden';
_el.name = 'token';
document.getElementById('paymentForm').appendChild(_el);
document.getElementById('paymentForm').submit();
}
}
});
}
</script>
You also need the onclick="Worldpay.submitTemplateForm()" attribute on your submit too.
I'm trying example from this site. It works fine. But if i separate views,models,routers into separate file it gives me a problem. There is 3 views. WineList view, WineListItemView and winedetails view. WineList view takes collection of wine models as model and winelistItem and winedetails view takes wine as a model.
Router's code is like this
var app = app || {};
app.AppRouter = Backbone.Router.extend({
routes:{
"":"list",
"wines/:id":"wineDetails"
},
initialize:function () {
$('#header').html(new app.HeaderView().render().el);
},
list:function () {
this.wineList = new app.WineCollection();
this.wineListView = new app.WineListView({model:this.wineList});
this.wineList.fetch();
$('#sidebar').html(this.wineListView.render().el);
},
wineDetails:function (id) {
if(this.wineList == undefined)
{
this.wineList = new app.WineCollection();
this.wineListView = new app.WineListView({model:this.wineList});
this.wineList.fetch();
$('#sidebar').html(this.wineListView.render().el);
}
this.wine = this.wineList.get(id);
if (app.router.wineView) app.router.wineView.close();
this.wineView = new app.WineView({model:this.wine});
$('#content').html(this.wineView.render().el);
}
});
On page load it fetches models from server and displays list of wines in sidebar div of page. When i click on particular wine item its details will be displayed in content div of page. That all works fine. But when i reload that page which now contains details of particular,wine model of Winedetails view gives undefined .
I'm intializing the router on main page like this
app.js
var app = app || {};
$(function() {
})
app.router = new app.AppRouter();
Backbone.history.start();
index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Backbone Cellar</title>
<link rel="stylesheet" href="../css/styles.css" />
</head>
<body>
<div id="header"><span class="title">Backbone Cellar</span></div>
<div id="sidebar"></div>
<div id="content">
<h2>Welcome to Backbone Cellar</h2>
<p>
This is a sample application part of of three-part tutorial showing how to build a CRUD application with Backbone.js.
</p>
</div>
<div>
Next page
</div>
<!-- Templates -->
<script type="text/template" id="tpl-header">
<span class="title">Backbone Cellar</span>
<button class="new">New Wine</button>
</script>
<script type="text/template" id="tpl-wine-list-item">
<a href='#wines/<%= id %>'><%= name %></a>
</script>
<script type="text/template" id="tpl-wine-details">
<div class="form-left-col">
<label>Id:</label>
<input type="text" id="wineId" name="id" value="<%= id %>" disabled />
<label>Name:</label>
<input type="text" id="name" name="name" value="<%= name %>" required/>
<label>Grapes:</label>
<input type="text" id="grapes" name="grapes" value="<%= grapes %>"/>
<label>Country:</label>
<input type="text" id="country" name="country" value="<%= country %>"/>
<label>Region:</label>
<input type="text" id="region" name="region" value="<%= region %>"/>
<label>Year:</label>
<input type="text" id="year" name="year" value="<%= year %>"/>
<button class="save">Save</button>
<button class="delete">Delete</button>
</div>
<div class="form-right-col">
<img height="300" src="../pics/<%= picture %>"/>
<label>Notes:</label>
<textarea id="description" name="description"><%= description %></textarea>
</div>
</script>
<!-- JavaScript -->
<script src="js/lib/jquery.min.js"></script>
<script src="js/lib/underscore.js"></script>
<script src="js/lib/backbone.js"></script>
<script src="js/models/WineModel.js"></script>
<script src="js/collections/WineListCollection.js"></script>
<script src="js/Views/WineListView.js"></script>
<script src="js/Views/WineListItemView.js"></script>
<script src="js/Views/WineDetailsView.js"></script>
<script src="js/Views/HeaderView.js"></script>
<script src="js/routers/routers.js"></script>
<script src="js/app.js"></script>
</body>
</html>
I'm new to this backbone technology. please tell me what am i missing
this.wineList.fetch();
fires an asynchronous request to your server, which means that the content will arrive (or not) at some point after executing this line, but your application execution continues whether the response arrived or not. On page reload (assume you have wines/:id in the URL) first you have to fetch the complete list of wines before accessing any particular wine from the collection.
You have to wait until is download the collection, and access the wine with id, after this request is finished.
So after initiating the request continue your application logic in the success callback:
this.wineList.fetch({
success: function(model) {
...
this.wine = model.get(id);
...
}
});