How to get specific entry with JS from a DB (JSON) - javascript

I'm trying to do something like a dictionary. The idea is there is a DB online. Someone can search for term and get the description from the db.
How it works:
1) whole terms from the db will be downloaded and compared with searchterm. each term has its specific ID. If the searchterm is the DB the ID will be saved.
2) The ID will be sent to the server with the DB and than it should receive the description
URL to get all Terms
http://s288617660.mialojamiento.es/api.php?rquest=terms
Url to get description
http://s288617660.mialojamiento.es/api.php?rquest=answers&param1=ID
Now this is my search function
<script>
getAllTerms();
function getAllTerms(){
var url = "http://s288617660.mialojamiento.es/api.php?rquest=terms";
$.get(url, function(data) {
localStorage.setItem("terms", JSON.stringify(data));
//alert(JSON.stringify(data));
}).done(function() { /*alert(localStorage.getItem("terms"));*/ })
.fail(function() { alert("error"); })
.always(function() { /*alert("finished");*/ });
}
function findTerm(){
var content = $("#SearchTerm").val();
//alert(content);
var id = 0;
var data = JSON.parse(localStorage.getItem("terms"));
$.each(data, function(index, term) {
//alert("My content " + content + ", term " + term.name);
if(content == term.name){
id = term.id_term;
}
});
//--------------my try to request the description
var url_answers = "http://s288617660.mialojamiento.es/api.php?rquest=answers&param1="+id;
//alert(url_answers);
var answer = "";
$.get(url_answers, function(data2) {
localStorage.setItem("answer", JSON.stringify(data2));
$.each(data2, function(index, object) {
answer = object.description+object.id_answer;
});
//-----------------end of my try
//alert(id);
var htmlStr = "";
if(parseInt(id) > 0){
//i found the term
localStorage.setItem("idterm",id);
htmlStr = "<li>" + content + "- id: " + id + answer + "</li>"
}else{
//not found
htmlStr = "<li>Term not found</li>"
}
$('#SearchList').empty();
$('#SearchList').append(htmlStr);
$('#SearchList').listview("refresh");
}
</script>
The ID request just works fine but not the description request. Why?
By the way: it's a android phonegap project

Related

special character % is transmitted to % at server side through jquery AJAX call: Updated

I have a HTML form as the output of a java that gets a text from database and fill an input of that form with it. In form I can edit the text that on submit
Is sent back to java via a jquery AJAX call. Through java the text is saved in the database.
If I enter test% in text area it is coming as test% at server side.
Let’s say the HTML form looks like this :
<form id="form_used_0" action="#" method="post" onclick="hideAjaxList();">
<textarea name="summary" id=" summary " data-mini="true"><%=HtmlWriter.preformat(summary)%></textarea>
<a id="saveBtn" class="actionBtn" href="#" data-theme="b" onclick="onSave (this);">Save</a>
</form>
On saveBtn click this AJAX call is made:
function onSave(thisHref)
{
var respData = "";
var id = $("#id").attr("value");
var params = $("#form_used").serialize()+"&ajaxAction=SaveHeader"+"&id="+id;
$.post(ajaxURL, params, function(data){
if(data.length >0)
{
respData = data.substring(data.indexOf("|")+1, data.lastIndexOf("|"));
}
}).complete(function(){
if (respData.length > 0)
{
var responseData = respData.split("|");
var status = responseData[0];
var msg = responseData[1];
if (status == 'SUCCESS')
{
showSuccessMsgHeader(msg);
}
else if (status == 'ERROR')
{
showErrorMsgsOnly(msg);
}
}
});
}
I tried using the serializeArray method but now getting 400 Bad request error. I checked the form data in network tab and found that it is showing as unable to decode value beside input field .
function onSave(thisHref)
{
var respData = "";
var id = $("#id").attr("value");
var x = $("#form_used_0").serializeArray();
var paramsArr = "";
$.each(x, function(i, field){
if(i == x.length - 1){
paramsArr = paramsArr + field.name + "=" + field.value;
} else {
paramsArr = paramsArr + field.name + "=" + field.value + "&";
}
});
var params paramsArr +"&ajaxAction=SaveHeader"+"&id="+id;
$.post(ajaxURL, params, function(data){
if(data.length >0)
{
respData = data.substring(data.indexOf("|")+1, data.lastIndexOf("|"));
}
}).complete(function(){
if (respData.length > 0)
{
var responseData = respData.split("|");
var status = responseData[0];
var msg = responseData[1];
if (status == 'SUCCESS')
{
showSuccessMsgHeader(msg);
}
else if (status == 'ERROR')
{
showErrorMsgsOnly(msg);
}
}
});
}
Would it be possible for anyone to help me on the same.
As per jQuery documentation, The .serialize() method creates a text string in standard URL-encoded notation.
You can use Apache Commons StringEscapeUtils.unescapeHtml() to decode the string at server level.
Alternatively, if required you can pass the text from textarea as an additional param, which you can use it.
Thanks.

File browsing and omdb

I'm kinda new to php + javascript.
I have set up "cute file browser" to look at a shared folder on my computer.
it works fine displays all files & folders no problem.
Now im trying to use OMDB to search for movie posters and then display them for each movie name.
Currently it works but only with the first movie title. when inspecting the element in FF it does show all the other posters but only within the first
This is the code i made for the OMDB...
var filmName;
var realName;
filmName = finfo;
realName = filmName.split('.')[0];
var omdbUrl = "http://www.omdbapi.com/?t=" + realName;
$.ajax({
url: omdbUrl,
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//now json variable contains data in json format
//let's display a few items
document.getElementById("folders").innerHTML += "<img id='imgposter' class='imgPoster' src='" + json.Poster + "'></img>";
}
});
And this is the code for displaying my movie folders:
if(scannedFolders.length) {
scannedFolders.forEach(function(f) {
var itemsLength = f.items.length,
name = escapeHTML(f.name);
if(itemsLength) {
icon = '<span class="icon folder full"></span>';
}
if(itemsLength == 1) {
itemsLength += ' item';
}
else if(itemsLength > 1) {
itemsLength += ' items';
getPoster(name);
}
else {
itemsLength = 'Empty';
}
var folder = $('<li id="folders" class="folders"><span class="name">' + name + '</span> </li>');
folder.appendTo(fileList);
});
}
This is the error i get
As i said i am new here. if anyone could give me any tips would be great thanks

Displaying images from JSON

Trying to display the cover art with the results. Something in the img src tag is causing the app not to load. If I just point the img to data.tracks[i].album.name (obviously not a real url, but enough to test if it's working) it pastes it in just fine, but the moment I change it to paste the url in place, it makes the whole app stop working.
$('#findTracks').click(function (e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.length > 0) {
var tracksLength = data.tracks.length, html = '';
for (var i=0; i<tracksLength; i++) {
var href = '';
if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1) { // data.tracks[i].href
href = data.tracks[i].href;
href = 'makeReq(\''+data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+'\')';
html += '<li>' +data.tracks[i].name + ' by '+data.tracks[i].artists[0].name+ ' <img src="' +data.tracks[i].album.images[0].url+ '" />';html += '</li>';
html += '</li>';
}
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
This is my first time ever coding in javascript so please go easy on me! lol
EDIT:
This seems to be running well! However, many of the songs do nothing when I click on them
For example, type "Don't Stop" and only "The Black Eyed Peas - Don’t Stop The Party" works out of the first ten...anybody know why?
also, anybody known why "if (data.tracks[i].album.availability.territories.indexOf(' GB ') !== -1)" is in there? If I take it out this all stops working...I am not in G.B.
If you look in the console you are getting the error
Uncaught TypeError: Cannot read property '0' of undefined
looking at the data the query returns we notice that data.tracks[i].album returns
{
"released": "2006",
"href": "spotify:album:2knAf4wg8Gff8q1bXiXCTz",
"name": "The Dutchess",
"availability": {
"territories": "MX"
}
}
there is no property images so when you call
data.tracks[i].album.images[0]
you get the undefined error, causing the script to halt execution.
I'm unfamiliar with the spootify api but taking a quick glance at the api theres the endpoint for get-album. Heres what I was able to come up with to get the album art
$.get("http://ws.spotify.com/search/1/track.json?q=Fergie",function(data){
var albumId = data.tracks[97].album.href.split(":")[2];
$.get("https://api.spotify.com/v1/albums/" + albumId,function(albumResponse){
var firstImage = albumResponse.images[0];
$('body').append($('<img/>',{
src : firstImage.url,
width : firstImage.width,
height : firstImage.height
}));
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>
You should research more into how to get the album art since I'm unsure if this is the optimal solution.
The search endpoint you mentioned is different from the one your using.
One your using
url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
One you linked to
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
Heres your solution with the change in endpoint
$('#findTracks').click(function(e) {
e.preventDefault(); // override/don't submit form
$('#recommendations').empty();
var artist = $('#artist').val();
var userid = "";
var playlistid = "";
$.ajax({
//url: 'http://ws.spotify.com/search/1/track.json?q=' + artist,
url: 'https://api.spotify.com/v1/search?q=' + artist + '&type=track,artist&market=GB',
type: 'GET',
dataType: 'json',
success: function(data) {
if (data.tracks.items.length > 0) {
data.tracks = data.tracks.items
data.artists = data.artists.items
var tracksLength = data.tracks.length,
html = '';
for (var i = 0; i < tracksLength; i++) {
var href = '';
href = data.tracks[i].href;
href = 'makeReq(\'' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + '\')';
html += '<li>' + data.tracks[i].name + ' by ' + data.tracks[i].artists[0].name + ' <img src="' + data.tracks[i].album.images[0].url + '" />';
html += '</li>';
html += '</li>';
}
$('#third').css('display', 'block');
$('#recommendations').append(html);
} else {
$('#recommendations').append('<li>No matches returned.</li>');
$('#third').css('display', 'none');
}
},
error: function(err) {
alert("The Spotify API failed to return a response.");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Artist:
<input type="text" id="artist" />
<button id="findTracks">Find Tracks</button>
<div id="recommendations"></div>

Saving data to parse using javaScript SDK

Using parse.com and JavaScript SDK.
- Section one shows a list of objects
- Section two lets the user select one of those objects and add to a modal box
- Section three saves the data to parse
What I'm unable to work out is how I can save the section 1 item.badgename and item.category to parse.
I've tried adding myBadge.set("category", badgename.toString()); to section 3, but I get a undefined error. i'm not sure how to define this before trying to save.
Really need some help and an example to follow.
3 -Saves the badge details to parse
var MyBadge = Parse.Object.extend("myBadges");
var FriendRequest = Parse.Object.extend("FriendRequest");
var friendRequest = new FriendRequest();
friendRequest.id = window.selectedFriendRequestId;
var badgeselected = $('#badgeselect .go').attr("src");
$(document).ready(function() {
$("#send").click(function() {
var myBadge = new MyBadge();
var badgeselected = $('#badgeselect img').attr("src");
var BadgeSentTo = $('#selectFriend').val();
var categorySelected = $('#category').val();
var uploadercomment = $('#UploaderComment').val();
myBadge.set("BadgeName", badgeselected); //got this working using .set
myBadge.set("Comment", uploadercomment); //got this working using .set
myBadge.set("category", categorySelected);
myBadge.set("SentTo", new Parse.User({
id: BadgeSentTo
}));
myBadge.set("uploadedBy", Parse.User.current());
myBadge.save(null, {
success: function(results) {
console.log("Done");
//location.reload();
},
error: function(contact, error) {
// The save failed.
alert("Error: " + error.code + " " + error.message);
}
});
return false;
});
});
** 1- Returns results to the page for user to select**
var GlobalBadges = Parse.Object.extend("Global_Badges");
var query = new Parse.Query(GlobalBadges);
query.exists("Global_Badges_img");
query.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('Global_Badges_img'),
//friendRequestId: results[i].id,
badgename: results[i].get('BadgeName'),
category: results[i].get('category')
});
}
// TW: replaced dynamic HTML generation with wrapper DIV that contains IMG and name DIV
_.each(friends, function(item) {
// using a wrapper so the user can click the pic or the name
var wrapper = $('<div></div>');
wrapper.append('<img class="images BadgeImgOutline responsive-image" src="' + item.imageURL + '" />'+ '<br>');
wrapper.append('<div id="name"class="tag badgelabel" >'+ item.badgename + '</div>'+ '<br>');
wrapper.append('<div id="category" class="tag categorylabel" >'+ item.category + '</div>'+ '<br>'+ '<br>' );
$('#container').append(wrapper);
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
2 -Upon the user selecting an object from above, this adds the data to a modalbox
$(document).ready(function() {
$('.go img').css('cursor', 'pointer');
$('.go').on('click', 'img', function(e) {
$('.go img').removeClass('BadgeImgOutline');
$(this).parent().appendTo('#badgeselect');
$(this).addClass('BadgeImgOutlineSmall');
$('.go img').addClass('BadgeImgOutline');
$('#modal').reveal({
closeonbackgroundclick: true,
dismissmodalclass: 'close'
});
return false;
});
});
This was addressed by making the following changes.
- Taking the data from #badgeSelect not #category
- From section 3, the line var categorySelected = $('#category').val(); was changed to categorySelected = $('#badgeselect .categorylabel').text();
By taking the data from #badgeSelect it meant that the only data being available was that shown shown in the text box, instead of '#category'that returned all results.
The it was simply targeting the text correctly with the change to the var categorySelected

Loading dynamically generated content and URL after page reload

I have a Google Instant style search script written in jQuery. When a user searches, a URL is created which is something like #search/QUERY/3/. However, when you either reload the page, click a result which goes to a different page or return back from a previous page the search results are no longer there. Why could this be?
Here is my jQuery code:
$(document).ready(function(){
$("#search").keyup(function(){
var search=$(this).val();
var query=encodeURIComponent(search);
var page=1;
var yt_url='search.php?q='+query+'&category=web&d='+page+'';
window.location.hash='search/'+query+'/'+page+'/';
document.title=$(this).val()+" - My Search Script";
if(search==''){
window.location.hash='';
document.title='My Search Script';
}
$.ajax({
type:"GET",
url:yt_url,
dataType:"html",
success:function(response){
if(response !=""){
$("#result").html(response);
} else {
$("#result").html("Your search did not return any results");
}
}
});
});
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
});
I think it could be something to do with these lines of code:
if(window.location.hash.indexOf('#search/')==0){
query=window.location.hash.replace('#search/', '').replace('/1/', '');
$('#search').val(decodeURIComponent(query)).keyup();
}
You need to write a function for the search so you can specify the page number.
$(document).ready(function(){
var search = function (query, page) {
page = page ? page : 1;
query = encodeURIComponent(query),
var yt_url = 'search.php?q=' + query + '&category=web&d=' + page + '';
if (query == '') {
window.location.hash = '';
document.title = 'My Search Script';
} else {
window.location.hash = 'search/' + query + '/' + page + '/';
document.title = $(this).val() + " - My Search Script";
}
$.ajax({ ... });
};
$("#search").keyup(function(){ search(this.value); });
if (window.location.hash.indexOf('#search/') == 0) {
var query = window.location.hash.replace('#search/', ''),
page = query.replace(/.+?\/(\d+)\//, '$1');
query = query.replace(/\/\d+\//, '');
search(decodeURIComponent(query), page);
}
});

Categories