How to append a link to a table using Javascript? - javascript

I have an ajax function that calls a method that returns a JSON file. I want to pull the information from the JSON and append it to the table. Which I can do like this:
function updateHome() {
$.ajax({
type: "POST",
url: '#Url.Action("GetHomePage", "Home")',
dataType: 'json',
success: function (result) {
response = $.parseJSON(result)
$(function () {
$.each(response, function (i, item) {
var table = document.getElementById("deviceTable");
var $tr = $('<tr class="accordion" id="'+item.mac+'">').append(
$('<td>').text(item.name),
$('<td>').text(item.loc),
$('<td>').text(item.com),
$('<td>').text(item.status)
).appendTo(table)
});
});
}
});
}
This works as intended. However, I want to make one of the td a link using <a href= but I'm not sure how I can achieve this using .text(). How can I add different HTML elements to this table?
Thanks!

.text sets the text content of your selection. It protects you from unintentionally injecting HTML.
.html sets the html content of your selection. Use that for a HTML string, or alternatively, use .append:
$('<td/>').append(
$('<a/>', { href: '#', text: 'Anchor text' })
)

Related

Get the text inside <h2> element from an ajax jquery post response

Is there any way to get the text inside an element which is a response from an ajax jquery load. I need to get the text inside element which is present inside the response text from ajax page. Following is my ajax code:
var url = '...';
var saveData = $.ajax({
type: 'POST',
url: url,
data: {data : data},
dataType: "text",
success: function (resultData) {
callback(resultData); // need to get the <h2> text here..
}
});
saveData.error(function () {
console.log("Request to API not send");
});
You can pass HTML to jQuery and use it in the same way as if the element was on the DOM, for example with find():
console.log( $(resultData).find('h2').text() );
If your HTML doesn't have a root element then you can wrap it like so:
resultData = '<div>' + resultData + '</div>';
console.log( $(resultData).find('h2').text() );
How about:
$(resultData).find('h2').text()

Unable to hide a imag using .hide()

I have the following view inside my asp.net mvc , which display a ajax-loading imag, which i am trying to hide after starting a jquery function as follow:-
<div id= "geturl" data-url="#Url.Action("ListPackages", "Home")">
<h1>All Processes</h1>
<img id="tobehide" src="~/Content/ajax-loading2.gif" />
<ul id="products">
</ul>
Then the following JavaScript file:-
$(document).ready(function () {
$.ajax({
url: $('#geturl').data('url'),
type: 'GET',
cache: false,
success: function (result) {
$('#tobehide').hide();
$.each(result.data, function (key, val) {
var str = val.packageName;
$('<li/>', { text: str })
.appendTo($('#products'));
});
}
});
});
Currently the data will be filled in the but the loading-imag will not be hiden.so how i can force the imag to hide when the java script starts executing?.
Best Regards
Your code is correct, and should work fine!
Try using FireBug or Chrome developer tools to see what's the javascript error you are getting back from the ajax call.
If that still doesn't help, and you want the image to be hidden regardless, then use the 'complete' callback on the jquery ajax call you are using.
$(document).ready(function () {
$.ajax({
url: $('#geturl').data('url'),
type: 'GET',
cache: false,
complete: function (result) {
$('#tobehide').hide();
$.each(result.data, function (key, val) {
var str = val.packageName;
$('<li/>', { text: str })
.appendTo($('#products'));
});
}
});
});
It should work fine. No mistake in your code Brother.
try adding async option. Set it to false. and try again

how do I access a HTML element from javascript using id,the html element belongs to another html document

Continued from the question title:
also the other html document is loaded in the parent using AJAX,like this:
$.ajax({
url: 'calender.aspx',
cache: false,
dataType: "html",
success: function (data) {
$(".mainBar").html(data);
}
});
I need to get a table from calender.aspx which has id 'tableID';
From within your success callback:
$(data).find("#tableID");
In your example, you appear to be inserting the document into your document via the line $(".mainBar").html(data);. That being the case, you can then just get it via $("#tableId") once you've done that:
$(".mainBar").html(data);
var theTable = $("#tableId");
If your goal is not to append everything, but to do something else, you can build up a disconnected DOM tree by doing $(data), and then search it via find:
var theTable = $(data).find("#tableId");
As a side note, you can just use .load. However, you would do this:
var $table;
$.ajax({
url: 'calender.aspx',
cache: false,
dataType: "html",
success: function (data) {
$table = $(data).find('#tableID');
$(".mainBar").empty().append($table);
}
});
Same thing with .load:
var $table;
$('.mainBar').load('calendar.aspx #tableID', function(html) {
$table = $(html).find('#tableID');
});

Problem with fetching Id of the dynamically generated tag using jquery

I have the following function to display the id for click event of tag for which the items are appended dynamically.but when execute the function my alert does not display the id,it pop up saying undefined.please can any one tell where exactly i am going wrong.
This is my function
function getmenu()
{
$.ajax({
type: "POST",
url: "JsonWebService.asmx/GetMenus",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success:
function (results) {
$(results).find("Menu").each(function () {
var Text = $(this).find("Text").text();
var MenuId = $(this).find("MenuId").text();
var dmenu = $("#Menudiv");
dmenu.append("<td id='" + MenuId + "'><ul>" + Text + "</ul></td>");
});
$("#Menudiv").children('td').click(function () {
alert($(this).children('td').attr('MenuId'));
});
}
});
}
This will be my sample xml code generated on ajax call.
<ArrayOfMenu><Menu><MenuId>1</MenuId><Text>Books</Text></Menu><Menu><MenuId>2</MenuId><Text>Cd</Text></Menu><Menu><MenuId>3</MenuId><Text>Calendar</Text></Menu></ArrayOfMenu>
Change this line:
alert($(this).children('td').attr('MenuId'));
to this:
alert($(this).attr('id'));
That shows the td's id. If you intend to inspect the ul within the td -- and note that you have no li elements within the ul -- you can use "children" as you did above, but you'd need to correct your HTML (<ul><li>...) and change the children selector accordingly... or use find()... depends what you're actually trying to do.

JQuery/ajax page update help pls

Hi Am new to Jquery/ajax and need help with the final (I think) piece of code.
I have a draggable item (JQuery ui.draggable) that when placed in a drop zone updates a mysql table - that works, with this:
function addlist(param)
{
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');}
});
}
but what I cannot get it to do is "reload" another page/same page to display the updated results.
In simple terms I want to
Drag & drop
Update the database
Show loading gif
Display list from DB table with the updated post (i.e. from the drag & drop)
The are many ways of doing it. What I would probably do is have the PHP script output the content that needs to be displayed. This could be done either through JSON (which is basically data encoded in JavaScript syntax) or through raw HTML.
If you were to use raw HTML:
function addlist(param)
{
$.ajax(
{
type: 'POST',
url: 'ajax/addtocart.php',
data: 'img=' + encodeURIComponent(param),
dataType: 'html',
beforeSend: function()
{
$('#ajax-loader').css('visibility','visible');
},
success: function(data, status)
{
// Process the returned HTML and append it to some part of the page.
var elements = $(data);
$('#some-element').append(elements);
},
error: function()
{
// Handle errors here.
},
complete: function()
{
// Hide the loading GIF.
}
});
}
If using JSON, the process would essentially be the same, except you'd have to construct the new HTML elements yourself in the JavaScript (and the output from the PHP script would have to be encoded using json_encode, obviously). Your success callback might then look like this:
function(data, status)
{
// Get some properties from the JSON structure and build a list item.
var item = $('<li />');
$('<div id="div-1" />').text(data.foo).appendTo(item);
$('<div id="div-2" />').text(data.bar).appendTo(item);
// Append the item to some other element that already exists.
$('#some-element').append(item);
}
I don't know PHP but what you want is addtocart.php to give back some kind of response (echo?)
that you will take care of.
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');
success: function(response){ /* use the response to update your html*/} });

Categories