Find ID in HTML in JSON and insert in new data - javascript

I have this HTML in AJAX and I want to grab an ID (#commentsContainer) and insert in my other HTML.
Formatted HTML in AJAX:
<blockquote class=\"blockquote\" style=\"font-size: 15px; background-color: #f5f5f0;\" id='comments1'>
<div id='commentsContainer'></div>
</div><br>
</blockquote>
The code I want to use and insert my new data
$(document).ready(function(){
$.ajax({
url: "/api/comments/",
method: "GET",
dataType: "json",
success: function(data) {
// console.log(data)
$.each(data, function(key, value) {
var commentdesc = value.description;
console.log(commentdesc)
$('#commentsContainer').append("<li>" + commentdesc + "<li>")
);
})
},
error: function(data) {
console.log("error")
},
})
})

There are 2 mistakes in your code.
Updated code
$(document).ready(function(){
$.ajax({
url: "/api/comments/",
method: "GET",
dataType: "json",
success: function(data) {
$.each(data, function(key, value) {
var commentdesc = value.description;
$('#commentsContainer').append("<li>" + commentdesc + "<li>");
});
},
error: function(data) {
console.log("error")
}
});
});
Mistake details:
Extra bracket next to append statement.
Extra comma at the end of error method.
Hope this will help you after rectifying the mistakes.

Related

Calling a javascript function from a global file and return it to append to html

I have a global javascript file 'Global.js' with a Global Handler 'GlobalHandler.ashx',
what i am trying to do is to render some data in the back-end (inside the handler ), than return text data using context.Response.Write(MyString)
The question is how to append the data to my html element .
I looked into the response (200) and the data is there , but i don't know the reason of not appending my text into the html element
I have tried to append them like the classic way success:function(data){
$(elementID).html(data);}
But that doesnt work
Here In Global.js
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here In MyPage.aspx
$(document).ready(function () {
GetProfession("Profession");
});
HERE In the Handler
string functionName = context.Request["functionName"];
GroupDAO GroupDAO = new GroupDAO();
if (functionName.Equals("GetProfession"))
{
var ListOfGroups = GroupDAO.GetGroups();
string Builder = "";
foreach (var group in ListOfGroups)
{
Builder+="<option value='" + group.GroupID + "'>" + group.GroupName + "</option>";
}
context.Response.Write(Builder);
}
I am expecting to have those options appended to the html element 'Profession'
but this unfortunately it does not happening
I found the answer , i did not recognize the logical reason of such behaviour ,
but the data was not in the success method even if the statuc code was 200 .
in fact it was in the error: properties of ajax request .
what i have done is :
instead of appending the data in success to the html element .
i did it in the response text
.
Here is the code before not working :
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "application/json;charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data) {
return $("#" + elementID).html(data);
}
});
}
Here is the one that works
function GetProfession(elementID) {
$.ajax({
url: "/Handlers/GlobalHandler.ashx",
dataType: "JSON",
contentType: "text/html; charset=utf-8",
//responseType: ResponseType,
data: {
functionName: "GetProfession"
},
success: function (data, fata, meta) {
},
error: function (err) {
$("#Profession").html(err.responseText);
//alert(err.responseText);
}
});
}

API data not showing on the page

I am trying to get data of currency prices using API, but somehow the data is not showing on the page. In the browser, console works everything fine.
Any help is greatly appreciated. Thanks!
Output:
price: undefined
My code:
<script>
$(function (){
var $data = $('#data');
$.ajax({
type: 'GET',
dataType: 'json',
url: 'https://cors.io/?https://www.freeforexapi.com/api/live?pairs=EURUSD',
success: function(data) {
console.log(data);
$.each(data, function([i, price) {
$data.append('<li>price: '+ price.rate + '</li>');
});
}
});
});
</script>
<ul id="data"></ul>
Made a working example for you, you have to loop the rates tag of the JSON you are getting, not the root one, like you was doing. Also, there was a lost "[" inside your code.
$(function()
{
$.ajax({
type: 'GET',
dataType: 'json',
url: 'https://cors.io/?https://www.freeforexapi.com/api/live?pairs=EURUSD',
success: function(data)
{
console.log(data);
$.each(data.rates, function(i, price)
{
$('#data').append('<li>price: ' + price.rate + '</li>');
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="data"></ul>
The URL you're fetching doesn't return an array. The response is an object with the rates nested at the second level.
{
"rates": {
"EURUSD": {
"rate": 1.157282,
"timestamp":1539727098144
}
},
"code":200
}
In your example, you need to access the 'rates' property on the response, and iterate over that, then access the 'rate' sub property on each curreny pair.
$.each(data.rates, function([currencyPair, rateInfo) {
$data.append('<li>price: '+ rateInfo.rate + '</li>');
});
A few changes, you can remove the loop and access the data object directly within your success function. Furthermore, we can improve upon readability by using Template literals
Here is the code:
$(function() {
var $data = $('#data');
$.ajax({
type: 'GET',
dataType: 'json',
url: 'https://cors.io/?https://www.freeforexapi.com/api/live?pairs=EURUSD',
success: function(data) {
$data.append(`<li>price: ${data.rates.EURUSD.rate}</li>`);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="data"></ul>

Need assistance with understanding .each() and issue with duplicate in Ajax GET

I have an ajax code as below :
<script>
$(document).ready(function () {
EmployeeStates("Available", 1, 15);
});
function EmployeeStates(state, pageNumber, pageSize) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "http://localhost:58102/api/EmployeeState?state=" + state + "&pageNumber=" + pageNumber + "&pageSize=" + pageSize,
//data: JSON.stringify({ "state": state,"pageNumber":pageNumber,"pageSize":pageSize }),
dataType: "json",
success: function (data) {
$.each(data, function (index, emp) {
$("#ReservationDesignation").append(emp.employee.designation.designationName);
});
},
fail: function (error) {
Console.Log(error);
}
})
}
</script>
While assigning the Designation name (emp.employee.designation.designationName) to #ReservationDesignation, I am getting a duplicate.
ie, ArchitectArchitect. The actual result should be Architect.
I am not familiar with .each() function.
Can anyone help me to remove the duplicate from the result?
Thank You.

How to use $.each with ajax to get JSON?

I am using ajax to get JSON from an API, however I am having a problem, retrieving the data. The code for ajax function is fine as I am using it elsewhere. I believe that the issue is with the .done(function().
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
//dataType: 'json',
//method: 'GET',
//contentType: 'application/json'
data: {url: developmentURL},
method: 'POST'
})
.done(function(data) {
//var developments = [];
$.each(data, function() {
$.each(this, function(i, obj) {
console.log(i, obj.Name + ' = ' + obj.ItemKey);
//developments.push();
});
});
})
.fail(function() {
alert('Failed to fetch data')
});
This is the code I am using, which just logs loads of 0 "undefined=undefined". However I have the .done(function() working in a jsfiddle, with the JSON hard coded. So I'm not sure where the problem lies.
Here is the fiddle
The data is of string type. Parse the string into JSON before looping:
data = JSON.parse(data);
$.each(data, function() {
If you want to avoid using JSON.parse you can Set the dataType to just 'json' and you will automatically recieve a parsed json response:
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
dataType: 'json', //Uncomment this line
//method: 'GET',
//contentType: 'application/json'
data: {
url: developmentURL
},
method: 'POST'
})
Or you can also make use of jquery $.getJSON api.
I assume the data that you retrive is an array of Json according to your code.
You forgot add key and value in the $.each callback function to loop into each Json value.
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
//dataType: 'json',
//method: 'GET',
//contentType: 'application/json'
data: {url: developmentURL},
method: 'POST'
})
.done(function(data) {
//var developments = [];
$.each(data, function(key,value) {
$.each(value, function(subKey, subValue) {
console.log(subKey, subValue.Name + ' = ' + subValue.ItemKey);
//developments.push();
});
});
})
.fail(function() {
alert('Failed to fetch data')
});

JSP AJAX return NULL

i using JQuery Ajax to call REST api in jsp but it return null no matter how i call but it can work in html. is there any way to solve this problem. Cant seem to find a solution in the net.
$(document).ready(function () {
alert('ready');
var accessKey = 'xkg8VRu6Ol+gMH+SUamkRIEB7fKzhwMvfMo/2U8UJcFhdvR4yN1GutmUIA3A6r3LDhot215OVVkZvNRzjl28TNUZgYFSswOi';
var thisUrl = 'http://www.onemap.sg/API/services.svc/getToken?accessKEY=' + accessKey;
$.ajax({
type: "GET",
url: thisUrl,
dataType: 'application/json',
success: function (data) {
alert('data is:' + data.GetToken[0].NewToken);
}
});
alert(thisUrl);
});
dataType should be jsonp
$(document).ready(function () {
var thisUrl = 'http://www.onemap.sg/API/services.svc/getToken?accessKEY=' + accessKey;
$.ajax({
type: "GET",
url: thisUrl,
dataType: 'jsonp',
success: function (data) {
console.log(data)
alert('data is:' + data.GetToken[0].NewToken);
}
});
});
Refer to this article:
http://www.isgoodstuff.com/2012/07/22/cross-domain-xml-using-jquery/
You only need "jquery.xdomainajax.js" that is there in the sample source-code to make it work.
$.ajax({
url: 'https://asdf/asdf',
dataType: "xml",
type: 'GET',
success: function(res) {
var myXML = res.responseText;
alert(myXML);
}
});

Categories

Resources