Trying to display images in HTML with Flickr API - javascript

For some reason images wont display when i pull them from Flickr, here's the code i have so far. As you can see I have one of the URLs commented out, the one commented out actually works and displays the images but the URL before it (the one I actually need) won't work.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="http://ajax.googleapis.com/ajax/li`enter code here`bs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bde2ddde05dd5e7abbc7a44b9abc12ef&tags=gtav%2C+grand+theft+auto%2C++rockstar&bbox=-122.65057757118905%2C37.71174524790033%2C-122.2214241288068%2C37.81705186562751+&has_geo=&format=json&nojsoncallback=?", displayImages1); <!--("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bde2ddde05dd5e7abbc7a44b9abc12ef&tags=gtav&format=json&jsoncallback=?", displayImages1); -->
function displayImages1(data) {
$.each(data.photos.photo, function (i, item) {
var photoID = item.id;
lat = item.latitude;
long = item.longitude;
$('#images1').append(photoID);
var photoURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg';
htmlString = '<img src="' + photoURL + '">';
$('#images1').append(htmlString);
$('#images1').append("<br/><hr/><br/>");
});
}
});
</script>
</head>
<body>
<div id="images1"> </div>
<p> </p>
</body>
</html>

Your link is not correct. The correct link is below. It ends with jsoncallback.
http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=bde2ddde05dd5e7abbc7a44b9abc12ef&tags=gtav%2C+grand+theft+auto%2C++rockstar&bbox=-122.65057757118905%2C37.71174524790033%2C-122.2214241288068%2C37.81705186562751+&format=json&jsoncallback=?

Related

Results not displayed in API call

I am trying to call weather API, but for some reason I could not see the results both in console and the webpage after entering a specific city
I called
<div id="results"></div>
and made sure to declare it in my script. Can someone help?
Update: When I combine them into one file, the code works. But when I separate them into two different files, it does not work. What am I missing here?
This is the script.js of the code
var cityform = document.getElementById("cityform");
// Check if the cityform variable is not null
if (cityform !== null) {
// Add a submit event listener to the form
cityform.addEventListener("submit", function(event) {
// Prevent the default form submission behavior
event.preventDefault();
// Get a reference to the input element
var cityInput = document.getElementById("thecity");
// Check if the cityInput variable is not null
if (cityInput !== null) {
// Get the input value
var city = cityInput.value;
// Make the API request using the city value
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data){
console.log(data);
// Extract the data from the API response
var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = Math.floor(data.main.temp) + "F";
var weather = data.weather[0].main;
// Get a reference to the element where the data will be displayed
var results = document.getElementById("results");
// Update the element with the data from the API
results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
});
}
});
}
Then here is the HTML
<head>
<meta charset="UTF-8">
<meta name ="viewport" content="width=device=width, intial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content ="is=edge">
<title>API</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script src = "script.js"></script>
</head>
<body>
<!-- HTML -->
<h1>Weather Report</h1>
<form id="cityform">
<label for="thecity">City:</label><br>
<input type="text" name="thecity" id="thecity"><br><br>
<button type="submit">Search</button>
</form>
<!-- Create an element where the data will be displayed -->
<div id="results"></div>
</body>
</html>
What could be the possible issue or if there's no issue, how can you display the result of the icon, temp and weather to the "results"
Paste the script.js linking part at the end.
It might be possible that when your scripts is ran form was not creaded thus those variables were not existing that time.
See both example, this works
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device=width, intial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="is=edge">
<title>API</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
<!-- HTML -->
<h1>Weather Report</h1>
<form id="cityform">
<label for="thecity">City:</label>
<br>
<input type="text" name="thecity" id="thecity">
<br>
<br>
<button type="submit">Search</button>
</form>
<!-- Create an element where the data will be displayed -->
<div id="results"></div>
<script>
var cityform = document.getElementById("cityform");
// Check if the cityform variable is not null
if (cityform !== null) {
// Add a submit event listener to the form
cityform.addEventListener("submit", function(event) {
// Prevent the default form submission behavior
event.preventDefault();
// Get a reference to the input element
var cityInput = document.getElementById("thecity");
// Check if the cityInput variable is not null
if (cityInput !== null) {
// Get the input value
var city = cityInput.value;
// Make the API request using the city value
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data) {
console.log(data);
// Extract the data from the API response
var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = Math.floor(data.main.temp) + "F";
var weather = data.weather[0].main;
// Get a reference to the element where the data will be displayed
var results = document.getElementById("results");
// Update the element with the data from the API
results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
});
}
});
}
</script>
</body>
</html>
But not this
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device=width, intial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="is=edge">
<title>API</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
var cityform = document.getElementById("cityform");
// Check if the cityform variable is not null
if (cityform !== null) {
// Add a submit event listener to the form
cityform.addEventListener("submit", function(event) {
// Prevent the default form submission behavior
event.preventDefault();
// Get a reference to the input element
var cityInput = document.getElementById("thecity");
// Check if the cityInput variable is not null
if (cityInput !== null) {
// Get the input value
var city = cityInput.value;
// Make the API request using the city value
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function(data) {
console.log(data);
// Extract the data from the API response
var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = Math.floor(data.main.temp) + "F";
var weather = data.weather[0].main;
// Get a reference to the element where the data will be displayed
var results = document.getElementById("results");
// Update the element with the data from the API
results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
});
}
});
}
</script>
</head>
<body>
<!-- HTML -->
<h1>Weather Report</h1>
<form id="cityform">
<label for="thecity">City:</label>
<br>
<input type="text" name="thecity" id="thecity">
<br>
<br>
<button type="submit">Search</button>
</form>
<!-- Create an element where the data will be displayed -->
<div id="results"></div>
</body>
</html>
If you want to check yourself then just after
var cityform = document.getElementById("cityform");
add alert(cityform)
When script linking is in head before body then we will get null in alert
But when the script is at end near closing body tag then alert will have the form element.
Hope it helps.
Comment if I am wrong somewhere.
You need to move script from head location inside of body in HTML
This code works
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device=width, intial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="is=edge">
<title>API</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
</head>
<body>
<!-- HTML -->
<h1>Weather Report</h1>
<form id="cityform">
<label for="thecity">City:</label><br>
<input type="text" name="thecity" id="thecity"><br><br>
<button type="submit">Search</button>
</form>
<!-- Create an element where the data will be displayed -->
<div id="results"></div>
<script src="script.js"></script>
</body>
</html>
function resultSubmit(event) {
event.preventDefault();
// Get the input value
var city = cityInput.value;
// Make the API request using the city value
$.getJSON("https://api.openweathermap.org/data/2.5/weather?q=" + city + "&units=imperial&appid=0dcc391bac34298837f2047642794ee3", function (data) {
console.log(data);
// Extract the data from the API response
var icon = "http://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
var temp = Math.floor(data.main.temp) + "F";
var weather = data.weather[0].main;
// Update the element with the data from the API
results.innerHTML = "<img src='" + icon + "'> <p>" + weather + "</p> <p>" + temp + "</p>";
});
}
const cityform = document.getElementById("cityform");
const cityInput = document.getElementById("thecity");
const results = document.getElementById('results')
cityform.addEventListener('submit', resultSubmit)
Result - I ran GO Live extension it in VS code
html tag and code relationship

Field Length Always = 1

Following the Reuters Ajax Solr tutorial I'm having an issue getting a fields length.
The issue is with the 'template' but I believe it may stem from another js file.
THE TUTORIALS 'TEMPLATE'
template: function (doc) {
var snippet = '';
if (doc.text.length > 300) {
snippet += doc.dateline + ' ' + doc.text.substring(0, 300);
snippet += '<span style="display:none;">' + doc.text.substring(300);
snippet += '</span> more';
}
else {
snippet += doc.dateline + ' ' + doc.text;
}
var output = '<div><h2>' + doc.title + '</h2>';
output += '<p id="links_' + doc.id + '" class="links"></p>';
output += '<p>' + snippet + '</p></div>';
return output;
},
MY 'TEMPLATE'
template: function (doc) {
var snippet = '';
if (doc.Solution.length > 200) {
snippet += doc.Solution.substring(0, 200) + ' ' + doc.date;
snippet += '<span style="display:none;">' + doc.Solution.substring(200);
snippet += '</span> more';
}
else {
snippet += doc.Solution.length + '<br>' + doc.date + '';
}
var output = '<div><br><b>' + doc.Problem + '</b><br>';
output += '' + snippet + '';
output += ' ID #' + doc.id + '</div>';
return output;
},
This section is supposed to allow for a 'more' button if a field is over a certain length. With my template, this is my output:
My 'Solution' field is a long text field which in my schema for solr (7.5) is defined as text_general.
I have tried String() and .toString but those gave me issues as well.
I'm very new to CS as a whole but it seems that my field is behaving as an array or boolean?
In the tutorial they have an older version of solr but the field they get the length on is text_general as well. I'm not exactly sure where I should look next.
PS: this is how the code is structured in the tutorial, a friend of mine was confused because it doesn't all seem to be best practices.
I my setup differs from the tutorial in a few ways, I use my version of JQuery (v3.3.1) and they use some style sheets that I do not.
The <head> of my html doc:
<title>Testing Solr</title>
<meta charset="UTF-8">
<!--style sheets and links in tutorial source code--
<link rel="stylesheet" href="reuters.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/smoothness/jquery-ui.css">
<!--my downloaded copy of jquery-->
<script src="script/jquery.js"></script>
<!-- mentioned in tutorial -->
<script src="script/our.js"></script>
<script src="script/Core.js"></script>
<script src="script/AbstractManager.js"></script>
<script src="script/Manager.jquery.js"></script>
<script src="script/Parameter.js"></script>
<script src="script/ParameterStore.js"></script>
<script src="script/AbstractWidget.js"></script>
<script src="script/ResultWidget.js"></script>
Switched to using their links other than the reuters.css, still displaying 1.
Using console.log(doc.Solution); this is indeed acting as an array.
["solution to unlock "]
0: "solution to unlock "
length: 1
__proto__: Array(0)
Adding console.log(doc.text); to the tutorial's ResultWidget.js returns plain text to the console. Whats a likely reason my field is being read as an array when theirs is read as a string?

How to update textarea with replace method through jQuery

I have a textarea that will contains a code entered by user and I want to get that code and scan it with jQuery to get the value inside a custom tag called setting then add this value to an input so the user will be able to change the value inside setting tag without touching the code. I was able to get the values and add them inside the inputs but I couldn't update the code with the new values.
HTML CODE :
<div id='tab-1'>
<textarea id='template-code' cols='67' rows='27'></textarea>
<button id='submit-code'>Submit Code</button>
</div>
<div id='tab-2' class='unactive'>
<form id='settings-form' method='POST'>
<div id='result'></div>
<button id='update-code'>Update Code</button>
</form>
</div>
CSS CODE :
.unactive {
display: none
}
jQuery CODE :
$('#template-code').change(function (){
var $that = $(this),
template_code = $that.val(),
code = '',
new_data = '',
text = '',
newCode = '';
// Extract settings from the theme and add them to #result
$(document).on('click', '#submit-code', function (){
$('#tab-1').addClass('unactive');
$('#tab-2').removeClass('unactive');
$(template_code).find('setting').each(function (i){
var $this = $(this),
setting_std = $this.text(),
setting_id = $this.attr('id');
code += '<input id="'+setting_id+'" name="'+setting_id+'" type="text" value="'+setting_std+'"><br>';
});
if(code !== ''){
$('#result').html(code);
}
});
// Update old data with the new one
$(document).on('click', '#update-code', function (){
new_data = $( "#settings-form" ).serializeArray();
$.each( new_data, function( i, new_field ) {
var start_key = "id='"+new_field.name+"'>",
end_key = '</setting>',
start = template_code.indexOf(start_key),
end = template_code.indexOf(end_key);
text = template_code.substring(start + start_key.length, end);
// THE PROBLEM IS HERE
// I want the variable template_code to contains the new value not the old one so I used replace but it seems that it doesn't work
template_code.replace(text, new_field.value);
});
$('#template-code').val(template_code);
$('#tab-1').removeClass('unactive');
return false;
});
});
This is an example of the theme code that will be added inside the textarea :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
<head>
<b:include data='blog' name='all-head-content'/>
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>
<link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>
<link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>
<title><data:blog.pageTitle/></title>
<div id='option-panel' style='display:none!important'>
<setting id='post_thumbnail'>http://lorempixel.com/640/300/</setting>
<setting id='search_icon'>on</setting>
</div>
</head>
<body>
</body>
</html>
To understand my issue please enter to this JsFiddle and copy the code above then put it inside the textarea and click submit code, you will get two inputs the content of those inputs come from these two tags :
<setting id='post_thumbnail'>http://lorempixel.com/640/300/</setting>
<setting id='search_icon'>on</setting>
I want when the user change the value of inputs and click "update code" to change the value of setting tag inside the entire code.
Try this and see if it's what you're looking for:
HTML
<div id='tab-1'>
<textarea id='template' cols='67' rows='27'></textarea>
<button id='submit'>Submit Code</button>
</div>
<div id='tab-2'>
<form id='settings-form' method='POST'>
<div id='result'></div>
<button id='update'>Update Code</button>
</form>
</div>
JavaScript:
function wrap(data) {
var string = '';
var i, l;
string += "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n";
string += "<!DOCTYPE html>\r\n";
string += "<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>\r\n";
string += " <head>\r\n";
string += " <b:include data='blog' name='all-head-content'/>\r\n";
string += " <link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>\r\n";
string += " <link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>\r\n";
string += " <link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>\r\n";
string += " <title><data:blog.pageTitle/></title>\r\n";
string += " </head>\r\n";
string += " <body>\r\n";
string += " <div id='option-panel' style='display:none!important'>\r\n";
for (i = 0, l = data.length; i < l; i++)
string += " " + data[i].toString() + "\r\n";
string += " </div>\r\n";
string += " </body>\r\n";
string += "</html>\r\n";
return string;
}
$("#submit").on('click', function() {
var virtual = document.createElement("div");
var temp = '';
virtual.innerHTML = $("#template").val();
$(virtual).find('setting').each(function(i) {
var $this = $(this),
setting_std = $this.text(),
setting_id = $this.attr('id');
temp += '<input id="' + setting_id + '" name="' + setting_id + '" type="text" value="' + setting_std + '"><br>';
});
if (temp !== '')
$('#result').html(temp);
});
$("#update").on('click', function(event) {
var temp = [];
event.preventDefault();
$("#result").find("input").each(function() {
temp.push("<setting id=\"" + this.id.toString() + "\">" + this.value.toString() + "</setting>");
});
$("#template").val(wrap(temp));
});
I believe that does what you're looking for? Even though you're using jQuery, I think you ended up making it a lot harder than it had to be. I used a virtual node to quickly/easily find and pull ONLY the setting tag from the textarea on submit (down and dirty, I suppose?).
I removed the styles and whatnot since it was interfering with rapid testing, and you'll need to apply proper sanity checking/validation against user input.
Edit: Updated answer to include a ghetto wrapping function to elucidate the concept. I would not recommend using it as is, but instead utilizing a real template, which would require work outside the scope of this question.
Most recent JSFiddle after editing: http://jsfiddle.net/zo3hh2ye/6/
Here's another version of the code. I saved the new values in an array and then replaced them with the existing values in the textarea text. Give a try and see if that solves your problem.
Script :
<script type="text/javascript">
$('#template-code').change(function () {
var $that = $(this),
template_code = $that.val(),
code = '',
new_data = '',
text = '',
newCode = '';
// Extract settings from the theme and add them to #result
$('#submit-code').click(function () {
$('#tab-1').addClass('unactive');
$('#tab-2').removeClass('unactive');
$(template_code).find('setting').each(function (i) {
var $this = $(this),
setting_std = $this.text(),
setting_id = $this.attr('id');
code += '<input id="' + setting_id + '" name="' + setting_id + '" type="text" value="' + setting_std + '"><br>';
});
if (code !== '') {
$('#result').html(code);
}
});
// Update old data with the new one
$('#update-code').click(function () {
new_data = $("#settings-form").serializeArray();
$(template_code).find('setting').each(function (i) {
template_code = template_code.replace("<setting", "").replace("id='" + $(this).attr("id") + "'>", "").replace($(this).html(), "{" + i + "}").replace("</setting>", "");
});
$.each(new_data, function (i, new_field) {
template_code = template_code.replace("{" + i + "}", "<setting id='" + new_field.name + "'>" + new_field.value + "</setting>");
});
$('#template-code').val(template_code);
$('#tab-1').removeClass('unactive');
return false;
});
});
</script>
HTML Template :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html>
<html b:version='2' class='v2' expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>
<head>
<b:include data='blog' name='all-head-content'/>
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,300italic,700' rel='stylesheet' type='text/css'/>
<link href='http://fonts.googleapis.com/css?family=Lora:400,400italic,700,700italic' rel='stylesheet' type='text/css'/>
<link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css' rel='stylesheet'/>
<title><data:blog.pageTitle/></title>
<div id='option-panel' style='display:none!important'>
<setting id='post_thumbnail'>text1</setting>
<setting id='search_icon'>text2</setting>
</div>
</head>
<body>
</body>
</html>
I couldn't replace the text 'on' in the template you provided, not sure if it has something to do with some reserved key word but everything else works fine.

Sorting on ajax scrolling content in javascript

I have some 1000 of records which I want to display in divs. I'm displaying them in bundles of 20, and when you scroll to bottom loads next 20 records. I'm sorting the records on a range attribute, but when I scroll and load new 20 records in success function of my ajax call, that sorting condition of div is not working for those divs.
Those new Records are displayed in serial order without getting sorted. I'm able to sort the records in present page but if u sort and then scroll to bottom and load new records - those records are not getting sorted on scrolling.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
</head>
<body>
<div id="container">
<div class="content" data-name="Peter" data-price="1000" data-location="US"><span class="productPriceForSorting">1000</span</div><br />
<div class="content" data-name="Willy" data-price="1200" data-location="Mexico"><span class="productPriceForSorting">1200</span</div><br />
<div class="content" data-name="Peter" data-price="2000" data-location="US"><span class="productPriceForSorting">2000</span</div><br />
<div class="content" data-name="Willy" data-price="800" data-location="Mexico"><span class="productPriceForSorting">800</span</div><br />
<div class="content" data-name="Willy" data-price="1300" data-location="Mexico"><span class="productPriceForSorting">1300</span</div><br />
<div class="content" data-name="Peter" data-price="800" data-location="US"><span class="productPriceForSorting">800</span</div><br />
</div>
</div>
<div id="prod"></div>
<button id="asc">sort by price asd</button>
below is my ajax scrolled records
<script type="text/javascript">
$(document).ready(function() {
var page=1;
<%String name1=(String)session.getAttribute("name");%>
var name2="<%=name1%>";
$(window).scroll(function(e)
{if ($(window).scrollTop()+ $(window).height() == $(document).height())
{page++;
$.ajax({ type : "Get",
url : "Someservlet",
datatype : "JSON",
contentType : 'application/json',
data : {pagenumber : page,
Pname : name2},
success : function(data) {
var data1 = data[0],
var len = data1.length;
for (var i = 0; i < len; i++) {
var name = "<div class=content data-name=" + data1[i].name + '' + " data-location=" + data1[i].location + ">"
+ "Peter" +"</div>"+"<div class=content data-name=" + data1[i].name + '' + " data-location=" + data1[i].location + ">"
+ "Willy" +"</div>";
$(name).appendTo("#prod");
}
}
});
}
});
});
</script>
Following is code for sorting
<script type="text/javascript">
function sortByPrice(a, b) {
return $(a).find('.productPriceForSorting').text() > $(b).find(
'.productPriceForSorting').text();
}
function reorderEl1(el) {
var container = $('#container');
container.html('');
el.each(function() {
$(this).appendTo(container);
});
}
$(document).ready('#asc').click(function() {
reorderEl1($('.content').sort(sortByPrice));
});
</script>
Please help me guys, how to sort the scrolling elements once sorting is clicked?
Your AJAX call generates records as following:
var name = "<div class=content data-name=" + data1[i].name + '' + " data-location=" + data1[i].location + ">"
+ "Peter" +"</div>"+"<div class=content data-name=" + data1[i].name + '' + " data-location=" + data1[i].location + ">"
+ "Willy" +"</div>";
Burt your sorting function is looking for .productPriceForSorting element which is not added by AJAX. That's what you need to change. Sorting function is not detecting .productPriceForSorting so it's not comparing.
Also your sort function is not comparing properly, it should be:
function sortByPrice(a, b) {
return parseInt($(a).find('.productPriceForSorting').text()) > parseInt($(b).find('.productPriceForSorting').text());
}
Here's the working demo of fixed sorting. Ajax is for you to be fixed. It must contain <span class=\"productPriceForSorting\">"+data1[i].price+"</span> or something like that.

JSon and Jquery Accordion

This is driving me freaking BATTY as hell.
This is essentially what I am trying to accomplish.
You'll see the Json there are a 2 different departments "Office" and "Stockroom"
What I am trying to accomplish is to arrange everyone by the department they are in. The problem with this is that the HTML needs to look something like this
<h3>Section 1</h3>
<div>
<p>
First Paragraph
</p>
<p>
Second Paragraph
</p>
<p>
Third Paragraph
</p>
</div>
But unfortunately I cannot seem to get the </div> tag in the right spot at the end of the last paragraph of each section
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="http://jqueryui.com/themes/base/jquery.ui.all.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://jqueryui.com/ui/jquery.ui.core.js"></script>
<script type="text/javascript" src="http://jqueryui.com/ui/jquery.ui.widget.js"></script>
<script type="text/javascript" src="http://jqueryui.com/ui/jquery.ui.accordion.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var contacts = [{"displayname":"Bruce Lee","email":"Bruce.lee#karate.com","department":"stockroom"},
{"displayname":"Your Momma","email":"Your.Momma#Yourmom.com ","department":"stockroom"},
{"displayname":"Bob","email":"Bob#bob.com ","department":"Office"},
{"displayname":"Cathy","email":"Cathy#Cathy.com ","department":"Office"},
{"displayname":"mike","email":"mike#Cathy.com ","department":"Office"},
{"displayname":"scott","email":"scott#Cathy.com ","department":"Office"}
];
var contacts2 = contacts;
var r = 1;
var lastvalue = 'blah';
for(var i=0; i <=contacts.length; i++)
{
if(contacts[i].department != null)
{
if(lastvalue != contacts[i].department)
{
if(i<1)
{
$('#accordion').append('</div><h3>' + contacts[i].department + '</h3>');
$('#accordion').append('<div><p>' + contacts[i].displayname + '</p>');
}else{
$('#accordion').append('<h3>' + contacts[i].department + '</h3>');
$('#accordion').append('<div><p>' + contacts[i].displayname + '</p>');
}
}else{
$('#accordion').append('<p>' + contacts[i].displayname + '</p>');
}
lastvalue = contacts[i].department;
r++;
}
}
});
$(function() {
$( "#accordion" ).accordion();
});
</script>
</head>
<body>
<div id="contactlist">
<div id="accordion">
</div>
</div>
</body>
</html>
You might want to change this to a jquery each loop and work with json objects directly inside it. The reason you were getting an accordion level each time was due to your loop inserting a h3 every time. I've supplied code to get you pretty much what you need.
edit:
Here is a link to my forked jsfiddle => http://jsfiddle.net/TTV6d/12/
Hope this helps
var departmentlist=new Array();
$.each(contacts, function(i,contact) {
//insert the departments
if (contact.department != null && $('#' + contact.department).length == 0) {
$('#accordion').append('<h3 id='+ contact.department +'>' + contact.department + '</h3>');
departmentlist.push(contact.department);
}
//insert contacts in the accordion
$('#' + contact.department).after('<p>' + contact.displayname + '</p>');
});
$.each(departmentlist, function(i,list) {
$("#" + list).nextUntil("h3").wrapAll("<div></div>");
});
First, be aware that browsers will generally attempt to normalize markup appended to the document: (http://jsfiddle.net/EVjaq/)
$('#container').append('<div><p>Testing</p>'); // no `</div>`
console.log($('#container').html()); // `<div><p>Testing</p></div>`
So, the open <div> in this line will be closed at the end for you, before the next <p> is appended:
$('#accordion').append('<div><p>' + contacts[i].displayname + '</p>');
To avoid this, you can store all of the HTML in a variable, concatenating segments together, and append it to the DOM only once it's done. Or, you can store the <div> and append to that, which can make the conditionals a bit simpler:
var lastvalue = null,
lastdiv = null;
for (var i = 0; i <= contacts.length - 1; i++) {
if (contacts[i].department != null) {
if (lastvalue != contacts[i].department) {
$('#accordion').append('<h3>' + contacts[i].department + '</h3>');
// remember `<div>`
lastdiv = $('<div>').appendTo('#accordion');
}
// append to the `<div>` directly rather than `#accordion`
// also, skip the `else` so you don't have to type this twice
lastdiv.append('<p>' + contacts[i].displayname + '</p>');
lastvalue = contacts[i].department;
r++;
}
}

Categories

Resources