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>
Related
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);
}
});
}
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.
I have an AJAX call I am using to grab some data from a DB.
$.ajax({
url: URL + '/main/noc/html_forms/query.cfm',
type: 'GET',
dataType: 'json',
data: {
dataset: 'Users'
},
async: false,
timeout: 5000,
cache: false,
success: function(data) {
var result = data.result;
console.log(result);
}
});
I can see from the console that the data is successfully retrieved, except that I can't print this data to a DOM ID element. Even if I do a document.write(result); the text that is displayed on the screen is
[object Object],[object Object],[object Object]
Again, the data is retrieved successfully because I can see it, I just can't get at it.
I know this is probably a silly question and it'll end up being something I can learn in a 101 class, but can someone explain what is happening here and how I can get at my data?
In your posted screenshot it seems like you are getting the result from the AJAX call as a form of Array. So, to access its data you should probably have to do something like... document.write(result[0].user_name) or
$.ajax({
url: URL + '/main/noc/html_forms/query.cfm',
type: 'GET',
dataType: 'json',
data: {
dataset: 'Users'
},
async: true,
cache: false,
success: function(data) {
var result = data.result;
for (var i = 0; i < result.length; i++) {
document.write(result[i].user_name);
}
console.log(result);
}
});
Hope this helps.
Your Code Is Fine but on the success it is returning array of object then you have to modify your code like this
$.ajax({
url: URL + '/main/noc/html_forms/query.cfm',
type: 'GET',
dataType: 'json',
contentType:'application/json;charset=utf-8',
data: {
dataset: 'Users'
},
async: false,
timeout: 5000,
cache: false,
success: function(data) {
alert(data[0].user_name);
console.log(result);
}
});
success: function(data) {
$.each(data,function(index,obj)
{
console.log('object ' + index);
$.each(obj,function(key,value)
{
console.log(key + ':' + value);
});
});
}
You are getting an array of objects from server. You cannot directly print that. You need to iterate through this array for printing the values. For this you can use $.each jquery function to first iterate through the array of object and then again to iterate through all the key-value pairs of each object. You can read about $.each function here
I am not able to pass value using ajax in php file.
Corrected Code
<script>
$("body").on('change', '#area', function () {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'box.php',
type: 'POST',
data: {option: selectedValue},
success: function () {
console.log("Data sent!");
}
});
});
</script>
here the php code
<?php $val=$_POST['option'];echo $val; ?>
There are a few problems here:
It should be url, not rl. Also, you have type: POST' with it ending in a ', but no starting '.
It should be type: 'POST'.
It should then look like this:
$("body").on('change', '#area', function() {
var selectedValue = this.value;
$.ajax({
url: 'box.php',
type: 'POST',
data: {
option : selectedValue
},
success: function() {
console.log("Data sent!");
}
});
});
If you want to view your data on the same page after (as on box.php, you are echo'ing the value.), you can do this:
success: function(data) {
console.log(data);
}
This will then write in the console what option is, which is the value of #area.
Try the following code
$("body").on('change',function(){
$.ajax({
URL:<you absolute url>,
TYPE:POST,
Data:"variable="+$("#area").val(),
Success:function(msg){
<do something>
}
});
});
Hope this will help you in solving your problem.
Your just miss ajax method parameter spelling of 'url' and single quote before value of type i.e. 'POST'. It should be like
$.ajax({
url: 'box.php',
type: 'POST',
data: {option : selectedValue},
success: function() { console.log("Data sent!");}
});
I need to call an asp.net page from javascript with queryString having Arabic text. It shows me an error when goes online but works smoothly on the local server. When arabic value is small then it works smoothly problem arises when arabic text is in multiple lines.
$.ajax({
url: "Empty/emptyGovt2.aspx",
data: "arKeyword="+encodeURIComponent($("#txt_arKeywords").val(),
success: function(data) {
diaL("Details Updated Successfully");
},
error: function(){
diaL('Error Occurred');
}
});
Dont use get with long and complex datas use post
$.ajax({
url: "Empty/emptyGovt2.aspx",
type:"POST",
data: {
"arKeyword" :$("#txt_arKeywords").val(),
"OrgId" : newParentOfficeID
// etc
},
success: function(data) {
diaL("Details Updated Successfully");
},
error: function(){
diaL('Error Occurred');
}
});
And on the php you can access the values as $_POST['OrgId'] etc
I would suggest you to use POST and dataType:'json' or 'text':
$.ajax({
url: "Empty/emptyGovt2.aspx",
type: 'POST',
data: {"arKeyword" : $("#txt_arKeywords").val()}, //<----json objects
dataType: 'json', //<----dataType
success: function(data) {
// retriev json response
var respData = $.parseJSON(data);
$.each(respData, function(i, item){
console.log(item);
});
diaL("Details Updated Successfully");
},
error: function(){
diaL('Error Occurred');
}
});
and make sure to return json from 'Empty/emptyGovt2.aspx'