collecting keyvalues from remote json using getJSON - javascript

I'm not very familiar with javascript I hope you can tell me how fix this. I have the the DB table as output in json format, this is a sample:
[{"ID":"11","nombre":"Sapo","direccion":"Chile 11","telefono":"4270044","apertura":"09:00:00","cerradura":"20:00:00","Hint":"sanguche","votos":"3","calificacion":"6.00","actualizacion":"2014-09-15 21:59:43"},{"ID":"12","nombre":"OtroComp","direccion":"San Martin 22","telefono":"456789","apertura":"10:00:00","cerradura":"20:00:00","Hint":"papa al horno y pollo","votos":"2","calificacion":"4.00","actualizacion":"2014-09-15 21:42:01"}]
and this is my code in javascript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" >
var gclaData = 'http://blablabla.com/jsonpuller.php?callback=?';
$.getJSON(gclaData,function(data){
event = 'Next Event Dates<br><br>';
$.each(data.ID, function(j,ID ){
event += '<div class="eventHolder">';
event += '<div class="eventID">'+ data.ID +"</div>";
event += '</div>';
event +='<hr>';
});
$('#output').html(event);
});
</script>
And nothing is shown in the page :-( how can I display all the ID's ?.

Try to change part of the $.each with this;
$.each(data, function(key){
event += '<div class="eventHolder">';
event += '<div class="eventID">'+ data[key].ID +"</div>";
event += '</div>';
event +='<hr>';
});

Related

Traversing to a hidden input element and getting its value

I have a table element that is loaded by jQuery and have a hidden input element on each row of my table and a button to open a pop up.
My problem is that when I try to get the value of hidden input when the button is clicked, I am not getting the value and it says undefined (I have used a jQuery function to get the value in click event of the button)
// function to get the hidden input value
$(document).on("click", '#registerhere', function(event) {
var id = $(this).find('#gameid').val();
console.log(id);
alert(id);
$colinforeg = $('#exampleModal');
$colinforeg.modal('show');
});
// ajax function to load the table
$.ajax({
url: 'allevents.php',
dataType: 'json',
type: 'post',
success: function(data, textStatus, jQxhr) {
console.log(data);
$.each(data, function (i, item) {
console.log(item[0]);
var events = '<tr>';
events += '<td>'+item[1]+'</td>';
events += '<td>'+item[4]+'</td>';
events += '<td>'+item[5]+'</td>';
events += '<td>'+item[6]+'</td>';
events += '<td>'+item[2]+'</td>';
events += '<td>';
events += '<button type="button" class="btn btn-primary" id="registerhere"> Register Here';
events += '</button>';
events += '<input type="hidden" id="gameid" value="'+item[0]+'">';
events += '</td>';
events += '</tr>';
$('#events').append(events);
});
},
Firstly, you are repeating the same id attributes in each appended row which is invalid. If you want to group common elements use classes instead.
With regard to the DOM traversal issues, note that the #gameid element isn't a child of the button, so find() isn't going to work there. You could instead get the closest('tr') and use find() from there:
// function to get the hidden input value
$(document).on("click", '.registerhere', function(e) {
var id = $(this).closest('tr').find('.gameid').val();
console.log(id);
// work with your modal here...
});
// ajax function to load the table
var events = '<tr>';
events += '<td>';
events += '<button type="button" class="btn btn-primary registerhere">Register Here</button>';
events += '<input type="hidden" class="gameid" value="foo">';
events += '</td>';
events += '</tr>';
$('#events').append(events);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table>
<tbody id="events"></tbody>
</table>

How to concat html object to html string using jquery?

I have created a loop and below is the part of the code between that loop
--- Loop Starts ---
var aElement = $('<a>');
aElement.attr('href', '#');
aElement.text(title);
aElement.click(function() {
alert("Hello World);
});
video_list_html += '<tr>' +
'<th scope="row">' + count + '</th>' +
'<td>' + aElement + '</td>' +
'</tr>';
--- Loop Starts ---
But as aElement is an object, it doesn't attach as html tag to the video_list_html but it attaches like this
[object Object]
How do I fix this, so that it attaches inside the video_list_html and also the .click() event stay working.
Try using aElement[0].outerHTML instead of aElement. Leave click handler as is.
The issue is because you cannot append an object to a string. The object gets coerced, ans the result is, as you've seen, [Object object].
A better solution to this problem would be to append the new HTML as one entire string, then use a delegated event handler to catch the events from those dynamically added elements. Try this:
var data = [{
videoId: 'abc123',
title: 'Video #1'
}, {
videoId: 'xyz987',
title: 'Video #2'
}]
var video_list_html = data.map(function(o, i) {
return '<tr><th scope="row">' + i + '</th><td>' + o.title + '</td></tr>';
}).join('');
$('#yourTable').append(video_list_html).on('click', 'a', function(e) {
e.preventDefault();
console.log($(this).data('videoid'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="yourTable"></table>

how do i capture which number <div> got clicked on inside my container <div> and store it in a variable

edit: my code is all held inside a $(document).ready(function() {} because of this, and because my html code is generated inside my javascript file on the fly, i am experiencing issues using .click() when applying the answer that was given to use
$('.movies_cell').click(function(){
var tmp = $(this).index();
});
original:
i have 20 div elements on a page with a class of .movies_cell that are all generated from an ajax file. All of the div's are created within container div called #movies.
any of the .movies_cell div's can be clicked to bring up a modal box, because i am going to place information from my json file in that modal depending on what gets clicked i need to know which div got clicked, for instance, if it was the 5th div i want to know that the 5th div was clicked and then store that number in a variable, if it was the 2nd, or 3rd i want that number to be stored in a variable and then clear when another .movies_cell div gets clicked.
how would i write a javascript or jquery script to accomplish this? :(
thanks!
$('#myMovies').click(function () {
$.getJSON('data/movies.json', function (allData) {
$.each(allData, function (i, field) {
$('#movies').append(function () {
var movies = '<div class="movies_cell">';
movies += '<div class="movies_image">';
movies += '<img src="img/movies/' + (field.image) + '" alt="' + (field.name) + ' Poster" style="width: 100%; height: 100%">';
movies += '</div>';
movies += '<div class="movies_detail">';
movies += '<h1>' + (field.name) + '</h1>';
movies += '<img src="img/rating/' + (field.myRating) + '.png" alt="movie rating" style="margin: auto;">';
movies += '</div>';
movies += '</div>';
counter++;
console.log(counter);
return movies;
});
});
});
});
Use event delegation.(https://api.jquery.com/on#direct-and-delegated-events) At the top
$('#movies').on( "click", ".movies_cell > div", function() {
var tmp = $(".movies_cell > div").index(this);
console.log(tmp);
});
then
$('#myMovies').click(function () {
//rest of code
Can you use .index() ? It is a zero-based index of the collection of items with, for example, class="movies_cell"
$('.movies_cell').click(function(){
var tmp = $(this).index();
});
jsFiddle Demo

how to put a button inside div where data is filled dynamically through $.each function

This should be very simple but i am struggling here.
I have a parent div which have multiple child div. These child div are generated according to $.each() function. Number of times function run, num of div get generated.Now, i want to write a server side function on button click but i am unable to list that button in these child div.
<div class="div1">
<div class="div2">
// this is the button which i cant see in my div2 div
<button type="input">follow</button>
<script type="text/javascript">
$(document).ready(function() {
$.getJSON("/Home/GetUsers", null, function(data) {
$(".div1").html("");
$.each(data, function(i, item) {
var html = "<div class='div2'>";
html += "Name: " + item.UserName + "<br />";
html += item.ArticleCount;
html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>"
html += "</div>";
$(".div1").append(html);
});
});
});
</script>
</div>
</div>
Any type of guidance appreciated.
If you'd like to add a button per child div you can do it in this way:
$(document).ready(function() {
var parent = $(".div1");
$.getJSON("/Home/GetUsers", null, function(data) {
parent.html("");
$.each(data, function(i, item) {
var html = "<div class='div2'>";
html += "Name: " + item.UserName + "<br />";
html += item.ArticleCount;
html += "<img src='" + item.UserImage + "'height='20px' width='20px'/>";
html += "<button type='button' class='newButton'>Click Me!</button>";
html += "</div>";
parent.append(html);
});
});
// In order to ensure that the button click is handled no matter when it was
// added, we can delegate the handler to the parent.
parent.on('click', '.newButton', function(e) {
var button = $(this);
// Handle the individual button click server side call here.
});
});

AJAX/Javascript In a Form and then submit it

I'm php developer starting to get heavier into ajax and I've come across a problem I am not sure how to solve.
I am creating a form on the fly like this:
function addSearchResult(label, tz) {
var html = '';
html += '<div>'
html += '<form id="product-form" >';
html += '<div class="clock">'
html += '<div class="hour"></div>'
html += '<div class="min"></div>'
html += '<div class="sec"></div>'
html += '<input type="text" id="label" name="Label" placeholder="Label">'
html += '</div>'
html += '<div class="city">GMT</div>'
html += '<a href="#" class="whiteButton submit" id="view-product-button" >View</a>'
html += '</form>'
html += '</div>'
var insert = $(html);
$('#search-results').append(insert.data('tz_offset', tz).find('.city').html(label).end());
}
And I am reading the form results like this:
$('#product-form').submit(function() {
alert('OK');
addProduct('Test Value', 'Test Produlct');
$('input').blur();
$('#add .cancel').click();
this.reset();
return false;
});
The problem is, it does not work. If I put the form directly in the html it works fine. But adding it through ajax, it will not pick up that the form exist.
How should I go about solving this problem?
Using the shortcut event handlers (eg submit() or click()) only works for elements which are placed in the DOM on page load.
For dynamically added elements, you need to use delegate(), or on() for jQuery 1.7+. Try this:
< jQ 1.7
$('#search-results').delegate('#product-form', 'submit', function() {
// rest of your code
});
jQ 1.7+
$('#search-results').on('submit', '#product-form', function() {
// rest of your code
});

Categories

Resources