Elasticsearch search data with angularjs - html

i want to search on the 'Index' and 'Type' that is input from the user through a html form. I'm new to both angular and Elasticsearch.
i tried using this code and binding the variables through ng-model
ExampleApp.controller('MatchController', function ($scope, client, esFactory) {
function click($scope){
$scope.index = '';
$scope.type = '';
$scope.key = '';
client.search({
index: $scope.index ,
type: $scope.type ,
size: 50,
body: {
"query":
{
"match": {
name: $scope.key
}
},
}
html code...
<input type="text" ng-model="index" id="index" /> <br><br>
<input type="text" ng-model="type" id="type" /><br><br>
<input type="text" ng-model="key" id="key" /><br><br>
<input type="button" value="search" onclick="click()">
Is it possible to do this??? if so how??
many thanks.

You need to create a service to connect and query elasticsearch using your functions.
https://www.sitepoint.com/building-recipe-search-site-angular-elasticsearch/
The above link shows you how to create and run queries via elasticsearch and AngularJS. The service that I mentioned is written in the last block of code. I suggest you read the whole article though to give you a better understanding.
You're mostly on the right track except your whole client.search part needs to go into a service which you call, otherwise whenever the controller is called that will be called too which you don't want happening.

Related

How do you add a value to datepicker from an Angular Factory?

i have an Angular Factory that gets a single date from the backend of my spring application, and i wanted to add it to an Input so the calendar input is always set with the date obtained from the backend, without the possibility for the user to change it. How could i achieve this? Should i put it on my controller or directly on the button? This is my code:
Factory(concatenated with other .factory):
.factory('DataInizioGeneraCalendario', function ($resource) {
return $resource('rest/anagrafica/dataInizioGeneraCalendario', {
get: {
method: 'GET'
}
});
Controller Function:
$scope.generaCalendario = function () {
$scope.modificaCalendarioDiv = true;
$scope.successMessage = false;
$("#idModificaCalendarioDiv").hide();
$scope.element = new Calendario();
autoScroll('generaCalendario');
$("#idErrorTemplate").hide();
$('#data').attr('disabled', false);
$("#idGeneraCalendarioDiv").show();
};
Input :
<div class="col-xs-12 col-md-2" >
<label for="dataInizio" class="row col-xs-12 control-label" style="text-align: left">da Data</label>
<input class="datepicker form-control" placeholder="gg/mm/aaaa" required type="text" id="data" ng-disabled="true" />
</div>
Edit : forgot to add, the controller function is called by the button that displays the input for the calendar.
Because your factory's GET request will return the date value asynchronously, it's better to have a $scope.date in your controller that will hold the date value that is returned from the server. Also, depending on the format in which you store dates on the backend, you might need to transform the value that is returned from the backend into the string format, so it would be properly consumed by the <input type="date"> as per Angular docs.
In your code, you need to bind the input element to this value, like this: <input ng-model="date">.
What it will do is bind this input to the data model, so that every time when user edits the input the $scope.date would be updated too.
If you do not want users to be able to edit this date, then you need to:
Keep the input field disabled <input disabled> (no need to use ng-disabled here, because you want to keep it always disabled). And also remove this line: $('#data').attr('disabled', false); in your function.
You the one-way binding, instead of two0way binding, like this: <input disabled ng-value="date">
Here is the working DEMO that shows two inputs: one that is editable and another that is not.

How to generate URL with form for vue-router?

I am trying to create search bar(form), but I need it to have pretty URL but I am using Vue-router so my app.js looks like this
let Search = Vue.component('search', require('./components/Search.vue'));
const routes = [
{ path: '/protocols/:param', component: Search },
]
now functionally when I type /protocols/test I get my desired results, but I am not sure how to create a form so when I type something to redirect me to that route /protocols/:param since my page is vue component
<form action="/protocols/?what goes here?">
<input type="text" placeholder="Search..." class="" name="" id="search">
</form>
since all tutorials are made for search on the same page, but I need to dedicate one for results
You can use v-model to assign the input value to your data and use a computed property to generate the URL action like this:
<form :action="urlAction">
<input type="text" placeholder="Search..." class="" name="" id="search" v-model='search'>
</form>
Now use data and computed props to build the dynamic URL
data () {
return {
search: ''
}
},
computed: {
urlAction () {
return "/protocols/" + this.search
}
}

How I use the data from Angular on Node JS? And how can I make a page load the information about a certain "data"?

I'm working on a project that I need from login, to compare the information at the form with the database. And later, after doing the validation, I need to load the information of a login in another page (I have no idea how).
(I tried to find some tutorials, but all of them use Express, that I'm not allowed to)
Now my code:
HTML (I think this part is OK, cause I could save the information in $scope.u)
<form ng-controller = "login" ng-submit="submit(user)">
<label>Login:</label>
<input type="text" ng-model="user.login" required>
<label>Senha:</label>
<input type="password" ng-model="user.pwd" required>
<label><input type="checkbox"> Lembre-me</label>
<button type="submit" class="btn btn-default">Login</button>
<p>{{user.login}}</p>
<p>{{user.pwd}}</p>
<p>LOGIN:{{user.login}}</p>
<p>SENHA:{{user.pwd}}</p>
</form>
Angular (I'm not sure if I understood the idea of $http.post, so I don't know if I can send the info of $scope.u to Nodejs)
app.controller('login',function($scope,$http){
$scope.u = {};
$scope.submit = function(user) {
$scope.u = angular.copy(user);
console.log($scope.u);
};
$http.post('/servico/login', $scope.u).success(function(data, status) {
console.log('Data posted successfully');
});
});
Node (If I could use the information of $scope.u, my problem would be finished there, but I don't know how I can load the information in another page)
The button Login should compare the values from the form and them, maybe, use to send to the other page.
function login(request,response){
var queryString = 'SELECT uLogin,uSenha FROM usuarios';
connection.query(queryString,function(err,rows){
});
}
I hope I've been clear with my doubt.
Thanks for your help.

Strange scope when trying to clear input text via AngularJS

I'm having trouble with what I though would be a rather pedestrian use case. Given the following form
<form class="form-inline" role="form">
<div class="form-group">
<input type="text" ng-model="customerInput" size="80" class="form-control" placeholder="Type the company name here"/>
<button class="btn btn-primary" ng-click="addCustomer(customerInput)">Add</button>
</div>
</form>
I simply want to clear the input field after adding the customer.
$scope.addCustomer = function(customer) {
$scope.customers.push({name: customer});
$scope.customerInput = '';
}
It doesn't work, so I inspected the $scope. The customerInput value I'm looking for lives in the $scope.$$childHead. This works.
$scope.addCustomer = function(customer) {
$scope.customers.push({name: customer});
$scope.$$childHead.customerInput = '';
}
I'm clearly doing something wrong. Can someone shed some light?
Angular $scopes often do things that you don't expect because of the inheritance chain. For this reason, it's useful to define a Plain Old JavaScript var and reference that within the scope:
angular.module('myApp').controller(function ($scope) {
var model = {
customerInput: ''
};
$scope.model = model;
});
And then in your template: <input ng-model="model.customerInput" />. Now you can operate on the model var in functions of that $scope, and be confident that only your chosen $scope is operating on that model. Of course, as you get more familiar with $scope inheritance patterns, you'll often want the implicit sharing between Controllers. And of course, in such a case, you could also store the data on a service.

Create a basic MailChimp signup form using their API

I'm new to MailChimp and need some help.
With their basic newsletter signup form... you simply embed some prepackaged HTML into your page. However the problem with this is that clicking on submit redirects to a MailChimp page. (I don't want to redirect to MailChimp, I want the user to stay on own website after hitting submit.)
They provide an API and plenty of documentation but just about zero useful examples. The API is supposed to allow me to do a full integration with my site or application. It seems that when I read something in their docs that applies to me, I click the link to get more information and I end up going around in circles. They tell you how to do it but they fail to "show" you how to it.
I can get an API Key, they have tons of documentation, and a whole bunch of wrappers & plugins... PHP, Drupal, Wordpress, etc...
The confusion here regarding their pre-packaged solutions is that I just have a regular static HTML page, it's not Wordpress, PHP, or Drupal... so I just don't know where to start ... I don't even know if I'm supposed to use POST or GET.
I'm not a newbie to API's... I do very well with getting the Google Maps API to do whatever I want. However, Google provides real-world working examples in addition to their detailed documentation which is how I learned it. I just want to see it in action before I can grasp the finer points of the API.
Without any solid examples or tutorials in their online documentation, I'm asking how to create the most basic HTML signup form using their API.
EDITED:
Since posting this answer MailChimp has released version 2 & 3 of their API. Version 3 will be the only supported version starting in 2017. As soon as I have a chance to test it, I will update this answer for API version 3.
MailChimp API v3.0
As per notification at the top of this page, all prior versions of the API will not be supported after 2016.
My solution uses PHP in the background for handling the API, and jQuery to facilitate the Ajax.
1) Download a PHP wrapper that supports API v3.0. As of this writing, there is nothing official listed in the latest MailChimp docs that supports v3.0, but several are listed on GitHub, so I selected this one.
2) Create the following PHP file, store-address.php, using your own API key and list ID, and then place it in the same directory as the wrapper from step one. Remember to follow the documentation for your wrapper, but they all seem fairly similar to this.
<?php // for MailChimp API v3.0
include('MailChimp.php'); // path to API wrapper downloaded from GitHub
use \DrewM\MailChimp\MailChimp;
function storeAddress() {
$key = "xxxxxxxxxxxxxxx-us1";
$list_id = "xxxxxx";
$merge_vars = array(
'FNAME' => $_POST['fname'],
'LNAME' => $_POST['lname']
);
$mc = new MailChimp($key);
// add the email to your list
$result = $mc->post('/lists/'.$list_id.'/members', array(
'email_address' => $_POST['email'],
'merge_fields' => $merge_vars,
'status' => 'pending' // double opt-in
// 'status' => 'subscribed' // single opt-in
)
);
return json_encode($result);
}
// If being called via ajax, run the function, else fail
if ($_POST['ajax']) {
echo storeAddress(); // send the response back through Ajax
} else {
echo 'Method not allowed - please ensure JavaScript is enabled in this browser';
}
3) Create your HTML/CSS/JavaScript(jQuery) form (It is not required to be on a PHP page, and the visitor will never see that PHP is being used in the background.)
The response is in JSON so you'll have to handle it correctly.
Here is what my index.html file looks like:
<form id="signup" action="index.html" method="get">
First Name: <input type="text" name="fname" id="fname" />
Last Name: <input type="text" name="lname" id="lname" />
email Address (required): <input type="email" name="email" id="email" />
<input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#signup').submit(function() {
$("#message").html("Adding your email address...");
$.ajax({
url: 'inc/store-address.php', // proper url to your "store-address.php" file
type: 'POST', // <- IMPORTANT
data: $('#signup').serialize() + '&ajax=true',
success: function(msg) {
var message = $.parseJSON(msg),
result = '';
if (message.status === 'pending') { // success
result = 'Success! Please click the confirmation link that will be emailed to you shortly.';
} else { // error
result = 'Error: ' + message.detail;
}
$('#message').html(result); // display the message
}
});
return false;
});
});
</script>
MailChimp API version 1:
(original answer)
After fumbling around for a while, I found a site using the PHP example with jQuery. From that I was able to create a simple HTML page with jQuery containing the basic sign-up form. The PHP files are "hidden" in the background where the user never sees them yet the jQuery can still access & use.
1) Download the PHP 5 jQuery example here... (EDIT: links are dead. However, the only important part is the official API wrapper for PHP which is available HERE.)
http://apidocs.mailchimp.com/downloads/mcapi-simple-subscribe-jquery.zip
If you only have PHP 4, simply download version 1.2 of the MCAPI and replace the corresponding MCAPI.class.php file above.
http://apidocs.mailchimp.com/downloads/mailchimp-api-class-1-2.zip
2) Follow the directions in the Readme file by adding your API key and List ID to the store-address.php file at the proper locations.
3) You may also want to gather your users' name and/or other information. You have to add an array to the store-address.php file using the corresponding Merge Variables.
Here is what my store-address.php file looks like where I also gather the first name, last name, and email type:
<?php
function storeAddress() {
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('123456789-us2');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "123456a";
if ($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype'])) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a confirmation link.';
} else {
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']) {
echo storeAddress();
}
4) Create your HTML/CSS/jQuery form. It is not required to be on a PHP page.
Here is what my index.html file looks like:
<form id="signup" action="index.html" method="get">
First Name: <input type="text" name="fname" id="fname" />
Last Name: <input type="text" name="lname" id="lname" />
email Address (required): <input type="email" name="email" id="email" />
HTML: <input type="radio" name="emailtype" value="html" checked="checked" />
Text: <input type="radio" name="emailtype" value="text" />
<input type="submit" id="SendButton" name="submit" value="Submit" />
</form>
<div id="message"></div>
<script src="jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#signup').submit(function() {
$("#message").html("Adding your email address...");
$.ajax({
url: 'inc/store-address.php', // proper url to your "store-address.php" file
data: $('#signup').serialize() + '&ajax=true',
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
Required pieces...
index.html constructed as above or similar. With jQuery, the appearance and options are endless.
store-address.php file downloaded as part of PHP examples on Mailchimp site and modified with your API KEY and LIST ID. You need to add your other optional fields to the array.
MCAPI.class.php file downloaded from Mailchimp site (version 1.3 for PHP 5 or version 1.2 for PHP 4). Place it in the same directory as your store-address.php or you must update the url path within store-address.php so it can find it.
Here is an example using version 2.0 of Mailchimp API together with mailchimp-api (a minimal php abstraction class for dealing with the Mailchimp API).
<?php
include('MailChimp.php');
$MailChimp = new MailChimp('API_KEY');
$result = $MailChimp->call('lists/subscribe', array(
'id' => 'LIST_ID',
'email' => array( 'email' => $_POST['email'] ),
'merge_vars' => array(
'MERGE2' => $_POST['name'] // MERGE name from list settings
// there MERGE fields must be set if required in list settings
),
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false
));
if( $result === false ) {
// response wasn't even json
}
else if( isset($result->status) && $result->status == 'error' ) {
// Error info: $result->status, $result->code, $result->name, $result->error
}
?>
Read more about what you can send with the API call at the MailChimp API Documentation.
Here's another example of using version 2.0 of the Mailchimp API using the Official PHP Wrapper.
The difference between my example and others posted here is that I'm using the subscribe method of the Mailchimp_Lists class, accessible through instantiation of the Mailchimp class (->lists), rather than the generic call method.
$api_key = "MAILCHIMP_API_KEY";
$list_id = "MAILCHIMP_LIST_ID";
require('Mailchimp.php');
$Mailchimp = new Mailchimp($api_key);
$subscriber = $Mailchimp->lists->subscribe($list_id, array('email' => $_POST['email']));
if ( ! empty($subscriber['leid'])) {
// Success
}