I am unable to save and get data when I put any data and click button nothing happen and not saving data.
Just want to save 2 value
APIkey
enabled or not a checkbox
and save them
My main.js for options
function saveSettings(e) {
chrome.storage.sync.set({
apiKey: apiKey.value,
isEnabled: isEnabled.checked
});
}
function restoreSettings(e) {
chrome.storage.sync.get("apiKey").then(
function(result) {
alert('working');
apiKey.value = result.apiKey || "";
},
function(error) {
console.log(error);
}
);
chrome.storage.sync.get("isEnabled").then(
function(result) {
isEnabled.checked = result.isEnabled
},
function(error) {
console.log(error);
}
);
}
//restoreSettings();
//saveButton.addEventListener("click", saveSettings);
document.addEventListener('DOMContentLoaded', restoreSettings);
document.getElementById('saveButton').addEventListener('click',
saveSettings);
And my html
<!DOCTYPE html>
<html>
<head>
<title>Plugin Options</title>
</head>
<body>
<img src="/icons/img1.png">
<div>
<form style="background-color:#000a1a">
<h3>Change Settings</h3>
<label>API Key : <input type="text" id="apiKey" /></label><br />
<label>Enabled : <input type="checkbox" id="isEnabled" /></label><br />
<input type="button" value="Save Settings" id="saveButton" class="button" />
</form>
</div>
<script src="main.js"></script>
</body>
</html>
I tried chrome.storage.local as well thanks for helping
First make sure you have set the right permissions in your manifest:
"permissions": [
"storage"
]
then to get a value:
chrome.storage.sync.get('myvalue', function(res){
})
where res.myvalue will be the content you are looking for.
To set a value do:
chrome.storage.sync.set({'myvalue': true})
Related
I need to update the comment status, i.e. the name of the "approve" field. To this end, I created the AJAX script also the backend seems correct because it receives a message after clicking the button. I don't know why I can't save the "approve" value to the database. Please help. I use NodeJS, MongoDB, Express, and EJS for frontend.
My database:
My frontend:
<% post.comments.forEach(function (comment) { %>
<tr>
<td> <%= comment._id %> </td>
<td> <%= comment.username %> </td>
<td> <%= comment.comment %> </td>
<form method="post" onsubmit="return doApprove(this);">
<input type="hidden" name="post_id" value="<%= post._id %>" />
<input type="hidden" id="comment_id" name="comment_id">
<td> <input class="approve-comment" type="checkbox" name="approve" value="true">
<button class="btn btn-info" value="Approve"/>
</td>
</form>
<% }) %>
</tr>
</table>
</div>
<script>
function doApprove(form) {
var formData= {approve:form.approve.value};
$.ajax({
url: "/do-edit-comment",
method: "POST",
data: formData,
success: function (response) {
formData._id =response._id;
alert(response.text);
}
});
return false;
}
</script>
My backend:
app.post("/do-edit-comment", function (req,res) {
blog.collection("posts").updateOne({
"_id": ObjectId(req.body.id),
"comments._id": ObjectId(req.body.id)
},{
$set: {
"comments": {approve: req.body.approve}
}
}, function (error,document) {
res.send({
text: "comment approved"
});
});
});
To update a single element from an array, what you need is the $[<identifer>] array update operator. For the scenario described in your question, the update query in the server should be something like this:
blog.collection("posts").updateOne(
{ "_id": ObjectId(req.body.post_id), },
{ $set: { "comments.$[comment].approve": req.body.approve } },
{ arrayFilters: [{ "comment._id": ObjectId(req.body.commentId) }] },
function (error, document) {
res.send({
text: "comment approved"
});
}
)
EDIT(Front-end issues/fix)
So I figured there are some issues with the front end code too. This edit attempts to explain/fix those issues.
Issues:
1. The backend expects a commentId in the request object(req.body.commentId) to be able to identify the comment to update but you are not sending that from the front end.
2. The backend needs the id of the post to uniquely identify the post to update, but you are not sending that from the front end.
3. The approve value in the form data sent from the front-end is a string and it would always be "true". This is not what you want, you want to send a boolean value(true or false) depending on if the checkbox is checked or not.
Fix:
Update the form template to this:
<form method="post" onsubmit="return doApprove(event);">
<input type="hidden" name="post_id" value="<%= post._id %>" />
<input type="hidden" id="<%= comment._id %>" name="comment_id" />
<td> <input class="approve-comment" type="checkbox" name="approve" value="true">
<button class="btn btn-info" value="Approve"/>
</td>
</form>
Changes:
- The doApprove handler attached to the submit event of the form is now called with event instead of this.
- I updated the value of the id attribute for the input#name="comment_id" element to the actual comment._id value.
And in the script tag, update the doApprove function to this:
function doApprove(event) {
event.preventDefault();
const form = event.target;
var formData = {
approve: form.approve.checked, // form.approve.checked would be true if the checkbox is checked and false if it isn't
post_id: form.post_id.value, // The value of the input#name=post_id element
commentId: form.comment_id.id, // The id attribute of the input#name=comment_id element
};
$.ajax({
url: "/do-edit-comment",
method: "POST",
data: formData,
success: function (response) {
formData._id =response._id;
alert(response.text);
}
});
return false;
}
I hope that helps.
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)
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>