I have seen many examples and I have used this myself in many of my programs but for some reason this doesn't want to work today.
I have JSON data that I can show in console.log but it is unusable in my select. I get this error in my console:
Cannot use 'in' operator to search for '76' in {"hello1":"hello1","hello2":"hello2"}
This is my code:
$.get("JSON.php?value=two", function(response) {
console.log(response);
// this is what my JSON returns
// {"hello1":"hello1","hello2":"hello2"}
if (response != '') {
$('#dropdown').find('option').remove();
$.each(response,function(key, value){
$('#dropdown').append('<option value=' + key + '>' + value + '</option>');
});
}
)};
I just tested this successfully
<html>
<head>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$( document ).ready(function() {
var response = {"hello1":"hello1","hello2":"hello2"} ;
$('#dropdown').find('option').remove();
$.each(response,function(key, value){
$('#dropdown').append('<option value=' + key + '>' + value + '</option>');
});
});
</script>
</head>
<body>
<select id="dropdown"></select>
</body>
</html>
Please check. You will get something
To achieve this your response should be an Array of Objects.
[
{
hello1 : "hello1"
},
{
hello2 : "hello2"
}
]
Solution
Worked when Array was converted to Object
$.get("JSON.php?value=two", function(response)
{
console.log(response);
// this is what my JSON returns
// {"hello1":"hello1","hello2":"hello2"}
if (response != '')
{
var response2 = JSON.parse(response);
$('#dropdown').find('option').remove();
$.each(response2,function(key, value){
$('#dropdown').append('<option value=' + key + '>' + value +
'</option>');
});
}
)};
Related
I am following a tutorial on YouTube but I couldn't make it run. Basically I have a country.json file.and I am trying to retrieve data inside it. What is wrong here??
This is how country.json file looks like
{
"name": "Germany",
"capital": "Berlin",
"pop": "some value"
}
JavaScript
var container = $("div.container");
$("input#get").click(function () {
$.ajax({
type: "Get",
url: "country.json",
dataType: "json",
successs: function (data) {
$.each(data, function (index, item) {
$.each(item, function (key, value) {
container.append(key + " : " + value + "</br>");
});
container.appendChild("<br/><br>")
});
}
});
});
HTML
<div class="container"></div>
<div id="form-area">
<h2>Get</h2>
<input type="submit" id="get" value="get">
</div>
You can get it like this:-
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<div class="container"></div>
<div id="form-area">
<h2>Get</h2>
<input type="submit" id="get" value="get">
</div>
</body>
</html>
<script type="text/javascript">
var container = $(".container"); //check change here
$("#get").click(function () { //check change here
$.getJSON( "country.json", function( data ) {
var myhtml = ''; // create an empty variable
$.each(data, function (key, value) {
myhtml += key + ' : ' + value + '</br>'; // append data to variable
});
container.append( myhtml); // append the whole data (variable) to div
});
});
</script>
Output (on my local browser):- http://prntscr.com/cq2jjt
Note:- to read data from json file $.getJSON() is required.
Check more detail:- http://api.jquery.com/jquery.getjson/
You need https:\\ to run the Ajax, Simply in local file it will not work. Specially in Chrome. Use the Apache server in your machine and add all your file. And run the application through localhost. Ajax call will fire. Before to that, Try the same application in Firefox one. Firefox might do the ajax locally.
we can acheive this by using jquery library..
$.getJSON( "ajax/country.json", function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$('#form-area').html(items.join(""));
});
I've researched this in depth on stackexchange and I don't think I am making a 'common' mistake, and the other answers have not solved this.
The problem is I am trying to append data to a DEFINITELY existing div of a certain ID. What I DO know is that the div is dynamically generated, and that is probably why it is hidden.
Despite using jquery on I cannot seem to get jquery to find the particular div.
Here is the code:
$(document).ready(function() {
function example_append_terms(data) {
var sender_id = data['sender_id'];
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = '<span data-lemma="' + v['key'] + '" class="lemma">' + v['name'] + '</span>';
$('#' + sender_id + ' .lemmas').append(html);
}
});
}
function example_get_options(data) {
$.ajax({
url: '/example/',
type: 'post',
data: data,
success: function(data) {
//alert(JSON.stringify(data))
example_append_terms(data)
},
failure: function(data) {
alert('Got an error dude');
}
});
return false;
}
$(document).on('click', ".example-synset-option", function() {
var synset = $(this).data('name');
var sender_id = $(this).attr('id')
example_get_options({
'synset': synset,
'sender_id': sender_id,
});
});
});
On clicking a certain div, an action is fired to "get options" which in turn runs an ajax function. The ajax function runs the "replacer" function example_append_terms.
Having tested up to example_append_terms the .each iteration is definitely working. But when I did tested $('#' + sender_id + ' .lemmas').length I continue to get 0.
Where is this jquery newb going wrong?
I fixed it by changing stuff...
For some inexplicable reason fetching the data attribute worked better than the id..
function intellitag_append_terms(data) {
var sender_id = $('*[data-location="'+data['sender_id']+'"] .lemmas');
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = $('<span data-lemma="' + v['key'] + '" class="label label-primary lemma">' + v['name'] + '</span>');
html.appendTo(sender_id)
//$('#' + sender_id).append(html);
}
});
}
I do not understand how to do the right thing.
With this query I get a JSON with the file names:
$.getJSON("http://api.server.com/my/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<div class='accordion-group span4'><div class='accordion-heading'>Video Frame<blockquote><a href='http://server.com/video/?my=" + result.File + "' target='_blank'><img src='http://jpg.server.com/" + result.File + ".jpg' class='img-polaroid'/></a><p>" + result.ListId + "</p><small>" + result.OwnerId + "</small><small>" + result.updatedAt + "</small> </blockquote><a class='accordion-toggle' data-toggle='collapse' data-parent='#accordion2' href='#" + result.File + "'>Share video</a></div><div id='" + result.File + "' class='accordion-body collapse'><div class='accordion-inner'><form class='share_file_form'>Set list<input name='nd' id='user_id' type='hidden'><input name='file' value = '" + result.File + "' type='hidden'><div class='list'></div><input type='text' placeholder='New list'><div class='modal-footer'><button class='share_file_submit'>Share video</button></div></form><div id='user_info_result'></div></div></div></div>");
});
$('#mytile').html(results.join(""));
}
);
With this query I get a JSON with the tag names:
$.getJSON("http://api.server.com/list/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<label class='radio'><input type='radio' name='list' id='" + result.List + "' value='" + result.List + "' checked>" + result.List + "</label>");
});
$('.my_list').html(results.join(""));
}
);
In the end, I need to display a list of files. Next to each file should to show a form with a file name and a list of tags:
$(document).on('click', '.share_file_form', function() {
$('.share_file_form').validate({
submitHandler: function(form) {
$.ajax({
type: "GET",
url: "http://api.server.com/set/",
timeout: 20000,
data: $(form).serialize(),
beforeSend: function() {
$(".share_file_submit").attr("disabled", true);
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
},
success: function(msg){
console.log("Data Saved: " + msg);
$("#share_file_submit").attr('disabled', false);
$("#share_file_submit").html("Share video");
$("#user_info_result_2").html(msg);
},
error: function(msg){
//////////////// $('#user_info_result_2').html("<div class='alert alert-error span3'>Failed from timeout. Please try again later. <span id='timer'></span> sec.</div>");
}
});
}
});
});
All of this works.
The question is how to make sure that each form will work separately?
Now only works the first form. If you press the button on the other forms will still work the first form.
Your mistake is in the way you identify the form on which the user clicked. The following line is the problem:
$('.share_file_form').validate({
Independent of what you clicked on, you always will get the first form with this selector.
Here is what you need instead:
$(document).on('click', '.share_file_form', function(event) {
$(event.target).validate({
submitHandler: function(form) {
hmm. I 'think' I know what you want..
how about wrapping the second call in a method, or perhaps both, ala.
function fireJSON(){
var func1 = function(){
//your first json code
func2(); // call your second json code
}
var func2 = function(){
// second json code
}
return {
func1: func1
}
}
fireJSON().func1();
I have created a dynamic link based on JSON data, The problem I am having, when I click on the links is its not loading the information associated for each of the link.
for example when i click on Algebra it should load the id and author info. But currently it work for only the last link.
How can I make it work for every link so that it loads for each one?
here is my code below:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
var url= 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function(data) {
console.log(data);
//$('.bookname').empty();
var html ='';
$.each(data.class, function(key, value) {
console.log(value.name+ " value name");
console.log(value.desc + " val desc");
$('.bookname').empty();
html+= '<div class="books" id="authorInfo-'+key+'">';
html+= '<a href="#" >'+value.name+ key+'</a>';
html+= '</div>';
$(".bookname").append(html);
var astuff = "#authorInfo-"+key+" a";
console.log(value.desc + " val desc");
$(astuff).click(function() {
var text = $(this).text();
console.log(text+ " text");
var bookdetails =''
$("#contentbox").empty();
$.each(value.desc, function(k,v) {
console.log(v.id +"-");
console.log(v.author +"<br>");
bookdetails+= v.id +' <br> '
bookdetails+= v.author + '<br>';
});
$("#contentbox").append(bookdetails);
});
});
},
error: function(e) {
console.log("error " +e.message);
}
});
</script>
</head>
<body>
<div id="container">
<div class="bookname">
</div>
<div id="contentbox">
</div>
<div class="clear"></div>
</div>
</body>
</html>
The problem is you are updating the inner html of the element bookname in the loop, which will result the previously added handlers being removed from the child elements.
The calls $('.bookname').empty(); and $(".bookname").append(html); within the loop is the culprits here. You can rewrite the procedure as something like this
jQuery(function ($) {
var url = 'sample.json';
$.ajax({
url: url,
dataType: "jsonp",
jsonpCallback: 'jsoncback',
success: function (data) {
var $bookname = $('.bookname').empty();
$.each(data.class, function (key, value) {
var html = '<div class="books author-info" id="authorInfo-' + key + '">';
html += '' + value.name + key + '';
html += '</div>';
$(html).appendTo($bookname).data('book', value);
});
},
error: function (e) {
console.log("error " + e.message);
}
});
var $contentbox = $("#contentbox");
$('.bookname').on('click', '.author-info .title', function (e) {
e.preventDefault();
var value = $(this).closest('.books').data('book');
var text = $(this).text();
console.log(text + " text");
var bookdetails = '';
$.each(value.desc, function (k, v) {
console.log(v.id + "-");
console.log(v.author + "<br>");
bookdetails += v.id + ' <br> ';
bookdetails += v.author + '<br>';
});
$contentbox.html(bookdetails);
});
});
Change
$(astuff).click(function()
to
$(document).on("click", "#astuff", function()
I assume "astuff" is a ID and you forgot the number sign and quotes in your original selector. The jQuery "click" listener only listens for events on elements that were rendered during the initial page load. You want to use the "on" listener, it'll look for events on elements currently in the DOM.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JQuery/Javascript how to Parse HTML using a Get
I have the following code that is working:
$.getJSON('json/shares.json', function(data) {
var items = [];
$.each(data.Shares, function(key, val) {
items.push('<option id="' + val.shareName+ '">' + val.shareName+ '</option>');
});
$('<select/>', {
'id': 'shares_select',
html: items.join('')
}).appendTo('#shares');
});
$.get('lon_shares.html', function(data){
$(data).appendTo('#shares');
});
This will create a dropdown list using a JSON file. I need it to autosubmit when a selection is made and then get the relevant html file, so if they choose "lon" from the dropdown the file is "lon_shares.html" and if they choose "par" it's "par_shares.html" and so on.
I am new to JQuery and Javascript so please give examples of how it needs to look including my code thanks.
//Suppose this is the html
<select id="share-list">
</select>
<div id="shares">
</div>
//this should be in script tag
$.getJSON('json/shares.json', function(data) {
//This clears previous items in the dropdown
$("select#share-list").html('')
$.each(data.Shares, function(key, val) {
$("select#share-list").append('<option value="' + val.shareName+ '">' + val.shareName+ '</option>');
});
});
//Binding a change event to the dropdown
$("select#share-list").change(function(e) {
var el = $(e.currentTarget);
var share_name = el.attr('value');
var page = share_name+'.html';
$.get(page, function(data){
$(data).appendTo('#shares');
});
});
You can trigger submit on form on select box change.
$.getJSON('json/shares.json', function(data) {
var items = [];
$.each(data.Shares, function(key, val) {
items.push('<option id="' + val.shareName+ '">' + val.shareName+ '</option>');
});
$('<select/>', {
'id': 'shares_select',
html: items.join('')
}).appendTo('#shares')
.change(function(){
$('form').trigger('submit');
$.get( this.value +'_shares.html', function(data){
$(data).appendTo('#shares');
});
});
});