Display data in dynamically created div using jquery - javascript

I want to display data function name and function description from database and display it in div which will be created dynamically using jquery. How can I display data with dynamic div using jquery...
code for dynamically created div is:
$(document).ready(function () {
$.ajax({
type: "POST",
url: 'FunctionListing.aspx/CountFunction',
data: "{}",
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
//alert(result.d);
for (var i = 1; i <= result.d; i++) {
$('body').append("<div id='div" + i + "' />");
}
},
error: function (result) {
alert(result);
}
});
});

dataType :"json"
Not datatype :"json"
Hope, it'll helps you.

Related

Populate Ajax response with clickable elements that fires another Ajax with correct parameters

So i have a function running an Ajax call that receives data and populate that as a table.
The response contains some rows with data and i now want to add a small fontawsome icon that when clicked fires another function with a parameter.
So i have this:
var latestprecasedata = '';
function getPreCaseData() {
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/GetPreCase",
dataType: "json",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;
data = $.parseJSON(data);
$("#PreCaseTblBody").html("");
for (var i in data) {
$("#PreCaseTblBody").append("<tr><td>" + data[i].pSubject + "</td><td><span class='preplus' id='" + data[i].pID + "'><i class='fa fa-plus'></i></span></td><td>-</td></tr>");
}
if (latestprecasedata !== response.d) {
$("#precasestatus").removeClass("titleupd1").addClass("titleupd2");
latestprecasedata = response.d;
}
else {
$("#precasestatus").removeClass("titleupd2").addClass("titleupd1");
}
}
$("#PreCaseTblBody tr:odd").css('background-color', '#f9f9f9'); //
$("#PreCaseTblBody tr:even").css('background-color', '#f1ffee');
setTimeout(getPreCaseData, 10000);
}
});
}
This works and every 10 seconds data is repopulated. (Maybe not the fastest solution, but it works..)
As you all can se i have a span with class=preplus and id of a unique value coming from my Ajax response. When inspecting the page i can see that every row from my Ajax response have a unique id.
For example two row looks like this:
<tr><td>Cables</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
<tr><td>Skrews</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
So now i have the data populated with span containing a unique id that i want to pass to another function.
I've tried span, div, buttons but the only one time I actually got a event fire was when i placed my second function inside the
for (var i in data) {
... and i know, that's not right at all because all rows contained the last id obviously...
So my other function resides outside my first function and look like this (I've tried many different methods to get the id of my span but for now, I'm here)
$(".preplus").click(function () {
var qID = $(this).attr('id');
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/UpdateQ",
dataType: "json",
data: "{'qid':'" + qID + "','pm':'plus'}",
success: function (data) {
}
});
return false;
});
Please guide me.

Repopulating Image Picker select control with new data after ajax call

I am using this Image Picker jQuery plugin (http://rvera.github.io/image-picker/) and I'm facing a problem with the following:
Repopulating the select control with new data after ajax call.
$.ajax({
type: "GET",
url: requestURL,
dataType: 'json',
success: function(result)
{
$.each(result, function(i, obj) {
console.log(obj.description);
$('#cake-filling-types-select')
.append($("<option data-img-src='" + obj.image + "'></option>")
.attr("value", obj.code)
.text(obj.description));
});
$("#cake-filling-types-select").imagepicker({
show_label : true
});
$("#cake-filling-types-select").data("picker").sync_picker_with_select();
}});
For more details please find the issue here: https://github.com/rvera/image-picker/issues/79
Thanks.
The issue is solved. With the help of #ArmindoMaurits # GitHub, so using the ' $("#cake-filling-types-select").empty();' is fine for clearing this plugin select.
Also, for the other issue where some items are not getting into the select control, I found that these the ones that is missing the img src.
Updated working code:
`$.ajax({
type: "GET",
url: requestURL,
dataType: 'json',
success: function(result){
$("#cake-filling-types-select").empty();
$.each(result, function(i, obj) {
if(obj.image != null)
{
var imgSrc = obj.image;
}else{
imgSrc = '';
}
$('#cake-filling-types-select')
.append($("<option data-img-src='" + imgSrc + "'></option>")
.attr("value", obj.code)
.text(obj.description));
});
$("#cake-filling-types-select").imagepicker({
show_label : true
});
}});`

Change label text on mouse over with ajax

I want to change the value of a label on mouse over. This is what I have done so far:
$(function () {
var hoverOff = "";
$("[id*=GV] td").hover(function () {
hoverOff = $("label", $(this).closest("td")).text();
$.ajax({
type: "POST",
url: "MyMethode.aspx/GetNewValue?text=" + hoverOff,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("label", $(this).closest("td")).html(data.d);
}
});
},
function () {
$("label", $(this).closest("td")).html(hoverOff);
}
);});
At the beginning I save the current text in hoverOff and send that value to the method GetNewValue wich returns the new value and inside ajax success I want to apply that value to the label. The problem is that the text for label never changes, although data.d contains the new text. Should I use something else instead of .html()?
this inside ajax callback isn't referring to the current hovered TD but to the jqXHR object. You can use $.ajax context option:
context: this,
BTW, $(this).closest("td") is quite unrelevant because obviously, even you have nested TDs, $(this).closest("td") will always return the current TD, so you could just use this:
hoverOff = $("label", this).text();
And data: "{}", could be data: {},, no point of setting a string here. >> because you are setting contentype to JSON
It's a context problem you can't use this inside success function, try this code:
$(function () {
var hoverOff = "";
$("[id*=GV] td").hover(function () {
var label = $("label", $(this).closest("td"));
hoverOff = label.text();
$.ajax({
type: "POST",
url: "MyMethode.aspx/GetNewValue?text=" + hoverOff,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
label.html(data.d);
}
});
},
function () {
label.html(hoverOff);
}
);});
You could use this solution from https://stackoverflow.com/a/10701170/3421811
$('.btn').hover(
function() {
var $this = $(this); // caching $(this)
$this.data('initialText', $this.text());
$this.text("I'm replaced!");
},
function() {
var $this = $(this); // caching $(this)
$this.text($this.data('initialText'));
}
);

Json data from Guardian API

I have a guardian json data feed that I want to pull into my page online.
http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz
I have used this javascript but nothing seems to be working to grab the right content from the json;
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz",
success: function(data) {
for (var i = 0; i < 12; i++) {
$("#cuban-news").append("<div class='guardian'><a target='_blank' href='" + webTitle + "'>Link</a></div>");
}
console.log(data);
}
});
});
This is not throwing anything in terms of errors.
Am I better using a js service like backbone or underscore?
Any help would be amazing on this.
Use
data.response.results[i].webTitle
instead of
webTitle
error was
Uncaught ReferenceError: webTitle is not defined
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "http://content.guardianapis.com/world/cuba?format=json&show-fields=trail-text%2Cheadline&order-by=newest&api-key=c3rr449rqqebmuxua9k5mdcz",
success: function(data) {
for (var i = 0; i < data.response.results.length; i++) {
$("#cuban-news").append("<div class='guardian'><a target='_blank' href='"
+ data.response.results[i].webTitle + "'>Link</a></div>");
}
console.log(data);
}
});
});​
JSFiddle

How to ensure that a function is executed completely, before navigating to another page?

I'm removing certain records using a webservice. The jquery ajax request is written in the onclick of a hyperlink. When im executing the script, line by line using firebug, it's getting removed otherwise it's not. Does any one meet any situation like this before? Please help
Code sample:
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
jQuery ajax functions return deferred objects, thus we return $.ajax. Then you should use deferred.done to execute the callback when the AJAX is fully finished. When the AJAX is done, navigate away using JS instead:
var func = function() {
...
return $.ajax({...}); //return our ajax deferred
}
$(".target").click(function() {
var target = this; //preserve "this" since this in the callback may be different
func().done(function(){ //our done callback executed when ajax is done
window.location.href = target.href; //assuming .target is a link
});
return false; //prevent the natural click action
});
You can use the async: false on the ajax call that is wait there to complete the call.
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: false,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
Alternative you can make the submit after the request.
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
return false;
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: true,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
$("#YourFormID").submit();
}
//Event that'll be fired on Success
});
}
Simply move the Event to the "success" handler in your ajax request:
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed");
//Event that'll be fired on Success
}
});
Alternatively use jQuery ajax callback methods.

Categories

Resources