Retrieve results from SOLR using jquery calls - javascript

I am working to get response from SOLR using jquery. When I use the below code I got the error saying Typeerror:data is null
When looked at the code in firebug, data in on_data function is null. I think I am missing something in the Solr URL.The URL I am using is http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q=%3A&version=2.2&start=0&rows=10&indent=on&wt=json.
Can you please take a look at my code, and also suggest me the URL style in the code
<html>
<head>
<title>Solr Search</title>
</head>
<body>
<h3>Solr Search</h3>
Query: <input id="query" />
<button id="search">Search</button>
<hr/>
<div id="results">
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function on_data(data) {
$('#results').empty();
var docs = data.response.docs;
$.each(docs, function(i, item) {
$('#results').prepend($('<div>' + item.name + '</div>'));
});
var total = 'Found ' + docs.length + ' results';
$('#results').prepend('<div>' + total + '</div>');
}
function on_search() {
var query = $('#query').val();
if (query.length == 0) {
return;
}
var url='http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q='+query+'&version=2.2&start=0&rows=50&indent=on&wt=json';
$.getJSON(url, on_data);
}
function on_ready() {
$('#search').click(on_search);
/* Hook enter to search */
$('body').keypress(function(e) {
if (e.keyCode == '13') {
on_search();
}
});
}
$(document).ready(on_ready);
</script>

Here is the working version of your code, and list of changes:
1) added wrf: adds a wrapper-function around the JSON response, useful in AJAX with dynamic script tags for specifying a JavaScript callback function
2) added callback: need to use JSONP instead of an ordinary JSON request, due to JavaScript’s cross-domain security restrictions.
<html>
<head>
<title>Solr Search</title>
</head>
<body>
<h3>Solr Search</h3>
Query: <input id="query" />
<button id="search">Search</button>
<hr/>
<div id="results">
</div>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function on_data(data) {
$('#results').empty();
var docs = data.response.docs;
$.each(docs, function(i, item) {
$('#results').prepend($('<div>' + item.name + '</div>'));
});
var total = 'Found ' + docs.length + ' results';
$('#results').prepend('<div>' + total + '</div>');
}
function on_search() {
var query = $('#query').val();
if (query.length == 0) {
return;
}
var url='http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q='+query+'&version=2.2&start=0&rows=50&indent=on&wt=json&callback=?&json.wrf=on_data';
$.getJSON(url);
}
function on_ready() {
$('#search').click(on_search);
/* Hook enter to search */
$('body').keypress(function(e) {
if (e.keyCode == '13') {
on_search();
}
});
}
$(document).ready(on_ready);
</script>

Since you are using $.getJSON, you might need to add &wt=json to your query.
So your query should be: http://xxxx.xxx.xxxx.xxx/xxx_xxx/core0/selectcore0/select/?q=search_query&version=2.2&start=0&rows=10&indent=on&wt=json
By default Solr gives XML response. You need to specify if you need JSON response by adding &wt=json
Mode detail: http://wiki.apache.org/solr/SolJSON

I have installed solr 5.2.1: item.name in the function on_data is not provided anymore. I used item.id and it worked.

Related

Calling Rest API from Javascript File: Data Return Issue

Hi i have created a javascript file where i make a call to rest api and get data.
I want to return the data to the calling function from html page but the way the call works, i am not been able to.
HTML:
<html>
<head>
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js" />
<script src="jquery-G5API-1.0.0.js" />
<script type="text/javascript">
function JSFile() {
var result = GetStatus(123456);
alert('HTML: '+ result);
}
</script>
</head>
<body>
<input id="Button1" type="button" value="JSFile" onclick="JSFile()" />
</body>
</html>
query-G5API-1.0.0.js:
function GetStatus(token) {
var url = 'some/url';
var result = '';
$.getJSON(url,function(data)
{
//alert(JSON.stringify(data));
})
.always(function(xhr, status) {
alert( "finished: " + JSON.stringify(xhr));
result = JSON.stringify(xhr);
});
alert('Returning result: ' + result);
return result;
}
The sequence in which alerts are being called:
Returning result: empty_string
HTML: empty_string
Finished: json_data
Any suggestions on how to return json data from .js file to calling function in html file will be highly appreciated.
You'll need to resolve the promise to get your expected result. Check out the
jQuery deferred object api and observe the (simplified) following...
function GetG5Status3(token) {
return $.getJSON('some/url')
}
function JSFile() {
GetG5Status(123456).done(function(response) {
console.log(response);
});
}
JSFiddle Link - simplified demo
Also, I am not seeing any usage of token

How do I fill tournament brackets with team names, then make the team names uneditable?

I'm working on a tournament bracketing system, and I found a library called "JQuery bracket" which can help a lot. But there are some problems:
I was planning to retrieve team names (and possibly match scores) from a PostgreSQL database and put them on the brackets. However, the data must be in JSON, and the parser is in Javascript. I can't seem to figure out a workaround.
Original code:
<html>
<head>
<title>jQuery Bracket editor</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.json-2.2.min.js"></script>
<script type="text/javascript" src="jquery.bracket.min.js"></script>
<link rel="stylesheet" type="text/css" href="jquery.bracket.min.css" />
<style type="text/css">
.empty {
background-color: #FCC;
}
.invalid {
background-color: #FC6;
}
</style>
<script type="text/javascript">
function newFields() {
return 'Bracket name [a-z0-9_] <input type="text" id="bracketId" class="empty" /><input type="submit" value="Create" disabled />'
}
function newBracket() {
$('#editor').empty().bracket({
save: function(data){
$('pre').text(jQuery.toJSON(data))
}
})
$('#fields').html(newFields())
}
function refreshSelect(pick) {
var select = $('#bracketSelect').empty()
$('<option value="">New bracket</option>').appendTo(select)
$.getJSON('rest.php?op=list', function(data) {
$.each(data, function(i, e) {
select.append('<option value="'+e+'">'+e+'</option>')
})
}).success(function() {
if (pick) {
select.find(':selected').removeAttr('seleceted')
select.find('option[value="'+pick+'"]').attr('selected','selected')
select.change()
}
})
}
function hash() {
var bracket = null
var parts = window.location.href.replace(/#!([a-z0-9_]+)$/gi, function(m, match) {
bracket = match
});
return bracket;
}
$(document).ready(newBracket)
$(document).ready(function() {
newBracket()
$('input#bracketId').live('keyup', function() {
var input = $(this)
var submit = $('input[value="Create"]')
if (input.val().length === 0) {
input.removeClass('invalid')
input.addClass('empty')
submit.attr('disabled', 'disabled')
}
else if (input.val().match(/[^0-9a-z_]+/)) {
input.addClass('invalid')
submit.attr('disabled', 'disabled')
}
else {
input.removeClass('empty invalid')
submit.removeAttr('disabled')
}
})
$('input[value="Create"]').live('click', function() {
$(this).attr('disabled', 'disabled')
var input = $('input#bracketId')
var bracketId = input.val()
if (bracketId.match(/[^0-9a-z_]+/))
return
var data = $('#editor').bracket('data')
var json = jQuery.toJSON(data)
$.getJSON('rest.php?op=set&id='+bracketId+'&data='+json)
.success(function() {
refreshSelect(bracketId)
})
})
refreshSelect(hash())
$('#bracketSelect').change(function() {
var value = $(this).val()
location.hash = '#!'+value
if (!value) {
newBracket()
return
}
$('#fields').empty()
$.getJSON('rest.php?op=get&id='+value, function(data) {
$('#editor').empty().bracket({
init: data,
save: function(data){
var json = jQuery.toJSON(data)
$('pre').text(jQuery.toJSON(data))
$.getJSON('rest.php?op=set&id='+value+'&data='+json)
}
})
}).error(function() { })
})
})
</script>
</head>
<body>
Pick bracket: <select id="bracketSelect"></select>
<div id="main">
<h1>jQuery Bracket editor</h1>
<div id="editor"></div>
<div style="clear: both;" id="fields"></div>
<pre></pre>
</div>
</body>
</html>
After the data is retrieved, upon display, you are going to want to add disabled to the html input element. For instance:
<input type="text" id="bracketId" class="empty" disabled>
This will render your text field uneditable.
If you are looking to do this as people are filling out their brackets, I would suggest you either add a <button> after each bracket or fire a jquery event with the mouseout() listener that adds the disabled attribute to your input fields.

removing contents on jquery

Hello im a little bit new on doing javascript and jquery please kinda help me on my problem. i would really appreciate it. Thank you!
On page 7-8 how can I remove the "disabled" on the "new game" button
Using jquery?
Here's the index.html:
<!DOCTYPE>
<html>
<head>
<link href="assets/css/blackjack.css" type="text/css" media="screen" rel="stylesheet">
<script src="assets/js/Modernizr.js"></script>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/Mustache.js"></script>
<script src="assets/js/blackjack.js"></script>
</head>
<body>
<div class="wrapper">
<img src="assets/images/rocket-u-logo-large.png">
<h1>Blackjack</h1>
<p>Hi, thanks for stopping by our blackjack table. Pull up a chair and let's play...</p>
<div id="card-table">
<h2>Dealer</h2>
<div id="dealer-hand"></div>
<div id="status"></div>
<div id="player-hand"></div>
<h2>Player</h2>
<div id="player-options">
<button class="bj" id="new-game" disabled>New Game</button>
<button class="bj" id="hit">Hit</button>
<button class="bj" id="stand">Stand</button>
</div>
</div>
</div>
</body>
</html>
and Here's the js:
$('#bj').click(function () {
$('#hit').show();
$('#stand').show();
});
function initGame() {
var initErrors = [];
var errorMessage;
// Test if browser supports local storage
if (Modernizr.localstorage) {
// console.log("Local storage is supported.");
} else {
var errorStatus = "Local storage is not available"
// console.log(errorStatus);
initErrors.push(errorStatus);
}
// Test if browser supports mustache.js
var mustacheScript = $('script[src*="js/Mustache.js"]').length;
if (mustacheScript != 0) {
// console.log("Mustache loaded!");
} else {
var errorStatus2 = "Mustache not loaded."
// console.log(errorStatus2);
initErrors.push(errorStatus2);
}
function displayErrorMessage() {
// Test if initErrors array has any errors
if (initErrors.length != 0) {
if (errorStatus2 === undefined) {
errorStatus2 = "";
} else if (errorStatus === undefined) {
errorStatus = "";
}
var errorMessage = "Houston, we have a problem (" + errorStatus + ', ' + errorStatus2 + ").";
// console.log(errorMessage);
$('#status').append("<p>" + errorMessage + "</p>");
} else {
var successMessage = "Ready to play? Click 'New Game' to start...";
$('#status').append("<p>" + successMessage + "</p>");
// console.log(successMessage);
}
}
displayErrorMessage();
//Test 'boolean' return values
if (initErrors.length != 0) {
return false;
$('#new_game').attr("disabled", "disabled");
} else {
return true;
$('#new_game').removeAttr("disabled");
}
}
console.log(initGame());
$(document).ready(function () {
initGame();
});
You wrote the code yourself. but it was below return statement which will make it in accesible.
bring the return statement below
$('#new_game').removeAttr("disabled");
It should work.
You can try this:
$('#new_game').prop('disabled',false);
You can use anyone of listed below
$('#new_game').attr("disabled", false);
OR
$("#new_game").removeAttr("disabled");
OR
$("#new_game").prop("disabled",false);
$('#new-game').removeAttr('disabled');
Looks like your JS code has an error: in HTML <button class="bj" id="new-game", but in JS $('#new_game').removeAttr("disabled");. You use underscore instead of '-' in id.

How Do You Run the ENTIRE Javascript Page From An Button In HTML?

I have been trying to make all my Javascript Page code from JSBin to work automatically upon the clicking of a button. Problems include not being able to run the code because it says I have multiple variables in my script that do not work together and not being able to put it all in HTML because console.log doesn't work. I tried a couple different ideas, but sadly, I am unable to do it correctly.
My Code Is:
var name = prompt('So what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
var name = prompt('Than what is your name?');
var confirmNamed = confirm('So your name is ' + UCFL(name) + '?');
}
if (confirmNamed === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmNamed === false) {
var name = prompt('Than what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
alert('Oh, guess what? I do not even fucking care what your name is anymore. Lets just
start..');
var start = confirm('Are you ready?');
}
}
if (start === true) {
var x = console.log(Math.floor(Math.random() * 5));
if (x === 1) {
alert('You are an dwarf in a time of great disease.');
alert('');
}
}
And this is what I want you to fix:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="" />
</form>
</body>
</html>
I've created an entry on JSBin suggesting many improvements to what you have now:
http://jsbin.com/epurul/3/edit
Visit the entry to test the code yourself. Here is the content, for convenience:
HTML:
<body>
<button onclick="playGame()">Play Game</button>
</body>
And JavaScript:
// Expose playGame as a top-level function so that it can be accessed in the
// onclick handler for the 'Play Game' button in your HTML.
window.playGame = function() {
// I would generally recommend defining your functions before you use them.
// (This is just a matter of taste, though.)
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
// Rather than capitalize name everywhere it is used, just do it once
// and then use the result everywhere else.
function getName(message) {
return UCFL(prompt(message));
}
var name = getName('So what is your name?');
// Don't repeat yourself:
// If you're writing the same code in multiple places, try consolidating it
// into one place.
var nameAttempts = 0;
while (!confirm('So your name is ' + name + '?') && ++nameAttempts < 3) {
// Don't use 'var' again as your name variable is already declared.
name = getName('Then what is your name?');
}
if (nameAttempts < 3) {
alert('Good. Lets start the roleplay, Sir ' + name + '.');
} else {
alert("Oh, guess what? I do not even fucking care what your name is anymore. Let's just start...");
}
};
Put your code in a function, for example:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function runGame() {
// put your js code here
}
</script>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="runGame();" />
</form>
</body>
</html>
It would also be a good idea to copy your js code to another file and import that using a script tag, for instance:
<script src="path/to/file.js"></script>

Dynamically uploading a file in background with JavaScript

I'm trying to upload files in the background. I am not able to use any frameworks so I have to do manually. The page already contains a form, and the file input fields are located within that form, so I can't embed a form in a form so I need to move the file input around.
The problem with the code I'm using is that it doesn't seem to actually submit, I don't see any network activity at all. Can anyone spot anything wrong here?
<form>
...
<input id="photo-file-input" type="file"/>
<button type="button" onClick="uploadBackground('photo-file-input');">Upload</button>
....
</form>
function uploadBackground(fileInputId)
{
var iframe = createIframe('TEST');
var form = createUploadForm('TEST', 'upload.php');
var fileInput = document.getElementById(fileInputId);
var fileInputParent = fileInput.parent;
//move file input into generated form
form.appendChild(fileInput);
form.submit();
iframe.onload = function()
{
alert('file was uploaded');
//put the file input back where it was
fileInputParent.appendChild(fileInput);
//clean up generated elements
iframe.parent.removeChild(iframe);
form.parent.removeChild(form);
}
}
function createUploadForm(target, action)
{
var form = document.createElement('form');
form.display = 'none';
form.target = target;
form.action = action;
form.method = 'POST';
form.enctype = 'multipart/form-data';
return form;
}
function createIframe(name)
{
var iframe;
try
{
iframe = document.createElement('<iframe name="' + name + '">');
}
catch (ex)
{
iframe = document.createElement('iframe');
iframe.name = name;
}
return iframe;
}
You can not copy a file input element and set/keep its value. It is for security reasons. There is no reason why you need to create a new form. Just append an iframe to the page, set the target of form to the iframe name and submit the original form.
I have looking for the same problem and I think, I have found an solution, which will work for Firefox and Chrome and may be on IE 10 and above ( here I need some morr testing )
The solution is a little bit ugly because I use a frameset. But this is the only solution I have found so far.
The use case is:
We have a website with an product catalog, the editor can upload videos for each product.
The upload of the video need a long time, so I have look for an solution, where after you have chosen a video an start the upload, you can navigate to an other product and upload an other file without to wait until the download of the first is complete.
The test is based on some other work:
https://stackoverflow.com/a/1186309/2248340
https://stackoverflow.com/a/105074/2248340
How it works:
If you press submit, all you form data will be placed in an object. in this object is also the selected file list.
This object will push in an array requests in the upload frame.
here runs the watchdog and look if there are new requests ( status = 0 )
If it found one a new upload is started.
Here is my test project to try it:
The frameset:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<frameset rows="*,100">
<frame id="start" name="start" src="start.html">
<frame id="upload" name="upload" src="frame.html">
</frameset>
<noframes>
<body>
please use this
</body>
</noframes>
</html>
start.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Start</title>
<script src="../js/jquery-1.11.3.min.js" ></script>
<script>
var files;
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var UploadRequest=function(f)
{
var o= {};
o['guid']=guid();
o['action']=$('form').attr('action');
o['files']=files;
o['values']=$('form').serializeObject();
o['status']=0;
return o;
}
function fileSelect( e){
files=e.target.files;
return false;
}
</script>
</head>
<body>
<form id="test" action="phpinfo.php">
<input name="test" >
<input type="hidden" name="h1" value="2">
<input type="file" name="uploadfile" onchange="fileSelect(event)">
<input type="submit" value="upload‚" >
</form>
<script>
var olddogcounter=localStorage['uploadwatchdog'];
var check=false;
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
}
$(function() {
$('#test').submit(function() {
var request=new UploadRequest();
parent.upload.requests.push(request);
return false;
});
});
</script>
<a href="test.html" >test</a>
</body>
</html>
and the upload frame:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>frame</title>
</head>
<body>
<h1>frame</h1>
<iframe id="response" width="100%" height="200"></iframe>
<script>
var requests=new Array();
var counter=0;
function watchdog()
{
for(var i=0; i<requests.length; i++)
{
var request=requests[i];
if(request.status==0)
{
alert("watchdog :"+dump(request));
request.status=1;
uploadFile(request);
}
}
}
function uploadFile(request)
{
var url = request.action;
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
iframe=document.getElementById("response");
iframe.src="data:text/html;charset=utf-8," + escape(xhr.responseText);
}
};
if(request.files.length>1)
{
for(var i=0; i<request.files.length;i++)
{
var file=request.files[i];
fd.append("upload_file[]", file);
}
}
else
{
var file=request.files[0];
fd.append("upload_file",file );
}
for( var key in request.values)
{
fd.append(key,request.values[key] );
}
xhr.send(fd);
}
window.setInterval(watchdog,2000);
</script>
</body>
</html>
The solution is not complete, but I think is an good starting point.
ToDo:
- Show name of uploads in a list
- after upload remove request from array requests
- show progess bar for upload
- some error handling

Categories