jquery to append a table to div - javascript

i have a div id.i have to append a table with values to the div.
<div id="testResult" style="padding-left: 120px; "></div>
am doing follwing steps but it is not working.
$.ajax({
url: '/getReports',
cache: false
}).done(function (html) {
if (html != "") {
$('#testResult').show();
var htm = "";
var string1 = '<table border="1"><tr><td>No</td><td>Testcase</td> <td>OS</td> <td>Browser</td> <td>Result</td></tr></table>';
$.each(html, function (i, data) {
string1 + = '<tr><td rowspan="3">1</td><td rowspan="3">' + data.status.test + '</td><td rowspan="3"><!--OS--></td><td>' + data.status.bwser + '</td> <td> ' + data.status.report + ' </td></tr>';
});
$('#testResult ').append(string1);
$("#testResult").html("<br/><br/>");
$("#testResult").html("<p>" + htm + "</p>");
}
}).fail(function () {
$("#testResult").html("Failed to run the test");
$('#edit ').removeAttr("disabled");
});

$("#testResult").html("<br/><br/>") and $("#testResult").html("<p>" + htm + "</p>") will overwrite contents of your "testResult" DIV. So, replace this
$('#testResult ').append(string1);
$("#testResult").html("<br/><br/>");
$("#testResult").html("<p>" + htm + "</p>");
}
with
$('#testResult ').append(string1);
$("#testResult").append("<br/><br/>");
$("#testResult").append("<p>" + htm + "</p>");
}
.append(): Will add or append extra strings to the existing contents of the DIV
where as
.html(): Will removes or overwrite the existing contents of the DIV with newer one.
This is the main difference between .append() and .html().

edit this part
$("#testResult").append("<br/><br/>");
Remove this part-->
$("#testResult").html("<p>" + htm + "</p>");
htm is empty string, as you never concatenate any string to it

Related

ADD #url.action with parameter on Table cell in AJAX

I am new to this and I want to add a action method on table cell. The problem is Table is generated by java-script(AJAX).
Here's code:
$.ajax({
url: "GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "POST",
success: function (obj) {
debugger;
$tbl.empty();
$tbl.append('<tr><th>ID</th><th>Name</th><th>Last Executed Date</th><th>Status</th></tr>');
for (var i = 0; i < obj.length; i++) {
$tbl.append(' <tr><td> ' + obj[i].senderId + '</td><td>' + obj[i].subject + '</td><td>' + obj[i].msg + '</td><td>TESTING</td></tr>');
}
}
});
Now instead of <a href="#"> I want to add Action Method #URL.Action on that <td>. Here's my Action Method:
<a href=#Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+',receiverId='+obj[i].senderId+ })>
But it shows error, I can't use javascript variable obj[i].senderId with c# code #Url.Action("SingleSentShow","Home", new { msgId ='+obj[i].senderId+'...
How can I fix this, or is there any other solution to add link or onClick on Table cell and pass data with it ?
David is right, but a simplified way for easy understanding.
var href = #Url.Action("SingleSentShow","Home", new { msgId ="__msgID__" ,receiverId="__receiverID__" });
href = href.replace("__mgsID__",obj[i].senderId).replace("__receiverID__",obj[i].senderId);
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');
Both will work fine.
Update: As per Comment.
Move the value of href to data-href and set href to # and add a new class for script to work. And when the link is clicked we can swap the values.
$tbl.append(' <tr><td> <a href=# class=Test data-href="' + href + '">' + '... the rest of your line');
And add the below script.
$(document).on('click', '.Test', function () {
$(this).attr('href',$(this).attr('data-href'));
});
You can't mix server-side code and client-side code like that.
One option might be to put the base action URL in a JavaScript variable, and then append your query string parameters to it in JavaScript code. Something like this:
var singleSentShowURL = '#Url.Action("SingleSentShow","Home")';
This would result in something like this client-side:
var singleSentShowURL = '/Home/SingleSentShow';
Then in your loop you could use that variable to manually build the URL. Something like this:
$tbl.append(' <tr><td> <a href="' + singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId + '">' + '... the rest of your line');
You might split it into multiple lines for readability:
var href = singleSentShow + "?msgId=" + obj[i].senderId + "&receiverId=" + obj[i].senderId;
$tbl.append(' <tr><td> <a href="' + href + '">' + '... the rest of your line');

add function onclick in json parse

Im trying to load article from json (its works) and add it link to fucntion, but when I add the a href tag with onclick function (for example - alert), the function doesn't work.
what am I missing?
$.getJSON(categoryAddr,function(data){
json=data;
jQuery(function ($) {
$.each(json, function (i, value) {
var list ="<a href='#' onclick='alert('hey!');'>"
+"<h1>" + value.title + "</h1>"
+ "<img src='" + value.image + "' alt=''/>"
+"<h2>" + value.excerpt + "</h2></a>";
$('.hold').append(list);
});
});
});
you need to escapq quotes inside the alert
change this line
var list ="<a href='#' onclick='alert('hey!');'>"
to
var list ="<a href='#' onclick='alert(\'hey!\');'>"
Use escaped double quotes around your JS
var list ="<a href='#' onclick=\"alert('hey!');\">"
Define onclick event outside instead of defining it inline as shown below
jQuery(function ($) {
var json={title:'title1'};
$.each(json, function (i, value) {
var list ="<a href='#' onclick=\"alert('hey!');\">"
+"<h1>" + value + "</h1>" ;
$('.hold').append(list);
});
});
Fiidle : https://jsfiddle.net/9qes9u8u/
Updated Fiddle based upon #rzr answer
https://jsfiddle.net/t8o56g28/
I would go for delegated events:
var list ="<a href='#' class='link'>"
Now you can use this script, and you don't need to have a nested doc ready block:
$.getJSON(categoryAddr,function(data){
json=data;
$.each(json, function (i, value) {
var list ="<a href='#' data-id='" + value.id +"' class='link'>"
+"<h1>" + value.title + "</h1>"
+ "<img src='" + value.image + "' alt=''/>"
+"<h2>" + value.excerpt + "</h2></a>";
$('.hold').append(list);
});
});
This is delegated event on newly created anchor:
$('.hold').on('click', '.link', function(){
alert($(this).data("id"));
});

How to append data for each div separately

Simple but I dont know how to do it. I am trying to append data for each div separately $. Each function is looping and assigning whole data to the same div.
These are my two div.
<div class="div1">
<div class="div2">
// whole javascript code is here
</div>
</div>
The whole code is something like this:
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function(data)
{
htmlResultData="<br /> " + "Users received from server: " + "<br />";
$.each(data, function (i, item)
{
htmlResultData += item.PostedByName + "<img src='" + item.PostedByAvatar + "'height='100' width='100'/> ";
});
$(".div2").empty().append(htmlResultData);
//however, i have tried to return false here but still same result
return false;
});
});
Div1 contains outer CSS for that particular div2. I want to generate multiple div2 for each data returned from the server. I have tried using return false but still same result. Please tell me how to do it.
This may help you. I have change the code to make it simple.
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function (data) {
//make parent div blank
$(".div1").html("");
$.each(data, function (i, item) {
//make html for div2
var html += "<div class='div2'>";
html += item.PostedByName;
html += "<img src='" + item.PostedByAvatar + "'height='100' width='100'/>"
html += "</div>";
//append all div2 to parent div1
$(".div1").append(html);
});
});
});
$(document).ready(function () {
$.getJSON("/Post/GetPosts", null, function(data)
{
htmlResultData="<br /> " + "Users received from server: " + "<br />";
$.each(data, function (i, item)
{
htmlResultData +="<div class='div2'> item.PostedByName + "<img src='" + item.PostedByAvatar + "'height='100' width='100'/></div> ";
});
$(".div1").empty().append(htmlResultData);
//however, i have tried to return false here but still same result
//return false;
});
});

JQuery PHP & Contenteditible

I am having a problem updating a database field via jquery and php with contenteditible. The ajax.php file just takes my input from the form and updates the database when the user clicks away but for some reason I can never hit the $("td[contenteditable=true]").blur(function(). Is it because I am displaying the html from the js file? If so how can I get the .blur() to run this way?
Here is a snip of my php.
<div id="status"></div>
<div class="row">
<div id="html"></div>
</div>
My js file
$(function(){
var message_status = $("#status");
$("td[contenteditable=true]").blur(function(){
var field_userid = $(this).attr("id") ;
var value = $(this).text() ;
$.post('ajax.php' , field_userid + "=" + value, function(data){
if(data != '')
{
message_status.show();
message_status.text(data);
//hide the message
setTimeout(function(){message_status.hide()},3000);
}
});
});
//snip
});
function updateTable() {
//snip
$.post("controller.php", payload, displayTable);
}
function displayTable(data){
var obj_defect = $.parseJSON(data);
//snip
html += '<thead><tbody>';
for(i=0; i<obj.length; i++) {
html +='<tr>';
html +='<td width="10%">' + obj[i].row1 + '</td>';
html +='<td width="10%">' + obj[i].row2 + '</td>';
html +='<td width="10%">' + obj[i].row3 + '</td>';
html +='<td width="10%">' + obj[i].row4 + '</td>';
html +='<td id="row0:'+obj[i].id+'" contenteditable="true"> ' + obj[i].row5 + '</td>';
html +='</tr>';
}
html += '</tbody></table>';
} else {
html = '<h4>No results found</h4>';
}
}
$("#html").html(html);
}
Your listener must run AFTER the element exists. You currently create the contenteditble td row after you receive the data from your post, which means when you go to assign a listener at page load there is no object in existence yet.
Something like this should work:
$.post("controller.php", payload, displayTable).done(function() {
// now create listener on td[contenteditable=true]
});

Loop through multiple RSS sources and outputting in different divs?

I want to loop through two (possibly more in the future) RSS-feeds and put them in different container divs. I started out with following this question: JQuery Fetch Multiple RSS feeds.
Here's my code.
var thehtml = '';
$(function () {
var urls = ['http://www.gosugamers.net/counterstrike/news/rss', 'http://www.hltv.org/news.rss.php'];
for (var i = 0; i < urls.length; i++) {
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(urls[i]),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (xml) {
values = xml.responseData.feed.entries;
console.log(values);
$.each(values, function(idx, value){
thehtml += '<a class="news-item" href="' + value.link + '" title="' + value.title +'" target="_blank"><p>' + value.publishedDate + '</p><h3>' + value.title + '</h3></a><hr>';
});
$("#content_1").html(thehtml);
}
});
}
});
I load two RSS feeds and in the console output I can see the two data arrays.
Right now I use $(#content_1).html(thehtml); to output the feed data as HTML in a container div, #content_1.
What I want to do is to put the first RSS-feed into #content_1 and the second into #content_2. I tried using .slice(0,10) but couldn't get it to work and it doesn't seem like the best way.
Here is the interval in place. The container content will empty to display the new data.
Update: Ajax results target content_1 and content_2 with optional second method.
$(function () {
function GetFeeds(){
var urls = ['http://www.gosugamers.net/counterstrike/news/rss', 'http://www.hltv.org/news.rss.php'];
urls.forEach(function(Query){
$.ajax({
type: "GET",
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q='+encodeURIComponent(Query),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(xml) {
//--Target ID's By content_1/2
var Content=parseInt(urls.indexOf(Query))+1;
$("#content_"+Content).html('');
$.each(xml.responseData.feed.entries, function(idx, value){
$("#content_"+Content).append('<a class="news-item" href="' + value.link + '" title="' + value.title +'" target="_blank"><p>' + value.publishedDate + '</p><h3>' + value.title + '</h3></a><hr>');
});
//---------------
//--Target ID's By Domain (Method Two)
/*
$("#"+Query.split('.')[1]).html('');
$.each(xml.responseData.feed.entries, function(idx, value){
$("#"+Query.split('.')[1]).append('<a class="news-item" href="' + value.link + '" title="' + value.title +'" target="_blank"><p>' + value.publishedDate + '</p><h3>' + value.title + '</h3></a><hr>');
});
-----------------------------------*/
}
});
});
}
//Call GetFeeds every 5 seconds.
setInterval(GetFeeds,5000);
//Page is ready, get feeds.
GetFeeds();
});
#content_1{float:left;width:40%;overflow:hidden;border:solid 2px blue;}
#content_2{float:right;width:40%;overflow:hidden;border:solid 2px yellow;}
/* Method Two Styles
#gosugamers{float:left;width:40%;overflow:hidden;border:solid 2px green;}
#hltv{float:right;width:40%;overflow:hidden;border:solid 2px red;}
*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="content_1"></div>
<div id="content_2"></div>
<!-- Method Two Elements
<div id="gosugamers"></div>
<div id="hltv"></div>
-->
If you don't understand any of the source code above please leave a comment below and I add any necessary comments/notes. Appreciation is shown by marking answers
I hope this helps. Happy coding!

Categories

Resources