how to view the data when searching without submitting | angularjs - javascript

in order to make the search process faster, my client requested to view the data when just the search box is filled without even submitting, my code works fine at submitting, what should i change with my code so i can get the desired result. this is my first project with angular js, i am very new to this technology. Many thanks in advance.
HTML View:
<input id="searchInput" type="text"/> // search box where
// the function below "getSearchResults()" will get results when submitting
<input ng-click="getSearchResults()" type="submit"/>
<table>
<thead>
<tr>
<th>NOM</th>
<th>TELEPHONE</th>
<th>LOCATION</th>
<th>CODE</th>
</tr>
</thead>
<tbody >
//view the data
<tr ng-repeat="c in clients">
<td>{{c.firstname}} {{c.lastname}}</td>
<td>{{c.telephone}}</td>
<td>{{c.location}}</td>
<td>{{c.code}}</td>
</tr>
</tbody>
</table>
Js source:
var app = angular.module('DMDGroup', []);
$scope.clients;
app.controller('ClientALL', function($scope, $http) {
/* the function put all results in the scope variable (client) in a json
form and the results viewed with the ng-repeat on the tr tag*/
$scope.getSearchResults=function(){
var searchKeyWord=$("#searchInput").val();
var url = '../php/clients.php';
var data = {"function":"getClients",
"searchKeyWord":searchKeyWord};
var options={
type : "get",
url : url,
data: data,
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
$scope.clients = response;
$scope.$apply();
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
}
i want the to directly change the data in the table depends on the search results, i'll attach an image of my view

put ng-change instead of ng-click
<input ng-change="getSearchResults(searchVal)" ng-model="searchVal" class="searchClientBtn" type="submit"/>
in controller function
$scope.getSearchResults=function(value){
var url = '../php/clients.php';
var data = {"function":"getClients",
"searchKeyWord": value};
var options={
type : "get",
url : url,
data: data,
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
$scope.clients = response;
$scope.$apply();
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}

Related

How to submit dynamic data without form?

I am getting data as form of Java Bean and I am inserting each value into a table.
Values are retrieved as common way at first.
But I added some Javascript source, so that I can modify the value if I click any area near it.
Now I would like to save the data in database as well if there was any change after I modify.
How can I do that?
Here is my HTML code
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-editable>${engboardVO.word}</td>
<td data-editable>${engboardVO.dialogue}</td>
<td data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
And Javascript
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
/* var $input = $('<input style="width:500px; height:100px"/>').val( $el.text() ); */
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.replaceWith($input);
var save = function() {
var $td = $("<td data-editable />").text($input.val());
$input.replaceWith($td);
};
$($input).blur(function() {
save();
})
});
You can use ajax for submitting data without form.
I can see you are using jQuery library. So I am writing code based on this library.
In HTML:
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-name="word" data-editable>${engboardVO.word}</td>
<td data-name="dialogue" data-editable>${engboardVO.dialogue}</td>
<td data-name="practice" data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
In javascript:
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.html($input);
var field_name = $el.attr('data-name');
var save = function() {
var $val= $input.val();
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
};
$($input).blur(function() {
save();
})
});
Then in server side, you can save fieldvalue as value of fieldname in your database.
Basically what we are doing here is:
Added an attribute data-name in td tag, its value can be related to your field name in table.
Get the name of attribute in javascript using var field_name = $el.attr('data-name');.
Using post request in ajax call passed the field_name and and value of this field to server.
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
Now in server side, you need to fetch this data as you fetch normally for post request in submit of a form and save this data in database.
url is same as action you provide in form tag.
Edit:
Check now. You were replacing the td, whereas you had to replace html inside td.
Don't worry if you don't have a form or can't have it for some reasons
You can still read the inputs of your web page and use them or send them to the server.
See below a simple example:
var inputs = document.getElementsByTagName('input');
var data = []
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
data.push(inputs[index].value)
}
var json = JSON2.stringify(data);
$.ajax({
type: "POST",
url: "your-api-url",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// done code
}
});

How to empty ajax data before sending it?

I have a form, when I submit it it creates an ajax function and then creates a table out of the data in the success. But knowing that my page is dynamic (without reloading the page I call the ajax function many times), but each time the data in the success doesn't get removed before generating more data. Is that normal? How can I empty the success data variable before sending the ajax?
Function :
function submitForm() {
if ($.fn.DataTable.isDataTable("#table")) {
$('#table').DataTable().clear();
$('#table').DataTable().destroy();
$('#table').empty();
}
url = $("#form").serialize();
console.log(url);
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: '/api/test?'+url,
'beforeSend': function (request) {
data = {}; // like this maybe?
},
success: function (data) {
//Getting data variable containing
data = data.data;
//the second time I call the function, data contains the new and old stuff at the same time
}
});
}
Form :
<form method="GET" action="" class="form-horizontal" id="form" onsubmit="return false;">
<button type="submit" onclick="submitForm();">Update table</button>
</form>
Table :
<table class="table table-striped display nowrap col-md-12" id="achats_table">
<thead>
<tr style="border-bottom:2px dashed #ccc"></tr>
</thead>
<tbody></tbody>
<tfoot align="right">
<tr></tr>
</tfoot>
</table>
You have to empty the table in beforeSend,
function submitForm() {
url = $("#form").serialize();
console.log(url);
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: '/api/test?'+url,
'beforeSend': function (request) {
if ($.fn.DataTable.isDataTable("#achats_table")) {
$('#table').DataTable().clear();
$('#table').DataTable().destroy();
$('#table').empty();
}
},
success: function (data) {
//Getting data variable containing
data = data.data;
//the second time I call the function, data contains the new and old stuff at the same time
}
});
}

Displaying the contents of ng-controller after calling AJAX with the "as" function

What I'm trying to show the contents of ng-repeat after calling AJAX (i.e. $http)
<table ng-controller="TableController as tc">
<tr>
<th>Date</th>
<!-- other headers are here -->
</tr>
<tr ng-repeat="order in tc.orders" >
<td ng-bind="order.id"></td> //It doesn't appear
<td>#{{ order.id }}</td> //It doesn't appear as well. I use Laravel, so I need to put #
</tr>
</table>
Here is the relevant script part
angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var instance = this;
this.orders = [];
$http({
method : "POST",
url : "/admin/getOrders"
}).then(function (response) {
this.orders = response.data;
console.log("Inside; "+this.orders.length);
});
});
From console.log("Inside; "+this.orders.length), I can see that the expected data was assigned to this.orders array. However, as the title of this post suggests, the array is not displayed with ng-repeat="order in tc.orders".
I followed this question, but following this did not solve this issue. Now I suspect that the cause lies in the as statement, which I have to use for this occasion.
As I don't see many information resources about the as online, I'd appreciate if you'd give any advice.
you should use your instance inside promise resolved function
to assign to the right instance (controller instance) :
angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var instance = this;
instance.orders = [];
$http({
method : "POST",
url : "/admin/getOrders"
}).then(function (response) {
instance.orders = response.data;
console.log("Inside; "+ instance.orders.length);
});
});
its usual to name this instance : vm refers to View Model
Example:
angular.module('adminAngular', ['ui.bootstrap','dialogs.main'])
.controller('TableController', function(dialogs, $http){
var vm= this;
vm.orders = [];
$http({
method : "POST",
url : "/admin/getOrders"
}).then(function (response) {
vm.orders = response.data;
console.log("Inside; "+vm.orders.length);
});
});

Issue in populating ajax data into table via ng-repeat

I am trying to populate a table on receiving JSON data on an Ajax get from Mongo DB.
I am able to see the received data in alert. But my table is not populated.
I am clicking the retrive button to get the data.
JS code:
$scope.retrive = function()
{
$scope.people =[];
$.ajax({
url : "https://api.mongolab.com/api/1/databases/geolocation/collections/boom?apiKey=veTqID_gkb74tG-yL4MGcS1p2RRBP1Pf",
type : "GET",
dataType: "json",
success: function(data) {
$scope.people = JSON.stringify(data);
alert($scope.people);
//alert("status = "+data.status+"descripttion"+data.description);
//console.log(data);
//document.getElementById("n1").innerHTML = data[0].name;
//alert(JSON.stringify(data));
tableCreate(data);
//alert(data[0].name);
//var json = JSON.parse(data);
//alert(json.name);
}
});
};
}]);
HTML code:
<div>
<table>
<tr>
<th>ITEM</th>
<th>DESCRIPTION</th>
<th>QUANTITY</th>
<th>LOCATION</th>
<th>CATEGORY</th>
</tr>
<tr ng-repeat="person in people">
<td>{{person.Item}}</td>
<td>{{person.Description}}</td>
<td>{{person.Quantity}}</td>
<td>{{person.Location}}</td>
<td>{{person.Category}}</td>
</tr>
</table>
</div>
Here is the Plunker Link :
http://plnkr.co/edit/OKzTApbW7ii8R0EMrOyx?p=preview
Try is like this:
Note (Just a tip ): Putting API keys within stack overflow questions is not a good idea. Keep the API key private as any body can use your key and you could blocked out from the service due to unauthorised usage.
var myApp = angular.module('myApp', []);
myApp.controller('projectController', function($scope, $http){
$scope.userDetails = [];
$scope.test = function(){
console.log("getting user projects, please wait ......");
// Simple GET request example (passing data) :
$http.get("https://api.mongolab.com/api/1/databases/geolocation/collections/boom?apiKey=YOUR-API-KEY", {
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("");
$scope.userDetails = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
});
Heres a working Plunker:
http://plnkr.co/edit/xoFuBa695E7O1g6gTcm4?p=preview
UPDATED Plunker
http://plnkr.co/edit/7E4PKbnqBDwsVptIaJ1Q?p=preview

ng-repeat not reflecting when the source variable gets modified

I have the following angularJs code. When my source data changes, my ng-repeat does not update my view. I looked at other posts and added $scope.$apply(); , $scope.$digest(); at the end of my ajax success callback, but it did not help. The idea is that the page will have an empty table in the begining and after the ajax call onReady() it will populate the rows with data. Could someone point me at what I am missing here or a better way to achieve the same
JS:
(function() {
var app = angular.module("jmeter-module", []);
app.controller('JmeterTableController', ['$scope', function($scope){
$scope.data = [];
$(document).ready(function(){
var url = "jmeterTableData.html";
fetchTableData(url, 10, 25);
});
function fetchTableData(url, minAge, maxAge){
$.ajax({
type: "GET",
url: url,
data: { minAge : minAge,
maxAge : maxAge },
datatype: "json",
success: function(data){
/*If I try to print data here, I see the values rightly getting returned*/
$scope.data = data;
},
error: function(e){
console.log(e);
}
});
}
}]);
})();
JSP:
<div id="buildGroupsParentDivId" ng-controller="JmeterTableController as row">
.
.
.
<tbody id="jmeter-table-content" >
<tr ng-repeat="val in row.data">
<td><img title="History" src="/images/history.png" width="20" height="20"></td>
<td><input type="checkbox" value="save"></td>
<td>{{val.firstName}}</td>
<td>{{val.lastResult}}</td>
</tr>
</tbody>
the problem is with the execution of $.ajax outside of the scope of Angular's digest cycle. You could get this working with $scope.$apply, but since you're already using Angular it's better to use the AngularJS xhr helper methods:
https://docs.angularjs.org/api/ng/service/$http
// Simple GET request example :
$http.get('/someUrl').
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Categories