Why is this html not working - javascript

I have this short piece of code:
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<script type="text/javascript">
$("#term").autocomplete({
source: function(request, response) {
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
dataType: 'JSONP',
data: {
format: 'json',
q: 'select * from xml where url="http://google.com/complete/search?output=toolbar&q=' + encodeURIComponent(request.term) + '"'
},
success: function(data) {
response($.map(data.query.results.toplevel.CompleteSuggestion, function(item) {
return { label: item.suggestion.data, value: item.suggestion.data };
}));
}
});
}
});
</script>
</head>
<body>
<label for="term">Search term: </label>
<input id="term" />
</body>
</html>
It is working good online at JsBin: JsBin preview
However when I copy code to desktop so I can work with it it doesn't work (it used to work however) What am I doing wrong?? Why is this not working except online??

try wrapping the javascript code inside the ready handler, jsbin does it automatically
$(document).ready(function(){
//your code here
});
or the short cut
$(function(){
//your code here
});
this wil execute the script once the DOM has finished loading, or as an alternative you can place the javascript at the end of the document so it is executed when the DOM has loaded

You are referring to the input element before it has been created. Perform your autocompletion initialization after the DOM elements have been set up.
...
<script type="text/javascript">
$(function() {
$("#term").autocomplete({
source: function(request, response) {
$.ajax({
url: 'http://query.yahooapis.com/v1/public/yql',
dataType: 'JSONP',
data: {
format: 'json',
q: 'select * from xml where url="http://google.com/complete/search?output=toolbar&q=' + encodeURIComponent(request.term) + '"'
},
success: function(data) {
response($.map(data.query.results.toplevel.CompleteSuggestion, function(item) {
return {
label: item.suggestion.data,
value: item.suggestion.data
};
}));
}
});
}
});
});
</script>
...

Related

JS changes cursor only when js function is completed

I have the following code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body style="background-color:yellow;width:100%;height:100%;">
test
<script>
function test() {
$("body").css("cursor","wait"); //cursor must be changed here
$.ajax(...);
}
</script>
</body>
</html>
The problem with this code is that cursor changes from default to wait in browser only when function test() is completed, but I need it to change in certain point of function. I tried in FF 58 on Ubuntu 14 and in Opera in Windows 7. I've read many posts about it and tried also this solution
$(document).ajaxStart(function() {
$(document.body).css({'cursor' : 'wait'});
}).ajaxStop(function() {
//$(document.body).css({'cursor' : 'default'});
});
but without success. How to fix it? Any ideas?
I found the answer. I had in my ajax async:false -
$.ajax({ ...
async: false,
...
});
When I changed to
$.ajax({ ...
async: true,
...
});
everything started to work as expected.
$(document).ajaxStart(function (event, jqxhr, settings) {
$(document.body).css({ 'cursor': 'wait' });
});
$(document).ajaxComplete(function (event, jqxhr, settings) {
$(document.body).css({ 'cursor': 'normal' });
});
$(document).ajaxError(function (event, request, settings) {
$(document.body).css({ 'cursor': 'normal' });
});
function AjaxCall() {
$.ajax({
type: "POST",
url: '/home/AjaxURL',
contentType: "application/json; charset=utf-8",
global: true,// this makes sure ajax set up ajaxStart/ajaxComplete/ajaxerror will triggered
dataType: "json",
success: function () { },
error: function () { }
});
}
$(document).ready(function () {
AjaxCall();
});
Note- Setting the cursor to document.body as you did means it will only apply in document and did not apply in other dom elements like anchor, textbox etc
You can use before send like this:
$.ajax({
beforeSend: function(){
// Handle the beforeSend event
},
complete: function(){
// Handle the complete event
}
// ......`enter code here`
});
OR use when and timeout:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function ajaxready() {
setTimeout(function() {
$.ajax({
url: "https://www.w3schools.com/jquery/demo_test.txt",
beforesend: function() {},
success: function(result) {
$("#div1").html(result);
$("body").css("cursor", "");
}
});
}, 500);
}
function loading() {
$("body").css("cursor", "wait"); //cursor must be changed here
}
$(document).ready(function() {
$("button").click(function() {
$.when(loading()).done(function() {
ajaxready();
});
});
});
</script>
<style>
button {
cursor: inherit
}
</style>
</head>
<body>
<div id="div1">
<h2>Let jQuery AJAX Change This Text</h2>
</div>
<span></span>
<button>Get External Content</button>
</body>
</html>

How to have autocomplete search using a large JSON file as data source?

I am trying to build an autocomplete search bar, using a JSON large file containing millions of rows as source.
To have better performance, it is not desired to have Ajax requests to a PHP script making %like% requests to a Database.
I started playing around with JQuery to achieve it but I can't get the JSON function to work.
What are some ways to improve the code below to get better performance when dealing with a large json file?
Thank you very much!
Here is the HTML:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Custom Search</title>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/redmond/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.js"></script>
<script type="text/javascript" src="app.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<input />
</body>
</html>
Here is the javascript, not working properly:
$(function() {
$.widget("custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var that = this,
currentCategory = "";
$.each(items, function(index, item) {
if (item.name != currentCategory) {
ul.append("<li class='ui-autocomplete-name'>" + item.name + "</li>");
currentCategory = item.name;
}
that._renderItemData(ul, item);
});
}
});
$("input").catcomplete({
delay: 0,
source: function(request, response) {
$.ajax({
url: "data.json",
dataType: "json",
data: {
term: request.term
},
success: function(data) {
var cat_data = $.map(data, function(item) {
return {
name: item.name
};
});
$("#searchfield").catcomplete({
delay: 0,
source: cat_data,
minlength: 0
});
}
});
},
minlength: 0
});
});
Here is the JSON data:
[{
"unit":12345,
"name":"Car Batteries",
"type":"HardGood",
"price":0.50,
"category":[
{"id":"1","name":"Automobile"},
{"id":"2","name":"Batteries"}]}
{
"unit":2345,
"name":"Soap",
"type":"Hygiene",
"price":1.00,
"category":[
{"id":"3","name":"Hygiene"},
{"id":"4","name":"Bathroom"}]}
{
"unit":56573,
"name":"Camera",
"type":"Photography",
"price":700.50,
"category":[
{"id":"6","name":"Photography"},
{"id":"7","name":"Gadgets"}]}
{
"unit":94893,
"name":"iPhone Cable",
"type":"Cables",
"price":0.50,
"category":[
{"id":"19","name":"Cables"},
{"id":"20","name":"Mobile"}]}]

How can I display the data from the JSON on my webpage?

I am writing a script that sends an ajax request. The Cloud seems to response with the JSON, but how can I display the data from the JSON on my webpage?
Here the link for the pretty printed JSON.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<script>
function myFunctionPost() {
jQuery.ajax( {
url: 'https://iotmmss0018275632trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/app.svc/T_IOT_77877E443B666B7FED2F?$format=json',
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
success: function( response ) {
console.log(response);
},
error : function(error) {
console.log(error);
}
} );
}
</script>
</body>
</html>
To achieve this you can use JSON.stringify() space argument. You will also need to wrap the output with <pre> </pre> will preserve the line spacing.
function myFunctionPost() {
$.ajax( {
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'GET',
success: function(response) {
$('#pp').html('<pre>' + JSON.stringify(response, undefined, 4) + '</pre>');
},
error: function(error) {
console.log(error);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<p id="pp"></p>
</body>
</html>
Source: Does jQuery have a JSON/javascript object to HTML pretty print function similar to PHP's var_dump?
By var responseObject = json.parse(response) to make a javascript object.
And then do as you would with JS object?
Hard to tell exact code without knowing what do you wanna display, in what HTML.

Calling React JS from jsp

I am new to React, and I'm making a webpage to show a list of items.
I have this React Code in a file called admins.js:
//more code
var AdminsBox = React.createClass({
getInitialState: function() {
return {adminsList: []};
},
setAdminsArray: function(data) {
this.setState({adminsList: data});
},
render: function() {
return (
<div>
<AdminsContentBox adminsList={this.state.adminsList}/>
</div>
);
}});
var AdminsBoxRender = ReactDOM.render(
<AdminsBox />,
document.getElementById('adminsContent')
);
And in the file index.jsp:
<html lang="es">
<head>
<link rel="stylesheet" href="base.css" />
<script src="react.js"></script>
<script src="react-dom.js"></script>
<script src="browser.js" charset="utf-8"></script>
<script src="jquery.min.js"></script>
<script src="marked.min.js"></script>
<link rel="stylesheet" href="fonts.css">
<link rel="stylesheet" href="material.indigo-blue.min.css">
<script type="text/babel" src="admins.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url: 'myUrlServlet',
type: 'POST',
data: "function=getAdmins",
dataType: "json",
success: function(data){
AdminsBoxRender.setAdminsArray(data);
}
});
});
</script>
</head>
<body>
<div id="adminsContent"></div>
</body>
The error I get is AdminsBoxRender is not defined.
What am I doing wrong?
Thank you in advance.
That's not the proper way to fetch data for your component, you should fetch it in componentDidMount()
var AdminsBox = React.createClass({
getInitialState: function() {
return {adminsList: []};
},
componentDidMount: function(){
$.ajax({
url: 'myUrlServlet',
type: 'POST',
data: "function=getAdmins",
dataType: "json",
success: function(data){
this.setState({adminsList: data});
}
});
},
setAdminsArray: function(data) {
this.setState({adminsList: data});
},
render: function() {
return (
<div>
<AdminsContentBox adminsList={this.state.adminsList}/>
</div>
);
}});
window.AdminsBoxRender = ReactDOM.render(
<AdminsBox />,
document.getElementById('adminsContent')
);
You should keep the stuff related to React "inside" React.
Your approach would fall under the heading of "fighting the framework".
I would recommend going with QoP's first recommendation rather than attaching the component to the window object.

Object [object Object] has no method 'select2'

Here I have included scripts:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type='text/javascript' src='//netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js'></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link href="http://ivaynberg.github.com/select2/select2-3.3.2/select2.css" rel="stylesheet" type="text/css" />
<script src="http://ivaynberg.github.com/select2/select2-3.3.2/select2.js"></script>
HTML:
<input type="hidden" id="parcele" />
and jquery code on the bottom of page:
<script>
function formatValues(data) {
return data.ime_prezime;
}
$('#parcele').select2({
ajax: {
dataType: "json",
url: "json.php",
results: function (data) {
return {results: data};
}
},
width: "300px",
formatResult: formatValues,
formatSelection: formatValues,
multiple: true
});
</script>
but I get error: Uncaught TypeError: Object [object Object] has no method 'select2'
What is wrong here? I dont get it...
You need to wait until jQuery and select2.js have loaded:
function formatValues(data) {
return data.ime_prezime;
}
$(document).ready(function() { // add this
$('#parcele').select2({
ajax: {
dataType: "json",
url: "json.php",
results: function (data) {
return {results: data};
}
},
width: "300px",
formatResult: formatValues,
formatSelection: formatValues,
multiple: true
});
}); // add this
EDIT: I found your problems:
You don't have any elements with id "parcele" on your actual page at http://agroagro.com/template/tema/zadaci.html# - I think you are thinking of the elements with id "parcela" (notice the "a" instead of an "e").
You actually have two elements with the id "parcela", but HTML ids have to be unique.
To fix this: Rename one of the elements with the id "parcela", then use one of them where you have "parcele" in your existing JavaScript.
Also, just to verify that everything works if you fix the naming problems, I created this jsFiddle, which works correctly.

Categories

Resources