JSON value doesn't well formed in jquery autocomplete - java

I have problem with my jquery autocomplete script.
Here is my code:
back
<?php
require_once("include/global.php");
require_once("include/con_open.php");
$q = "select name, id from tbl_hotel";
$query = mysql_query($q);
if (mysql_num_rows($query) > 0) {
$return = array();
while ($row = mysql_fetch_array($query)) {
array_push($return,array('label'=>$row["name"],'id'=>$row["id"]));
}
}
echo(json_encode($return));
front
<input type="text" id="hotel" />
<link rel="stylesheet" type="text/css" href="http://cdn0.favehotels.com/v2/style/autocomplete/jquery.ui.all.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$( "#hotel" ).autocomplete({
position: { my : "right bottom", at: "right top" },
source: "hotel-search.php",
minLength: 2,
select: function( event, ui ) {
window.location.href=ui.item.id;
}
})._renderItem = function( ul, item ) {
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").text(item.label))
.appendTo(ul);
};
});
</script>
source: "hotel-search.php" returning [{"label":"A", "id":"1"}]
when I changet the line source: "hotel-search.php" to source: [{"label":"A", "id":"1"}]
it doesn't work yet.
but when i change it to source: [{label:"A", id:"1"}] it works fine.
what should I do to make return of "hotel-search.php" to be like {label:"Hotel A", id:"1"} not {"label":"Hotel A", "id":"1"}

Naufal Abu Sudais: "it doesn't work yet" refers the autocomplete keep showing up all list. It keep showing "A", even I typed "B"
When you use autocomplete with AJAX call, a GET parameter is sent to the service, term :
hotel-search.php?term=WhatYouTypeInAutocomplete
So if you want shortest list, You must use $_GET['term'] in your PHP file to filter response items.

Try $.getJSON to let jQuery to get and parse JSON response as JSON Object :
$.getJSON('hotel-search.php', function(jsonData) {
$("#hotel" ).autocomplete({
position: { my : "right bottom", at: "right top" },
source: jsonData,
minLength: 2,
select: function( event, ui ) {
window.location.href=ui.item.id;
}
})._renderItem = function( ul, item ) {
return $("<li></li>")
.data("item.autocomplete", item)
.append($("<a></a>").text(item.label))
.appendTo(ul);
};
});

Related

docx templater use my own template (joget web)

i m tryng to use docx templater in my app joget browser. I put my template tag-example.docx in my google drive but when i change **function generate () *{loadFile("my google drive url" nothing appen. Somebody have a suggestion, how can i use my template docx ?
here the basic code :
<html>
<body>
<button onclick="generate()">Generate document</button>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/docxtemplater/3.29.0/docxtemplater.js"></script>
<script src="https://unpkg.com/pizzip#3.1.1/dist/pizzip.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.js"></script>
<script src="https://unpkg.com/pizzip#3.1.1/dist/pizzip-utils.js"></script>
<!--
Mandatory in IE 6, 7, 8 and 9.
-->
<!--[if IE]>
<script
type="text/javascript"
src="https://unpkg.com/pizzip#3.1.1/dist/pizzip-utils-ie.js"
></script>
<![endif]-->
<script>
function loadFile(url, callback) {
PizZipUtils.getBinaryContent(url, callback);
}
function generate() {
loadFile(
"https://docxtemplater.com/tag-example.docx",
function (error, content) {
if (error) {
throw error;
}
var zip = new PizZip(content);
var doc = new window.docxtemplater(zip, {
paragraphLoop: true,
linebreaks: true,
});
// Render the document (Replace {first_name} by John, {last_name} by Doe, ...)
doc.render({
first_name: "John",
last_name: "Doe",
phone: "0652455478",
description: "New Website",
});
var out = doc.getZip().generate({
type: "blob",
mimeType:
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
// compression: DEFLATE adds a compression step.
// For a 50MB output document, expect 500ms additional CPU time
compression: "DEFLATE",
});
// Output the document using Data-URI
saveAs(out, "output.docx");
}
);
}
</script>

Make a pie chart with tymeleaf highcharts spring mvc java

I want to create a pie chart with a dynamic data in highcharts
i really need your help
i wanna make a pie chart that counts the gender
here is my code
im really stuck there
..........................................................................
Controller :
#RequestMapping("/piechart")
public ResponseEntity<?> getAll(Model model) {
List<user> list = userRepository.allusers();
return new ResponseEntity<>(list,HttpStatus.OK);
}
Repository :
#Query(value=" SELECT *,count(*) AS count_gender FROM user GROUP BY gender", nativeQuery = true)
List<User> allusers();
HTML:
<body>
<div id="container" style="width: 550px; height: 400px; margin: 0 auto"></div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script th:inline="javascript">
$.ajax({
url: 'piechart',
dataType:'json',
success: function(result){
var series=[];
var data= [];
for(var i=0;i<result.length;i++){
var object={};
object.name=result[i].gender;
object.y=result[i];
data.push(object);
}
var seriesObject={
name:'percentage',
colorByPoint: true,
data: data
}
series.push(seriesObject);
drewPiechart(series);
}
})
function drewPiechart(series){
Highcharts.setOptions({
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
Highcharts.chart('container', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
},
tooltip: {
formatter: function(){
return 'y value: '+this.y+'<br/>is '+this.percentage+'% of total ('+this.total+')';
}
},
accessibility: {
point: {
valueSuffix: '%'
}
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %'
},
showInLegend: true
}
},
series: series
});
}
</script>
</body>
</html>
here is my result:
it shows nothing bcz i didnt know how to get the count result of the query on the yaxis

How do I search for a particular object within an array of JSON objects using postman

How do I query for a particular BusStopCode from within a JSON object in a JSON array
"value": [
{
"BusStopCode": "01012",
"RoadName": "Victoria St",
"Description": "Hotel Grand Pacific",
"Latitude": 1.29684825487647,
"Longitude": 103.85253591654006
},
{
"BusStopCode": "01013",
"RoadName": "Victoria St",
"Description": "St. Joseph's Ch",
"Latitude": 1.29770970610083,
"Longitude": 103.8532247463225
},
for example if I want to find only the first object then the bus stop code I would query is 01012
my current URL query request looks like this-
http://transport/dataservice/BusStops?BusStopCode=01012
here http://transport/dataservice/BusStops is my URL
and ?BusStopCode=01012 is my path
tl;dr: You can't unless they implemenet it on the server side.
Postman is only the client side.
When you are sending a URL - the server reads it and have an implementation for this specific url / url + parameters in our case.
If the server have an implementation for something like http://transport/dataservice/BusStops?BusStopCode=01012 They should expose it to you. You can't guess what is their API.
You can filter your response data using JSONpath Visualizer in Postman.
To enable the Visualizer, please paste the following code in the Test section of Postman where you are creating your request.
let template = `
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jsonpath#1.0.2/jsonpath.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.4.1/dist/jquery.min.js"></script>
</head>
<body>
<div>
<div>
<input id="filter" style="width:450px;" type="text" placeholder="Example query: $..name.first">
</div>
<div>
<button id="resetButton" style="background-color:red;color:white;">Reset</button>
<input id="showErrors" type="checkbox" value="1"/>
<span class="item-text" style="font-family:courier;">Show Evaluation Errors</span>
</div>
<div id="errors" style="font-family:courier;color:red;display:none;"></div>
<div>
<p id="content" style="font-family:courier;color:green;font-size:18px;"></p>
</div>
</div>
</body>
</html>
<script>
pm.getData( (error, value) => {
const extractedData = jsonpath.query(value, '$');
$(function() {
$('#filter').keyup(function() {
try {
let filteredData = jsonpath.query(extractedData, $(this).val());
$("#content, #errors").empty();
$("#content").append("<pre><code>" + JSON.stringify(filteredData, null, 4) + "</code></pre>");
} catch (err) {
console.info(err);
$("#errors").empty();
$("#errors").append("<pre><code>" + err + "</code></pre>");
}
});
});
$( "#resetButton" ).click(function() {
$("#content, #errors").empty();
$("#filter").val('');
$("#content").append("<pre><code>" + JSON.stringify(extractedData, null, 4) + "</code></pre>");
})
})
$(function() {
$("#showErrors").on("click",function() {
$("#errors").toggle(this.checked);
});
});
</script>`
pm.visualizer.set(template, pm.response.json())
Here is the example.
Sample data is also provided for better understanding.

Code inserting into database twice

I have the form
<aui:form action="<%= editURL %>" method="POST" name="fm">
<aui:fieldset>
<aui:input name="name" />
<aui:input name="url" />
<aui:input name="address" />
</aui:fieldset>
<aui:button-row>
<aui:button type="submit" />
<aui:button name="cancel" value="Cancel"/>
</aui:button-row>
</aui:form>
and this piece of javascript code which is inserting into database twice I don't know why.
<aui:script use="aui-base,aui-form-validator,aui-io-request">
AUI().use('aui-base','aui-form-validator',function(A){
var rules = {
<portlet:namespace/>name: {
required: true
},
<portlet:namespace/>url: {
url: true
},
<portlet:namespace/>address: {
required: true
},
};
var fieldStrings = {
<portlet:namespace/>name: {
required: 'The Name field is required.'
},
<portlet:namespace/>address: {
required: 'The Address field is required.'
},
};
alert("validator");
new A.FormValidator({
boundingBox: '#<portlet:namespace/>fm',
fieldStrings: fieldStrings,
rules: rules,
showAllMessages:true,
on: {
validateField: function(event) {
},
validField: function(event) {
},
errorField: function(event) {
},
submitError: function(event) {
alert("submitError");
event.preventDefault(); //prevent form submit
},
submit: function(event) {
alert("Submit");
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
alert("inside success");// not getting this alert.
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
}
}
});
});
</aui:script>
However if I add the following piece of code, which is redundant because it is already present inside the submit block of above code and is not triggered any way because I do not have any save button in the form, then the value is inserted only once.
<aui:script use="aui-base,aui-io-request">
A.one('#<portlet:namespace/>save').on('click', function(event) {
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
});
</aui:script>
This code generates Uncaught TypeError: Cannot read property 'on' of null which I think is because there is no save button in the form. But adding this code, the value is inserted into database just once which is what I want but the logic is flawed. How can I get the results I want by just by using the first piece of code?
The insertion was happening twice. Once from the default form submit and other from the A.io.request. Adding this piece of code
<aui:script use="aui-base,aui-io-request">
A.one('#<portlet:namespace/>save').on('click', function(event) {
var A = AUI();
var url = '<%=editURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().refreshPortlet();
Liferay.Util.getOpener().closePopup('popupId');
}
}
}
);
});
</aui:script>
resulted in the insertion only once. This code has obviously no relevance because there is no save button in the form. Hence there was Uncaught TypeError: Cannot read property 'on' of null which masked the flaw and prevented the form from being submitted twice.
Removing the above piece of code and preventing the default submit (by adding onSubmit="event.preventDefault(); in the form tag) resolves the issue.

How to print google-annotated-chart by clicking on print button, just like normal print as save it as a pdf programatically?

How to print Google annotated chart by clicking on print button in a web page?
In my code, I used window.print() method, but when I print the page, chart disappears from the webpage and rest of the content is printing.
Please help me.
<!DOCTYPE html> <html> <head>
<title>Google Chart with jsp Mysql Json</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"><!--
css for datepicker -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script><!--
Javascript for datepicker -->
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]}); $(document).ready(function(){
showGoogleChart('2013-12-01','2013-12-31');
//============================= Onpage load calling chart function
$( "#from" ).datepicker({ changeMonth: true,
dateFormat:'yy-mm-dd', numberOfMonths: 3, onClose: function(
selectedDate ) { $( "#to" ).datepicker( "option", "minDate",
selectedDate ); } }); $( "#to" ).datepicker({
dateFormat:'yy-mm-dd', changeMonth: true, numberOfMonths: 3,
onClose: function( selectedDate ) { $( "#from" ).datepicker(
"option", "maxDate", selectedDate ); } }); });
//==================== OnChange date call google chart
================== function getChartdate(){ alert("hi"); var startdate = $('#from').val(); var enddate = $('#to').val();
showGoogleChart(startdate,enddate); //===========On button click
calling chart function========= }
function showGoogleChart(startdate,enddate){
var queryObject="";
var queryObjectLen="";
var postdata = {"startDate":startdate,"endDate":enddate};
$.ajax({
type : 'POST',
url : 'testPages.jsp',
data:postdata,
dataType:'json',
success : function(data) {
queryObject = eval('(' + JSON.stringify(data) + ')');
queryObjectLen = queryObject.empdetails.length;
google.setOnLoadCallback(drawChart(queryObject,queryObjectLen));
},
error : function(xhr, type) {
alert('server error occoured')
}
});
}
function drawChart(queryObject,queryObjectLen) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'date');
data.addColumn('number', 'temp');
for(var i=0;i<queryObjectLen;i++)
{
var name = queryObject.empdetails[i].date;
var empid = queryObject.empdetails[i].temp;
data.addRows([
[name,parseInt(empid)]
]);
}
var options = {
title: 'Employee Information',
}; var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options); }
</script>
</head>
<body>
<div style="margin: 50px;">
<label for="from">From</label> <input type="text" id="from" name="from"> <label for="to">to</label> <input type="text"
id="to" name="to"> <input type="button" id="changeChart"
onclick="getChartdate();" value="Change Chart"/>
</div>
<div id="chart_div"></div>
</body>
</html>
The method window print() will simply open the print dialog. How the page is formatted for print depends on how the browser formats webpages and the print stylesheet if present.
Assuming the chart is some kind of image (or canvas), it might be that the browser choses to strip images when printing. Especially if the image is added using css background-image: url(...) because it assumes a background image (like background-color) is just for decoration and would waste ink if printed.
A plain img tag should print though in most cases unless some css is removing it for print...

Categories