I get the JSON output on the UI using the below function
$("#idvar").click(function(){
var d1 = document.getElementById("dText");
var d2 = document.getElementById("dJson");
var mytext = d1.textContent;
alert(mytext);
$.post(
url,
{doc: mytext},
function(data) {
console.log(Object.keys(data).length);
d2.textContent = data;
}
);
});
where d1 is the displaying the uploaded input document, d2 for the output generated from processing the document on a model. Currently, I am getting json format. I tried to implement the codes in these posts (Parsing JSON objects for HTML table, Convert json data to a html table), but I get [object, Object] in the text area. Is there a way to convert the json to table.
In the URL text area i get
[{"tag":"a1","relevance":0.5},
{"tag":"a2","relevance":0.3},
{"tag":"c3","relevance":0.2},{"tag":"d3,
...
Instead, I was hoping to get
enter image description here
You should traverse the data and print it in table format. First, make sure the element with id dJson is a <table> element. Then, you can change your success callback to something like:
function(data) {
console.log(Object.keys(data).length);
var html = '<tr><th>Tag</th><th>Relevance</th></tr>';
for(var i=0; i<data.length; i++){
html +=
'<tr>' +
'<td>' +
data[i].tag +
'</td>' +
'<td>' +
data[i].relevance +
'</td>' +
'</tr>'
;
}
d2.innerHTML = html;
}
Here you have a working example (without the $.post call): https://jsfiddle.net/cLbqmwa4/
Related
I have DataTables table with row details which are opening by clicking on row. The row details are displayed in 3 different languages which are selected by checkbox. When the row is clicked, the language is send to details.php script (langy:chLanguage) which returns json values for this selected language.
Initialy the language is set to chDe and everything is working fine until I click on another language. When the language is changed to EN or RU, or even back to DE, the returned json is empty.
index.php :
<h5>Language</h5>
<input type="checkbox" id="chDe" name="languages" checked>DE
<input type="checkbox" id="chEn" name="languages">EN
<input type="checkbox" id="chRu" name="languages">RU
<script>
var chLanguage = "chDe";
$('input[name=languages]').click(function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
chLanguage = [];
$('input[name=languages]:checked').each(function() {
chLanguage.push($(this).attr('id'));
});
if (chLanguage == '') {
chLanguage = 5;
}
$('#example').DataTable().ajax.reload();
});
function format ( rowData, row, $chLanguage ) {
// FOLLOWING CONSOLE.LOG RETURNS THE ACTUALLY SELECTED LANGUAGE CORRECTLY
console.log("chLanguage in format function: " + chLanguage);
var div = $('<div/>')
.addClass( 'loading slider' )
$.ajax( {
url: 'scripts/details.php',
data: {
name: rowData[0],
langy: chLanguage,
},
dataType: 'json',
type: 'post',
success: function ( json ) {
// FOLLOWING CONSOLE.LOG RETURNS [Object object] unless the language is changed, then it returns nothing
console.log("json: " + json);
var childTable = '<div id="rowdetails" class="slidera"><ul class="slider">';
childTable = childTable.concat(
'<div class="row rdstyle">' +
'<table class="detailstable detailserrors">' +
'<tr><td><b>Error class:</b></td><td>' + json[0].ERRTRIEDA + '</td></tr>' +
'<tr><td><b>Error group:</b></td><td>' + json[0].ERRSKUPINA + '</td></tr>' +
'<tr><td><b>Error:</b></td><td>' + json[0].ERRPOPIS + '</td></tr>' +
'</table>' +
'</div>
);
});
}
details.php :
$language = $_POST['langy'];
if ($language == 'chDe' ) {
$setLang = 'DE';
}else if($language == 'chEn') {
$setLang = 'EN';
} else{$setLang = 'RU';}
and $setLang is used in SQL query to filter data by language.
I hope I'm not far away from working solution, because it's working already, just the language switch don't work. Sorry not to attach working sample. I don't know how to implement all these parts including mysql db and several differenct php scripts :(
I have this ajax request that's working on pulling the data I need but I would like to make this a search function that lets the user pull in data as requested. Is there away to take my working code and repurpose it to work with the search box? Not sure how to go about this...
function foodQuery(){
var foodURL = "http://api.example.com/items?key=123456789";
$.ajax({
url: foodURL,
type: 'GET',
contentType: "text/plain",
dataType: 'json',
success: function(json) {
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>' ;
// get itemCode
htmlString += '<h4 class="item_id" >#' + product.itemCode + '</h4>';
// get description
htmlString += '<p class="product_desc">' + product.description + '</p>';
// open price
htmlString += '<div class="price">';
// get price & close div
htmlString += '<span class="dollar"><span class="usd">$</span>' + product.price + '</span> <span class="product_desc">per weight</span></div>'
// close divs
htmlString += '</div>';
//console.log(htmlString);
$('.listing').append( $(htmlString) );
}); //end each
}, // end success
error: function(e) {
console.log(e.message);
$('.listing').append( '<h1 class="errmsg" >Sorry, there was an unkown error.</h1>' );
} // end error
}); // end ajax request
}
It depends on the API that you are using, but assuming the API has a way to search using text, you could have something that looks like the following:
function foodQuery(searchTerm) {
var foodUrl = '/path/to/api?query=' + searchTerm;
$.ajax({
// fill in AJAX call here and callback handling like you are doing
})
}
$('#searchBox').on('keypress', function() {
foodQuery($(this).val());
});
So every time the user types, the function foodQuery() will be run with the current search term. You may want to add some delay so that the API is not hit every time the user types a new character.
First create a text input,
<input type="text" id="search">
Then listen for the keyup event of that input. Get the value of the input as the user is typing (if this is the behavior you want) and call the foodQuery function sending the value of the input as a parameter. Then use this value as the key parameter of the foodURL. Then perform the ajax request the same way you did.
$(function() {
/**
Whenever user types a letter and release the key, its value is passed to the
foodQuery function
**/
$("#search").keyup(function() {
var value = $(this).val();
foodQuery(value);
});
function foodQuery(key) { // key is passed as a parameter
var foodURL = "http://api.example.com/items?key=" + key;
/** Send you ajax request here and manipulate the DOM the same way yo do. Since we are
fetching new products continuously, it is better to clear the .listing element
every-time before you update it. **/
$(".listing").html("");
/**
$.ajax({
url: foodURL,
type: 'GET',
contentType: "text/plain",
dataType: 'json',
success: function(json) { **/
}
});
$.post("Hirarchi/addHirarchi",
{/*'id':hirarchiId,*/'hirarchiName':hirarchiName,'level':HirarchiLevel},
function(data) {
$('#lblMessage').html (data);
$('#txtHirarchiName').val('');
$('#txtHirarchiLevel').val('');
var data = $.parseJSON(data);
$.each(data, function(a,b,c) {
alert(data);
});
});
you can not pass object to alert. If you give object to it, it will [Object Object]. alert parameter must be string
//for Each loop code
$.each(data, function(index,value,list) {
alert(JSON.stringify(value)); //if you want to alert each object then use
//data will not be accessible inside $.each you can access the same using 3rd parameter which list
alert(JSON.stringify(list));
});
But the thing is why you gave alert in $.each and alerting same data.
I'm assuming it is part of some functionality in your code. But that is not good practice to do.
Update 1.
Here is your answer with rendering table.
Code
drawTable(data); /// call this line from your ajax success
function drawTable(data) {
var tData = data.tblHirarchi
for (var i = 0; i < tData.length; i++) {
if (tData[i] != null) {
drawRow(tData[i])
}
}
}
function drawRow(rowData) {
var row = $("<tr />")
$("#personDataTable").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it
row.append($("<td>" + rowData[0] + "</td>"));
row.append($("<td>" + rowData[1] + "</td>"));
row.append($("<td>" + rowData[1] + "</td>"));
}
Fiddle HERE
Instead of print just data, print something like:
alert(JSON.stringify(data));
See, if that solves your problem.
I am currently working on an app to retrieve feeds from a wordpress site and list individual posts in a jquery mobile list format. Below is the JS code:
$(document).ready(function () {
var url = 'http://howtodeployit.com/category/daily-devotion/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&output=json_xml&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function (data) {
var postlist = data.responseData.feed.entries;
var html = '<ul data-role="listview" data-filter="true">';
for (var i = 0; i < 6; i++) {
var entry = postlist[i];
console.log(entry);
html += '<li>';
html += '<a href="#articlepost" onclick="showPost(' + entry.id + ')">';
html += '<div class="etitle">' + entry.title + '</div>';
html += '<div class="esnippet">' + entry.contentSnippet + '</div>';
html += '</a>';
html += '</li>';
}
html += '</ul>';
$("#devotionlist").append(html);
$("#devotionlist ul[data-role=listview]").listview();
}
});
});
function showPost(id) {
$('#articlecontent').html("Loading post...");
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function (data) {
var html = '';
html += '<h3>' + data.post.title + '</h3>';
html += data.post.content;
$('#articlecontent').html(html);
});
}
When I click on any of the 6 posts displayed, only the contents of the first Post gets displayed instead of the contents of the individual posts.
How did I workaround this?
Step1: From my WordPress Permalink Settings, I selected Custom Structure and added /%postname%/%post_id% This means my RSS XML output results for my 'Link' element will be in this format:
<myurl>/<postname>/<postID> (http://howtodeployit.com/xxx/111/)
Step2: To make it easier for me instead of writing a regex query I used a Split command like this:
var postlink = entry.link;
var id = postlink.split(/\//)[4];
(///)[4] would simply split the URL by the number of slashes and take only that 4th bit which is where my postID is.
I hope this comes in handy for others in my position
I have the following code that retrieves Json data:
<script type="text/javascript">
$(document).ready(
function(){
$.getJSON(
'./json.txt',
function(data){
for(i=0; i<data.length; i++){
var content = '<li>';
content += data[i].fname + ' ' + data[i].lname;
content += '</li>';
$('ul.rubrica').append(content);
}
}
);
}
);
</script>
<ul class="rubrica">
</ul>
And the json data:
[
{
"fname" : "<a href='http://www.riccardo.it'>Piottino</a>",
"lname" : "Mr Potato"
}
]
Now I have the json in another server: http://www.site.com/json.txt
How can I use jsonP to get the content like I did before?
Tnx in advance
--Edit: Since I see I have to use a server side language, how can I do it with asp.net?
Details # http://api.jquery.com/jQuery.getJSON/
Example -
$.getJSON("http://www.site.com/json.txt?jsoncallback=?",
function(data) {
for(i=0; i<data.length; i++){
var content = '<li>';
content += data[i].fname + ' ' + data[i].lname;
content += '</li>';
$('ul.rubrica').append(content);
});
You cannot do it with a stand alone JSON file.
When the JQUERY makes a cross domain call for JSON using jsonp, it sends a parameter in the form of a number in the REQUEST parameters array. The JSON that is returned should then be the value of this parameter.
SO you need a php or asp file that reads the REQUEST parameter and gets the value of the parameter (name of parameter i've forgotten- do a print of REQUEST parameter and find it).
e.g. if the parameter value you got in the php REQUEST is 1245563
then your JSON output should be
EDIT:
1245563 = "[
{
"fname" : "<a href='http://www.riccardo.it'>Piottino</a>",
"lname" : "Mr Potato"
}
]";