Dynamic Creation of Div inside an array and Appending data to it - javascript

I am fetching result from database and i want too append it to dynamically created div.
for (j = 0; j <= 2; j++)
{
selected = $(".content" + (j + 1));
ajax1(arr[j]);
}
function ajax1(pref) {
$.ajax({
async: false,
url: "../handlers/guestpreference.ashx",
data: { "pref": pref },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: guestsuccess,
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
alert(thrownError);
}
});
}
function guestsuccess(resultset)
{
$.each(resultset, function (i, data) {
$(selected).append('<div class="blogpost" >');
$(".blogpost").append("<div class='blogposth'>");
$(".blogpost").append("<div class='blogpostf'>");
$(".blogposth").append('<font style="font-size:30px; color:blue;padding-left:10px;margin-top:10px;">' + data.Name + '</font>');
$(".blogpostf").append('<font style="font-size:30px; text-align:centre;">' + data.Title + '</font><br>');
$(".blogpostf").append('<font style="text-align:left;float:left;">' + data.Post + '</font><br>');
$(".blogpostf").append('<hr>');
var likes = data.Likes;
if (likes > 0)
$(".blogpostf").append('<font style="font-size:10px;text-align:left;float:left;">' + likes + ' people like it.</font><br>');
else
$(".blogpostf").append('<font style="font-size:10px;text-align:left;float:left;">Nobody like it.</font><br>');
$(selected).append("<br>");
});
}
Here selected holds the class where i have to append .blogpost.
this code is working fine if i have only 1 row of result but in case of multiple result the results are being appended to previously created div.
Since i have CSS for .blogpost .blogposth .blogpostf how can i modify my code so that i can append value uniquely.

create object of div which you append to "selected" . check demo on FIDDLE
$blogpost = $('<div class="blogpost" ></div>');
$blogpost.appendTo('#app');
$blogposth = $("<div class='blogposth'><div>");
$blogpost.append($blogposth);
$blogpostf = $("<div class='blogpostf'><div>");
$blogpost.append($blogpostf);
$blogposth.append('<font style="font-size:30px; color:blue;padding-left:10px;margin-top:10px;">Name</font>');
$blogpostf.append('<font style="font-size:30px; text-align:centre;">Title</font><br>');
$blogpostf.append('<font style="text-align:left;float:left;">POST</font><br>');
$blogpostf.append('<hr>');

Related

JSON parsing and listing data in PhoneGap not working

I'm working on making an API call in PhoneGap. I wrote a function and calling it from a button click event, and I'm getting a response too, but I want to know how to display it. I have tried, but it's not working.
function getContactList() {
console.log("Entering getContactList()");
$.ajax({
url: "https://api.androidhive.info/contacts/",
dataType: "json",
cache: false,
error: function(xhr, ajaxOptions, thrownError) {
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success: function(json) {
console.log("====CONTACTLIST ---->", json);
$(json).find("contacts").each(function() {
var html = '<li>' + $(this).find("name").text() +
' ' + $(this).find("name").text() + '</li>';
$('#contacts').append(html);
});
}
});
}
You're receiving JSON string which is then automatically converted by jQuery to a JavaScript object, so you can interact with it directly and shouldn't convert it to a jQuery object like $(json). Change the code inside your success to this:
for (var i = 0; i < json.contacts.length; i++) {
var c = json.contacts[i];
var html = '<li>' + c.name + ' ' + c.email + '</li>';
$('#contacts').append(html);
}
Note: it seems that there is an error in your code, you're using the find("name") twice. I changed it to name & email, but you can use any property of the contacts that you're getting.

How to set the data in AJAX success function?

I have an ajax call that is returning me the data to be populated in a drop down list. Now, I need to be able to select a value which is returned and set the value of the drop down in the same function if possible. But by using $("#idOfDropDown").val(data), it is not getting set i.e While I am submitting the data, in the database all the options that were returned and populated are getting submitted and not the selected option. So, How do I set the selected value only?
Here's my AJAX function:
$.ajax({
type: "POST",
dataType: 'json',
url: "/Controller/Action",
data: {
param: param,
},
success: function(data) {
if (data.Response == "Unsuccessful") {
console.log("Unsuccessful");
} else if (data.Response == "Successful" || data.Response == "ConditionallySuccessful") {
for (var i = 0; i < data.ExteriorColor.Data.length; i++) {
$("#Exterior_Color").append($("<option></option>").val(data.ExteriorColor.Data[i]).html(data.ExteriorColor.Data[i]));
console.log(data.ExteriorColor.Data[i]);
}
var html = '<ul>'
for (var i = 0; i < data.Options.length; i++) {
html += '<li>' + data.Options[i] + '</li>';
}
html += '</ul>'
$("#twoColumnOptions").append(html);
$("#twoColumnOptions").data(html);
$("#Options").val(data.Options);
$("#Exterior_Color").val(data.ExteriorColor.Data).change(); //Value to be changed
if (data.ExteriorColor.isInstalled == true)
$("#Exterior_Color").attr("disabled", true);
}
},
error: function(result) {
console.log("Error while fetching data");
}
});
Try to trigger the change you made using .trigger('change') like:
$("#Options").val(data.Options).trigger('change');
//Or
$("#Options").val(data.Options).change();
I implemented something similar in my solution and my code is like this, you need to set the value like this:
success: function (response) {
var array = response;
if (array != '') {
for (i in array) {
$("#district").append("<option value='"+
array[i].Id + "'>" + array[i].DistrictName + "</option>");
}
}
},

I have dynamically generated 2 <tr> and I want to get the data of the <tr> I click

The Question might be confusing but this is the exact situation..
I have dynamically generated few ( as per data fetched from database) and now I want to allow the user to select one of the radio buttons and I want to capture the details of the row clicked so please check my code and assist
My ajax code
$.ajax({
data: data,
url: url,
type: 'POST',
datatype: 'JSON',
success: function (response) {
console.log(response);
var result = $.parseJSON(response);
var count = result.length;
for (var i = 0; i < count; i++) {
var $row = $("<tr><input type='hidden' id='"+ result[i].objId + "' value='"+ result[i].objId+"'><td><input type='radio' name='dbRadio' id='dbRadio'></td><td>" + result[i].name + "</td><td> Murgency Global Network</td><td>" + result[i].number + "</td><td>" + result[i].city + "</td><td> 0.5 Km</td></tr>");
$('table.queriedResponder > tbody:last').append($row);
}
console.log($row);
}
});
my radio button detection code
$('input[name=dbRadio]').change(function(){
console.log('clicked');
});
Use an instance of this and get the closest tr:
$('input[name=dbRadio]').change(function(){
console.log($(this).closest("tr"));
});
Of course, if this handler isn't being hit, it's probably because your rows are being added dynamically - so delegate the handler:
$('table.queriedResponder').on('change', 'input[name=dbRadio]', function() {
console.log($(this).closest("tr"));
});

javascript passing values dynamically to a method jquery

$(document).bind('pageinit', function () {
var vendor_id = $.urlParam('vendor_id');
$.ajax({
type: "GET",
url: "http://testservice/testmenu",
data: {
vendor_id: vendor_id
},
error: function () {
alert("Could not get the menu : " + url);
},
success: function parseXml(xml) {
var jsonData = $.parseJSON(xml);
$(jsonData).each(function (index, post) {
$(post).each(function (index, row) {
var finalString = [];
for(var index = 0; index < row.menu.length; index++) {
finalString.push('<div id="collapsibleMenu" data-mini="true" data-role="collapsible" data-inset = "true" data-content-theme="g">');
finalString.push('<h3>' + row.menu[index].category_name + '</h3>');
finalString.push('<ul id="menuDetails" data-role="listview">');
for(var j = 0; j < row.menu[index].products.length; j++) {
var output = ['<li data-icon="addToCart" id="addToCart"> <p>' + row.vendor_menu[index].products[j].prod_name + '</p><p> $' + Number(row.vendor_menu[index].products[j].price).toFixed(2) + '</p>' + '</li>'];
finalString.push(output);
}
finalString.push('</ul></div>');
}
$('#output').append(finalString.join(''));
});
});
$('#output').trigger('create');
}
});
});
function test(prod_id) {
alert("entered test " + prod_id);
addToCart(prod_id, 1);
}
In the following code, where I am doing the following:
<a href="javascript:test("+row.menu[index].products[j].prod_id")">
This is obviously giving me an error. The point is, I need to pass the prod_id dynamically into the javascript test method. I am not sure how to do that. If I just call test without passing prod_id, it works great. Please help!
Try removing the quotes in the argument.
I think I might have figured it out.
Try this.
<a href="javascript:test(\''+row.menu[index].products[j].prod_id+'\')">
This looks like the perfect reason to use a template engine. You might use a Jade template like this:
for post in posts
for row in post
for menu in row.menu
#collapsibleMenu(data-mini="true", data-role="collapsible", data-inset="true", data-content-theme="g")
h3= menu.category_name
ul#menuDetails(data-role="listview")
for product in menu.products
li#addToCart(data-icon="addToCart")
a(href="#", data-product-id=product.prod_id)
p= product.prod_name
p= '$' + Number(product.price).toFixed(2)
Then you can simplify your $.ajax call to:
$.ajax({
// ...
dataType: 'json',
success: function(data) {
$('#output').append(templateFunction(data));
}
});
For the click event, use event delegation:
$('#output').on('click', 'a[data-product-id]', function() {
addToCart(Number($(this).data('product-id')), 1);
});
Easy, yeah? Now change all of your ids to classes, because ids must be unique and yours aren't!

Array and while loop: make unique clickable

I have an array (via ajax) that looks like this:
data[i].id: gives the id of user i
data[i].name: gives the name of user i
I want to output the array like this:
X Leonardo Da Vinci
X Albert Einstein
X William Shakespeare
...
The X is an image (x.gif) that must be clickable. On click, it must go to functiontwo(), passing the parameter data[i].id. Functiontwo will open a jquery dialog with the question "Delete id data[i].id"?
I know this can't be too hard to do, but I can't seem to figure it out...
This is what I have so far:
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
$("." + data[i].id + "").click(function () {
functiontwo(myvar);
});
i++;
}
}
});
}
function functiontwo(id) {
...}
I know why this isn't working. Var i gets populated again and again in the while loop. When the while loop stops, i is just a number (in this case the array length), and the jquery becomes (for example):
$("." + data[4].id + "").click(function () {
functiontwo(myvar);
});
, making only the last X clickable.
How can I fix this?
Thanks a lot!!!
EDIT:
This is my 2nd function:
function functiontwo(id) {
$("#dialogdelete").dialog("open");
$('#submitbutton').click(function () {
$('#submitbutton').hide();
$('.loading').show();
$.ajax({
type : 'POST',
url : 'delete.php',
dataType : 'json',
data: {
id : id
},
success : function(data){
var mess = data;
$('.loading').hide();
$('#message').html(mess).fadeIn('fast');
}
});
//cancel the submit button default behaviours
return false;
});
}
In delete.php there's nothing special, I used $_POST['id'].
As I pointed out in my comment. The problem is the .click part. Either use bind, or use a class for all the elements, and a click-event like this $('.classnamehere').live('click',function () { // stuff });
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=\"clickable\" id=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
i++;
}
}
});
}
$('.clickable').live('click',function () {
alert($(this).attr('id') + ' this is your ID');
});
The usual trick is create a separate function to create the event handler. The separate function will receive i as a parameter and the generated event will be able to keep this variable for itself
make_event_handler(name){
return function(){
functiontwo(name);
};
}
...
$("." + data[i].id + "").click( make_event_handler(myvar) );

Categories

Resources