Working with JSON input - javascript

I'm trying to get a JSON input with AJAX and load it in a select control.
but when I run it :\ It stuck on "Downloading the recipes....".
anyone see the problem maybe? (I tried couple of changes but nothing work so far)
1 more issue can anyone think on a shorter way to do the
ConvertToTable(targetNode)
cuse it's way to long and complex, I think :\
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
document.getElementById("span").style.visibility = "visible";
document.getElementById("span1").style.visibility = "hidden";
document.getElementById("button").style.visibility = "hidden";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
result = xmlhttp.responseText;
result = eval('(' + result + ')');
txt = "<select onchange='ShowRecipeDetails(this)'>";
for (i = 0; i < result.length; i++) {
txt = txt + "<option VALUE=" + result[i].recipe + ">" + result[i].recipe + "</option>";
}
txt = txt + "</select >";
document.getElementById("span").style.visibility = "hidden";
document.getElementById("span1").style.visibility = "visible";
document.getElementById("myDiv").innerHTML = txt;
}
}
xmlhttp.open("POST", "http://food.cs50.net/api/1.3/menus?meal=BREAKFAST&sdt=2011-03-21&output=json", true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.send();
}
function ShowRecipeDetails(event) {
// get the index of the selected option
var idx = event.selectedIndex;
// get the value of the selected option
var field = event.options[idx].value;
$.ajax({
type: "GET",
url: "http://food.cs50.net/api/1.3/recipes?&output=json&id=" + field,
success: function (data) {
$("#TableDiv").html(ConvertToTable(data[0]));
}
});
}
function ConvertToTable(targetNode) {
var table = "<table border = 1 borderColor =green>";
table += "<tr>";
table += "<td>" + "ID" + "</td>";
table += "<td>" + targetNode.id + "</td>";
table += "</tr>";
table += "<td>" + "Ingredients:" + "</td>";
table += "<td>" + targetNode.ingredients + "</td>";
table += "</tr>";
table += "<td>" + "Name:" + "</td>";
table += "<td>" + targetNode.name + "</td>";
table += "</tr>";
table += "<td>" + "Size:" + "</td>";
table += "<td>" + targetNode.size + "</td>";
table += "</tr>";
table += "<td>" + "Unit" + "</td>";
table += "<td>" + targetNode.unit + "</td>";
table += "</tr>";
table += "<td>" + "VEGETARIAN:" + "</td>";
table += "<td>" + targetNode.VEGETARIAN + "</td>";
table += "</tr>";
table += "</tr>";
table += "</table>"
return table;
}
</script>
and the HTML:
<button id="button" type="button" onclick="loadXMLDoc()" >Get all recipes</button>
<br />
<span id="span" style="visibility:hidden">Downloading the recipes....</span>
<span id="span1" style="visibility:hidden">Please choose a recipe ID to view</span>
<div id="jsonDiv"></div>
<div id="myDiv"></div>
<div id="TableDiv"></div>

The HarvardFood API also supplies a JSONP version. So if you change your URL to this:
http://food.cs50.net/api/1.3/menus?meal=BREAKFAST&sdt=2011-03-21&output=jsonp&callback=parseResponse
you can create a parseResponse function to handle the data that comes back, and you can do the AJAX by inserting a script tag.
The problem is that you're running afoul the Same Origin Policy.
I see that you've updated the question to use jQuery AJAX. That offers a jsonp data type, which might be easier than adding a script tag.

Related

Get return true values using if else statements in jquery

I want to get true values from the if/else statement using jQuery. I apply this code but I can't get the required output. It displays both true and false values.
$.each(response, function(index, value) {
var user = (user_id == value.User_id);
if (user_roll == 'Customer' && user) {
if (user === true) {
//alert(user === true);
html += "<tr data-id='" + value.ticket_id + "'>";
html += "<td>" + value.ticket_id + "</td>";
html += "<td>" + value.User_id + "</td>";
html += "<td>" + value.User_name + "</td>";
html += "<td>" + value.Customer_name + "</td>";
html += "<td>" + value.subject + "</td>";
html += "<td>" + value.priority + "</td>";
}
}
The response is this : [The response I got][1]
[1]: https://i.stack.imgur.com/oePac.png . I want to get only User_id = 1 records
try comparing the string values together. Sometimes what happens is one of the id that you pass is read as String.
So ,
user_id.toString() == value.User_id.toString()
this is what I do in Javascript to compare id, please check how to convert into String in jquery.

How to wrap code in a function correctly?

I have a code that automatically creates a table for me. It gathers information from a saved file, however, I have two of these files and currently can call one at the time. How can I possibly wrap this code in a function so that there are two calls on the same code with different information that will be put in it? So right now I am using getElementById on file "house-data" but I also want to have this same js on a file "senate-data"
I thought of creating some sort of if statement where if(you have one file): do this
else
do that. But this method doesnt work.
var table = "";
var cols = 1;
var members = data.results[0].members;
var rows = members.length;
table += "<tr>" +
"<th>" + "Full Name" + "</th>" +
"<th>" + "Party" + "</th>" +
"<th>" + "State" + "</th>" +
"<th>" + "Seniority"+ "</th>" +
"<th>" + "Total Votes"+ "</th>" + "</tr>";
for (var r = 0; r < rows; r++) {
table += "<tr>";
for (var c = 0; c < cols; c++) {
table +=
"<td>" + members[r].first_name +", "+
(members[r].middle_name || " ") +" "+
members[r].last_name + "</td>";
table += "<td>" + members[r].party + "</td>" + "<td>" + members[r].state + "</td>" + "<td>" + members[r].seniority + "</td>";
if (members[r].votes_with_party_pct === undefined) {
table += "<td>" + "-" + "</td>"
} else {
table += "<td>" + members[r].votes_with_party_pct + "%" + "</td>"
}
}
table += "<tr>";
}
document.getElementById("house-data").innerHTML = JSON.stringify(table);
function tableCreator(elementID, data) {
[...]
document.getElementById(elementID)[...]
}
above will work for you and keep in mind to check
var members = data.results[0].members;
is available before going to for loop

how to select attributes to show (name, height,weight ) swapi.co

shows all the attributes, I need only name weight growth, eye color, skin color and gender
url = "https://swapi.co/api/people";
function heroes () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
console.log(data); // see object
}
document.getElementById('demo').innerHTML = xhr.responseText; // write info
};
xhr.open("get", url, true);
xhr.send();
}
You're started by showing the request and parsing into a JSON object. That's a good start!
Now, you need to iterate each result (you can use a for loop) and render the property.
I've built an example, here's the code:
Html:
<div id="output">
</div>
Javascript:
var url = "https://swapi.co/api/people";
function heroes() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var data = JSON.parse(xhr.responseText);
var tableContent = '<table>'
tableContent += "<thead><tr>";
tableContent += "<td>Name</td>";
tableContent += "<td>Height</td>";
tableContent += "<td>Mass</td>";
tableContent += "<td>Eye Color</td>";
tableContent += "<td>Skin Color</td>";
tableContent += "<td>Gender</td>";
tableContent += "</tr></thead>";
for(var i=0;i<data.results.length;i++) {
var person = data.results[i];
tableContent += "<tr>";
tableContent += "<td>" + person.name + "</td>";
tableContent += "<td>" + person.height + "</td>";
tableContent += "<td>" + person.mass + "</td>";
tableContent += "<td>" + person.eye_color + "</td>";
tableContent += "<td>" + person.skin_color + "</td>";
tableContent += "<td>" + person.gender + "</td>";
tableContent += "</tr>";
}
tableContent += "</table>"
document.getElementById('output').innerHTML = tableContent; // write table
}
// document.getElementById('demo').innerHTML = xhr.responseText; // write info
};
xhr.open("get", url, true);
xhr.send();
}
heroes();
Here's a pen, if you want to see it live.

Trying to store the response of ajax to a global variable but that value is not assigned outside the ajax code

One more thing is here that if I use the alert() at end of the ajax code the code is working fine. here whatever the ajax response comes has to be appended to the existing table.
for (var i = 1; i < rows.length; i++) {
var cells = splitCSVtoCells(rows[i], ",");
var obj = {};
for (var j = 0; j < cells.length; j++) {
obj[first_Row_Cells[j]] = cells[j];
}
jsonArray.push(obj);
}
console.log(jsonArray);for (var i = 0; i < jsonArray.length-1; i++) {
html += "<tr id=\"rowitem" + i + "\"><td id=\"rownum"+i+ "\" style=\"display:none;\">" + i + "</td><td> " + jsonArray[i].Clientgroup + " </td>";
html += "<td>" + jsonArray[i].hostgroup + "</td>";
html += "<td>" + jsonArray[i].server + "</td>";
html += "<td>" + jsonArray[i].Group + "</td>";
html += "<td>" + jsonArray[i].user + "</td>";
html += "<td>" + jsonArray[i].ticket + "</td>";
html += "<td>" + jsonArray[i].requesttype + "</td>";
$.ajax({
url : "BulkValidateServlet",
type : "POST",
data : {clientgroup: jsonArray[i].Clientgroup, hostgroup: jsonArray[i].hostgroup, server: jsonArray[i].server
},success : function(response){
//alert("i in of ajax:"+i);
status = response;
if (status) {
//alert("outside if: " + status);
//$('<img src=\'images/check_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/check_mark.png' height='20' width='20'/></td>";
} else {
//alert("outside else: " + status);
//$('<img src=\'images/cross_mark.png\' height=\'20\' width=\'20\'/></td>').appendTo(tr);
html += "<td id=\"result"+ i + "\"><img src='images/cross_mark.png' height='20' width='20'/></td>";
}
console.log("Data: " + status);
// alert("Data: " + status );
//return status;
}
});
console.log("outside: " + status);
alert();
}
document.getElementById('tbodyLeads').innerHTML = html;
}
You can try adding
async: false
to your ajax attributes.
Refer to this link.

JQuery Drag and Drop from two tables

I need to implement drag and drop feature form one table to another and vise versa.
This is my function where i get transactions to particular IBAN number, I also have the same function which retrieves users transaction which are hidden.
function getAllTransactions(iban) {
var iban = $("#ibanSelection").val();
var username = $("#hiddenusername").val();
var url = 'http://localhost:64300/api/BankAccountApi/GetUserTransaction/?iban=' + iban;
var table = "<table id=\"table1\">";
if ((username != "") && (iban !="")) {
$.getJSON(url, function (data) {
table += "<tr class=\"ibanSelection\">";
table += "<th>My IBAN</th>";
table += "<th>Send to IBAN</th>";
table += "<th>Transfer Date</th>";
table += "<th>Amount</th>";
table += "</tr>";
$.each(data, function (key, val) {
table += "<tr class=\"draggable_tr\">";
table += "<td>" + val.My_Iabn + "</td>";
table += "<td>" + val.Iban_To + "</td>";
table += "<td>" + val.Transfer_Date + "</td>";
table += "<td>" + val.Amount_Transferd + "</td>";
table += "</tr>";
});
table += "</table>";
$("#divResult2").html(table);
});
}
}
Just use the jQueryUI Sortable feature.
Here's the complete example + documentation. Very easy.
Also this example shows your case:
http://jqueryui.com/sortable/#connect-lists

Categories