Retrive number from database and pass it on as a search parameter - database

When someone search for a particular CITY in my real estate website, I need to retrieve the matching cityID from a .csv database and pass the retrieved cityID to my vendor website as one of the search parameters, like http;//www.vendor.com?cityID=9999
The list of cityID and the cityName is in a file called myproperty.csv
Below are the current html codes that i have now.
<form action="vendor.com" method="get" target="_blank">
<label>Please enter city name:-</label>
<input type="text" id="cityName" name="cityName">
<!-- Please help me to add some codes here -->
<input type="submit" value="Submit">
</form>
Can someone please help me with the codes to achieve the objective above?
I have searched high and low for answers, still nothing works. Please help. Thanks in advance for all your help
Hafiz

I assume you run your site on a PHP enabled web server, don't you? In that case here's one solution for you, which uses PHP to read the csv file line by line and create an html dropdown for the user to select the city by name.
Also, if you don't have PHP running on your server it is possible to do the same using JavaScript, if you need that rather than PHP let me know.
That's probably the most simple solution, you can get further by implementing a javascript autocomplete function if you want to use a text input rather than a list of cities in a dropdown.
<form action="vendor.com" method="get" target="_blank">
Please select city:
<?php
// Set filename to read from
$csvFile = 'dummy.csv';
// Open file handle
$fp = fopen($csvFile, "r");
// In case the file don't exist, exit
if (!is_resource($fp)){
die("Cannot open $csvFile");
}
?>
<select name="city">
<?php //Let's read the csvfile line by line: ?>
<?php while($line = fgetcsv($fp)): ?>
<?php // Assuming that the csvfile's structure is the following: city_id,city_name, we create the dropdown options: ?>
<option value="<?php echo $line[0];?>"><?php echo $line[1]?></option>
<?php endwhile; ?>
</select>
<input type="submit" value="Submit">
</form>
And now here's the JavaScript solution (the code uses the JQUERY framework so you'll have to include it in your html tag:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
You'll also need a hidden form input to contain the matched city id, so here's the extended html markup for your form:
<form action="vendor.com" method="get" target="_blank" id="myForm">
Please enter city name:-
<input type="hidden" id="cityId" name="cityId">
<input type="text" id="cityName" name="cityName">
<input type="submit" value="Submit">
</form>
And your JavaScript to do the job:
<script>
$(function(){
//Ajax call to get csv file contents
$.ajax({
type: "GET",
url: "dummy.csv",
dataType: "text",
success: function(data) {process_csv(data);}
});
//Event handler for form submission
$('#myForm').submit(function(){
//Let's get the value of the text input (city name)
var city_name = $('#cityName').val().toLowerCase();
//If the city name exists in our map, let's set the matched city id to the hidden input field called cityId
if (city_ids[city_name] > 0)
{
$('#cityId').val(city_ids[city_name]);
return true;
}
//Otherwise we can't find the city id in our database, so we can't post the form either...
alert('No such city name in database!');
return false;
});
});
//global variable to contain map of city names and id's
var city_ids = {};
//Function to parse csv file and set city map
function process_csv(text) {
var lines = text.split(/\r\n|\n/);
for (var i=0; i<lines.length; i++) {
var data = lines[i].split(',');
city_ids[data[1].toLowerCase()] = data[0];
}
}
</script>

Related

How to get results in form of tables with column titles in wordpress?

<form action="" method="post" name="myForm">
Filter <input id="isbn" type="text" name="isbn" />
<input type="submit" name="submit" value="Submit" /> </form>
<?php
if(isset($_POST['submit']))
{
global $wpdb;
$table_name = "isbn"; // change this to your table name
$field = $_POST['isbn']; // change this to your isbn field $_POST['ISBN'];
$retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name where isbn = '".$field."'");
foreach ($retrieve_data as $retrieved_data) {
echo $retrieved_data->Title;
echo $retrieved_data->Image; // for image
echo $retrieved_data->Isbn;
}
}
// I have this php code for accessing data from my database table. but the result is not coming in desired form. i am sending some screenshots which are describing my situations.
This image contain my database table structure and record containing title, image and isbn column.
This is the output which i am getting after applying above query and image is also not displaying in browser.
This type of output i want in my browswer after someone enter isbn number of book in search form.
Can someone please provide me code for this?
Try adding ARRAY_A in the get_results method argument like below.
$retrieve_data = $wpdb->get_results( "SELECT * FROM $table_name where isbn = '".$field."'", ARRAY_A);
and then for displaying image try
foreach ($retrieve_data as $retrieved_data) {
echo $retrieved_data['Title'];
echo '<img src="data:image/jpeg;base64,'.base64_encode( $retrieved_data['Image'] ).'"/>'; // for image
echo $retrieved_data['Isbn'];
}

Angular: get file length from file input

I have input like this: <input id="file" name="someFile" type="file" ng-model="userInfo.someFile" /> . How can I get file length in js code using Angular?
Something like this don't work:
var fileLen = $('#file').files[0].length;
if (fileLen == 0) {
//some code
}
What exactly do you mean by file length? I am assuming you are asking the number of files selected? If not let me know and I can update the answer. But the below will show you how to get access to the $event object which has the file(s) properties.
html:
<div>
<input ng-change="add_files($event)" type="file" multiple>
</div>
in your controller:
$scope.add_files = function($event){
//this will give you the $event object details
//from that object you should be able to determine file name(s) / size(s)
//I believe this will give you the file size
console.log($event.files[0].size)
}

cannot get input value of Struts 2 file selector with Angular

I am using Angular and I want to get access to the file input field's file name attributes and display it in another input box.
This is the file upload field:
<div class="btn btn-orange btn-file col-sm-3" >
<s:text name="expedientes.btn.seleccionar.fichero" />
<s:file name="form.filesUpload" multiple="multiple" ng-model="filesUploadModel" id="filesUploadId"/>
</div>
And the input box to show file name:
<input type="text" class="form-control"
id="fileNameId" name="fileName"
ng-model="fileNameModel" ng-disabled="true"
ng-init="" ng-bind="fileNameModel = filesUploadModel">
But the ng-bind is not working.
I also tried to define $watch for the file input field like this:
$scope.$watch(function() {
$scope.files = angular.element(document.querySelector('#filesUploadId'));
return files;
},
function(newValue, oldValue) {
$("#fileNameId").val(files.files[0].name);
});
to watch if the <input type="file" id="filesUploadId"> has changed, select this element and return it as files, and let the element with id fileNameId's value equals to files.files[0].name, because the file upload input has an attribute named files with all the files I upload, and their file names files[i].name.
But FF tells me files is undefined and no avail. It's not working.
Am I doing something wrong here? Please help and thanks!!
Edit: I am using this and no error, but no result either:
if (!angular.equals(document.getElementById("filesUploadId"), null)) {
$scope.$watch(function() {
var myFiles = document.getElementById("filesUploadId");
return myFiles;
},
function(newValue, oldValue) {
$( "#fileNameId" ).val(function(){
var result = null;
$(myFiles).each(function(){
result = name + this.attr(files).attr(name);
});
return result;
});
});
}
I solved it with pure JavaScript, enlighted by another question here:
AngularJs: How to check for changes in file input fields?
Actually, I find it impossible to use onchange() when the function I want to call is wrapped in angular module, except in the way in above answer:
onchange="angular.element(this).scope().setFileName()"
And in my script I only use pure JavaScript, except for the definition of the function:
angular.module('es.redfinanciera.app').controller('PanelMandarCorreoCtrl', function ($scope, $modalInstance) {
....(other functions)
$scope.setFileName = function() {
var result = "";
var adjuntos = document.getElementById("filesUploadId").files;
for (i = 0; i < adjuntos.length; i++){
result = result + adjuntos[i].name + "\r\n";
};
document.getElementById("fileNameId").value = result;
}
}
$scope.btnClean = function() {
document.getElementById("filesUploadId").value = "";
document.getElementById("fileNameId").value = "";
};
And in my jsp page, finally I have my file upload button and a clean button like this:
<div class="btn btn-orange btn-file col-sm-3" >
<s:text name="expedientes.btn.seleccionar.fichero" />
<s:file name="correoForm.filesUpload" id="filesUploadId" multiple="multiple" ng-model="filesUploadModel"
onchange="angular.element(this).scope().setFileName()"/>
</div>
<div class="col-sm-2">
<button class="btn btn-default btn-normal" type="button" ng-click="btnClean()">
<s:text name="expedientes.btn.quitar.fichero" />
</button>
</div>
I have a <textarea> to display all the file names:
<textarea class="form-control" ng-model="fileNameModel"
name="fileName" id="fileNameId"
ng-disabled="true"></textarea>
EDIT:
Clear button is not working in IE8 because it is not permitted in IE8 to set "" value to a file input field. My guess is, I can remove this file input field and copy a new one, with same style but no file is selected. But I have found a good question who has amounts of answers here:
clearing-input-type-file-using-jquery
Also, I heard that in IE8 onchange() event will not be triggered if you only select a file, you must add this.blur() after selecting a file. Regarding this issue, IE is following strictly the spec, but FF is not. But in my case, the event is actually triggered. Maybe because I am testing under IE 11 using Developing Tools' emulator for IE8.

Grouping results in ui-bootstrap typeahead [duplicate]

I am implementing typeahead using AngularUI-Bootstrap. I need to show the results grouped based on some values coming from the database. Here's a sample scenario
There are some users in the database, each user has a "Department". One user name can be available in multiple departments.
The end-user types in the names to search users from the database and retrieves the list in the typeahead list. Since one user name can belong to multiple departments, the requirement is to show the user names grouped by different departments. Something like this:
Then the user can select the desired user name and proceed.
As per the Typeahead documentation present here, I don't see any option to cater to my requirement.
I have tried the this workaround: Whenever the typeahead array is getting formed, I appended the user department to the array element:
$scope.fetchUsers = function(val) {
console.log("Entered fetchUsers function");
return $http.get("http://localhost:8080/TestWeb/users", {
params : {
username : val
}
}).then(function(res) {
console.log("Response:",res);
var users = [];
angular.forEach(res.data, function(item) {
users.push(item.UserName + " - " + item.UserDepartment);
});
console.log("users=",users);
return users;
});
};
This way, at least the end user sees the department. But when I select the record, the selected value is the full content of the array element. Below is sample screenshot to elaborate:
HTML
Users from local service
<pre>Model: {{userList | json}}</pre>
<input type="text" ng-model="userList" placeholder="Users loaded from local database"
typeahead="username for username in fetchUsers($viewValue)"
typeahead-loading="loadingUsers" class="form-control">
<i ng-show="loadingUsers" class="glyphicon glyphicon-refresh"></i>
User types in the string
User selects one record
I want to avoid the department (in this case, string - Desc 4 ) when user selects a record.
Is there any way I can achieve this grouping without any workaround? Or is there any way I can enhance my workaround?
I used to have a similar requirement and here is how I did it that time.
Example Plunker: http://plnkr.co/edit/zujdouvB4bz7tFX8HaNu?p=preview
The trick is to set the typeahead-template-url to a custom item template:
<input type="text" class="form-control" placeholder="Users loaded from local database"
ng-model="selectedUser"
typeahead="user as user.name for user in getUsers($viewValue)"
typeahead-template-url="typeahead-item.html" />
The item template, this represent each item in a dropdown:
<div class="typeahead-group-header" ng-if="match.model.firstInGroup">Desc {{match.model.group}}</div>
<a>
<span ng-bind-html="match.label | typeaheadHighlight:query"></span>
</a>
As you can see, there is an ng-if to show a group header if that item has a property firstInGroup set to true.
The firstInGroup properties are populated like this using lodashjs:
$scope.getUsers = function (search) {
var filtered = filterFilter(users, search);
var results = _(filtered)
.groupBy('group')
.map(function (g) {
g[0].firstInGroup = true; // the first item in each group
return g;
})
.flatten()
.value();
return results;
}
Hope this fit to your requirement too.
please see here http://plnkr.co/edit/DmoEWzAUHGEXuHILLPBp?p=preview
instead of creating new objects here:
angular.forEach(res.data, function(item) {
users.push(item.UserName + " - " + item.UserDepartment);
});
use create template :
<script type="text/ng-template" id="customTemplate.html">
<a> {{ match.model.name}} - department : {{match.model.dept}}</a>
</script>
and use it in your Typeahead directive
<input type="text" ng-model="selected"
typeahead="user.name as user for user in users | filter:$viewValue | limitTo:8" class="form-control"
typeahead-template-url="customTemplate.html">

ng repeat not updating

Hi I am a newbie to angular js and I am hoping someone can help me out with the following problem.
I have a numeric field called numAdults and I need to show a set of field (such as name, address, telephone etc ) numAdult times to get those information for each of those person.
Here is the jsfiddle for the problem jsfiddle link
Here is also an overview of code of the controller
function bookingController($scope){
$scope.numAdults = 1;
$scope.personLoop = function(){
console.log('personLoop called')
return new Array($scope.numAdults);
//return new Array(2);
}
the html
<label for="book_num_adults">Number of adults:</label>
<input id="book_num_adults" type="text" ng-model="numAdults">
<div class="row" ng-repeat="t in personLoop()" style="border:2px solid red;margin-top:10px">
<h4>Person {{$index+1}}</h4>
<input placeholder="name"><br>
<input placeholder="address"><br>
<input placeholder="telephone"><br>
</div>
Can you also help me with how to transform this as an module ( not just a controller based )
Thank you in advance!
Your Fiddle was riddled with errors...
http://jsfiddle.net/bRgTR/5/
Under Frameworks & Extensions, you need to change the 2nd dropdown from "onLoad" to one of the "No wrap" options
Your controller definition is mangled. It's supposed to be: .controller('name', ['depname', function (depname) { })]); -- you had your closing array misplaced.
You should really use semi-colons.
You don't create an array of 5 items in JavaScript like this: var a = new Array(5), that creates an array that contains a 5. Instead, you should do var a = []; a.length = 5;

Resources