Dynamically list and click event - javascript

I need to make list (like ng-repeat in angularjs) and click on any of item in list, call function with passed data of the selected item
I make list with $.ajax call and $.each
$(document).ready(function() {
var inHTML = "";
$.ajax({
url: 'http://some.some',
dataType: "json",
success: function(data){
$("#dynamicTable").append('<tr><th><h5 style="margin-left: 15px; margin-top: 15px;">' + "Events" + '</h5></th></tr>');
$.each(data.videos, function(key, value){
$("#dynamicTable").append('<table><tr><td class="aktivniItem backgroundIdKlupa_izbornik_td" style="color: white">'+ moment(value.time).format('DD-MM-YYYY HH:mm:ss') +'</td><tr></table>').click({param1: value.href}, setSourceToVideoPlayer);
});
function setSourceToVideoPlayer(event){
alert(event.data.param1);
}
}
});
});
and in HTML
<table id="dynamicTable" class="table-hover"></table>
Problem is, with this code, when I click on any of item in list I get alert with passed datafor all items, one-by-one, not only for clicked.

Please try below code. I have given the only idea, it might be possible some syntax error.
$(document).ready(function() {
var inHTML = "";
$.ajax({
url: 'http://some.some',
dataType: "json",
success: function(data){
$("#dynamicTable").append('<tr><th><h5 style="margin-left: 15px; margin-top: 15px;">' + "Events" + '</h5></th></tr>');
$.each(data.videos, function(key, value){
$("#dynamicTable").append('<table><tr><td class="aktivniItem backgroundIdKlupa_izbornik_td" data="' + value.href + '" style="color: white">'+ moment(value.time).format('DD-MM-YYYY HH:mm:ss') +'</td><tr></table>');
});
$(".aktivniItem").click(function (){
alert($(this).attr("data"));
});
}
});
});

Only way I can get this to work, for now, is with event.stopImmediatePropagation();
function setSourceToVideoPlayer(event){
alert(event.data.param1);
event.stopImmediatePropagation();
}
Here is detail about this. If this is not a good way to do this, pls tell me. Thnx

Related

I want to set a url inside my ajax call back function

I want to make a clickable link in my ajax success response. But I could not do this.
<td id="attachment"></td>
function DoAction(id) {
$.ajax({
type: "get",
url: "/view_message",
data: "id=" + id,
dataType: 'json',
success: function(data) {
if (data) {
var text = "No Files There !";
$('#myModal').modal('show');
$('#subject').text(data.subject);
$('#body').text(data.body);
$('#created_at').text(data.created_at);
if (data.attachment) {
$('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
} else {
$('#attachment').text(text);
}
}
}
});
}
I want to display a clickable link in my .
I always encounter this when using ajax calls so;
Update your code from this.
$('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
To This.
$(document).find('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
if the code doesn't work add a console.log("working") function to see if your code is really reaching the success function.
I hope it helps.

How to use pass ajax data that is displaying in html?

I have a question, that I can't seem to find the 'best' solution for my question.. I have an AJAX call that displays data in the DOM, via jQuery.
JSON
[{
"id":"123"
},
{ "id":"456"
}]
JS
$(document).ready(function() {
$.ajax({
url: 'get/data',
dataType: 'json',
data: '{}',
success: function(data) {
var html = '';
$.each(data, function(i) {
html += '<p>My ID: ' + data[i].id + '</p>';
}
$('#id').append(html);
},
error: function(err) {
console.log(err);
}
})
});
As you can see I am displaying that data here. I would like to pass that ID to another AJAX call by selecting a checkbox and pushing a button or perhaps clicking a link. Whats the best way to accomplish this?
EDIT: I apologize, my actual issue is related to array data. I have updated the code. I am displaying an JSON array in the html now, and I want to pass the id of the user/row that I click?
Thanks,
Andy
$(document).ready(function() {
var resid;
$.ajax({
url: 'get/data',
dataType: 'json',
data: '{}',
success: function(data) {
resid = data.id;
var html = '';
html += '<p>My ID: ' + data.id + '</p>'; $('#id').append(html);
},
error: function(err){
console.log(err);
}
});
$('link').click(function () {
// pass id to second ajax
});
});
try jquery-template
https://github.com/codepb/jquery-template
hope help you

Checkbox jquery change function is not working and no errors

I have a list of items and I want to do something whenever one of the items is selected, but the problem is that the check-box's change function is not working with me.
I have checked the code inside the function and it's working fine outside the change event. i'm not sure of the reason why it's not working but what could it be other than the function its self ?
Here the change function:
$("input[name='checkCoResult']").change(function () {
if (this.checked) {
$("#searchResultSecond").attr("style", "opacity: 0.6");
$("#searchResultSecond *").attr("disabled", "disabled").off('click');
}
});
and this is the code that generate my list:
$.ajax({
url: "CCDMSWebService.asmx/getCoSearchResult",
data: JSON.stringify(objectData),
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var Result = response.d;
contantDiv.text("");
$.each(Result, function (index, val) {
contantDiv.append('<div class="panel-bod"><label style="margin:2px; border-radius: 10px;border: 1px solid #cc0000;padding: 5px;"><input type="checkbox" value="' + val.companyID + '" name="checkCoResult" class="nnn"> '
+'<img src="images/' + val.companyID + '.png" alt="company logo" width="30%" height="30%">' + val.companyName + ' provides all your needs</label></div>');
})
},
failure: function (msg) {
alert(msg);
}
});
You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content). In your case it seems you already have a div named contantDiv present in your page, so modify your code like
contantDiv.on("change","input[name='checkCoResult']",function(){ ...
Check out http://api.jquery.com/on/#direct-and-delegated-events for more details.
if your content is dynamic then try
$(document).on("change","input[name='checkCoResult']",function(){
// your code
});

Onclick function on div not working

I have a function for getting records from database on keyup event.
Here is my code:
function displaySearch(key) {
$.ajax({
type:"POST",
url:"searchprofile.php",
data:{
k:key
},
success:function(data){
var details_arr=data.split("+");
$('.searchresult').empty();
for(var i=0;i<details_arr.length-1;i++){
$('.searchresult').append("<div class='profile' id='searchprofile'><img class='profilepic' src='images/profile.jpg'/><div class='doctorname'><div class='pname' onclick='saveName("+details_arr[i]+")'>"+details_arr[i]+"</div></div></div>");
$('.searchresult').show();
$('.searchresult .profile').show();
}
details_arr.length=0;
}
});
}
But i am getting javascript error here saying "Unexpected token ILLEGAL".
How do i give the onclick function with the value of details_arr[i]?
Please help.
As you have jQuery, you really shouldn't inline code. As you see it makes it more difficult to handle quotes inside quoted strings (yes, you're missing quotes around your argument to saveName).
You may do this :
(function(i){
$('.searchresult').append(
"<div class='profile' id='searchprofile'>"
+ "<img class='profilepic' src='images/profile.jpg'/>"
+ "<div class='doctorname'>"
+ "<div id=someId class='pname'>"+details_arr[i] // <- give some Id
+"</div></div></div>"
);
$('#someId').click(function(){saveName(details_arr[i])});
})(i);
$('.searchresult').show();
Note that I used a closure to ensure that i has the needed value in the callback (not the value at end of iteration).
Be careful with the split: on most browsers "+aaa".split('+') makes ["", "aaa"] and as you don't iterate up to the end of the array, this sample string would made you iterate on nothing.
function openNow(x)
{
var pageUrl = '<%=ResolveUrl("~/OnFriends.php")%>'
$.ajax({
type: "POST",
url: pageUrl + '/CreateNew',
data: '{k: "'+ x +'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(data)
{
<---Now Do Your Code Hear--->
}
});
}
CreateNew is my web service what i created in .php file
I would use something like that
bare in mind ID must be unique inside a document (HTML Page)
because the content is generated on the fly; it's better to use the JQuery "on"
$(".pname").on("click", function (event) {
saveName($(this).text());
});
event handler to bind the click event
function displaySearch(key){
$.ajax({
type: "POST",
url: "searchprofile.php",
data: {
k: key
},
success: function(data) {
var details_arr = data.split("+");
var searchResults = "";
for (var i = 0; i < details_arr.length - 1; i++) {
searchResults += "<div class='profile'>" +
"<img class='profilepic' src='images/profile.jpg'/>" +
"<div class='doctorname'>" +
"<div class='pname'>" + details_arr[i] +
"</div></div></div>";
}
$('.searchresult').html(searchResults).show();
}
});
}
$(".pname").on("click", function (event) {
saveName($(this).text());
});
use the Jquery html to replace everything inside searchresult outside the loop that way it
will be called once not details_arr.length - 1 times
you should tell the line at which you are getting error
i think you did not specified you web service in ajax call at...
"url:"searchprofile.php"
Finally got the onclick function working. :)
Instead of appending the div everytime, i just editted my php page by adding the html i needed in the data that is returned in ajax.

Using Ajax callback variable values in JQuery dynamic click handlers

I'm doing a simple ajax query which retrieves a variable-length list of values as JSON data. I'm trying to make a list based on this data which has click-functions based on the values I got from the JSON query. I can make this work just fine by writing the onClick-methods into the HTML like this:
function loadFooList() {
var list_area = $("#sidebar");
list_area.html("<ul>")
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosesfoo" + item.id;
list_area.html(list_area.html()
+ "<li> <a href='#' onClick='alert(\"" +
link_id + "\");'>" +
item.name + "</a></li>");
});
list_area.html(list_area.html() + "</ul>");
}
});
}
I don't like writing the onClick-function into the HTML and I also want to learn how to create this same functionality via JQuery click-function.
So the problem is obviously variable-scoping. My naive attempt here obviously won't work because the variables are no longer there when the click happens:
function loadFooList2() {
var list_area = $("#sidebar");
var link_ids = Array();
list_area.html("<ul>")
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosefoo" + item.id;
list_area.html(list_area.html()
+ "<li> <a href='#' id='" + link_id + "'>"+item.name+"</a></li>");
link_ids.push(link_id);
});
list_area.html(list_area.html() + "</ul>");
for (link_index=0; link_index<link_ids.length; link_index++) {
$("#" + link_ids[link_index]).click(function() {
alert(link_ids[i]);
});
}
}
});
}
Obviously I'd like to do something else than just alert the value, but the alert-call is there as long as I can get that working and move forward.
I understand that I'll have to make some kind of handler-function to which I pass a state-variable. This works for a single value (I can store the whole link_ids array just fine, but then I don't know which of them is the right value for this link), but how would I do this for arbitrary-length lists?
Here is an example from JQuery docs which I'm trying to copy:
// get some data
var foobar = ...;
// specify handler, it needs data as a paramter
function handler(data) {
//...
}
// add click handler and pass foobar!
$('a').click(function(){
handler(foobar);
});
// if you need the context of the original handler, use apply:
$('a').click(function(){
handler.apply(this, [foobar]);
});
And I quess the last example here, "if you need the context of the original handler..." would probably be what I want but I don't know exactly how to get there. I tried to store the current link_id value into this, use it from this in the applied function (using apply()) but I didn't succeed. The necessary values were still undefined according to FireFox. I'm using JQuery 1.3.2.
So what's the right solution for this relatively basic problem?
Use append instead of html():
function loadFooList() {
var ul = $('<ul>');
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosesfoo" + item.id;
var a = $('<a>').attr('href','#').bind('click', function(e) {
alert(link_id,item_name);
e.preventDefault();
});
$('<li>').append(a).appendTo(ul);
});
ul.appendTo('#sidebar'); // this is where the DOM injection happens
}
});
}
So the problem appears to be getting the link id associated with the link so that your click handler has access to it. Note that if it's alphanumeric it will qualify for the id attribute and you can extract it from there. If it is purely numeric, it will be an illegal id attribute. In that case, you can either use an attribute, like rel, or the jQuery.data() method to store the link id with the link. You can also simplify by using append. I'll show both examples.
var link = $("<li><a href='#' id='" + link_id + "'>" + item.name + "</a></li>";
link.click( function() {
alert( $(this).attr('id') );
});
list_area.append(link);
or (if numeric)
var link = $("<li><a href='#'>" + item.name + "</a></li>";
link.data('identifier', link_id )
.click( function() {
alert( $(this).data('identifier') );
});
list_area.append(link);
Try this:
function loadFooList() {
var list_area = $("#sidebar");
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
var out = '<ul>';
$.each(json, function(i, item) {
var link_id = "choosefoo" + item.id;
out +="<li><a href='#' id='" + link_id + "'>"+item.name+"</a></li>";
});
out +="</ul>"
var $out = $(out);
$out.find('a').click(function(){
var link_id = this.id;
var item_name = $(this).text();
alert(link_id);
alert(link_name);
})
list_area.html($out);
}
});
}
Using multiple appends causing the browser to redraw multiple times in a row. You only want to modify the dom once.

Categories

Resources