I'm trying to fetch the data from Yahoo! Finance to get value for currency exchange with this url assuming I'm getting currency exchange for USD to EUR in javascript
http://download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=l1
in the csv, I would receive just the one value I need. Eg. - '0.8994'
Now, in same javascript file, I want this value to be pass into a variable
var USDEUR;
at this point, I'm not sure how to pass the value from the downloaded csv. Could someone enlighten me how to do this properly?
Thanks in advance
It seems you don't actually need to parse this file as a csv, it's basically a plain text string? Assuming jquery:
var USDEUR;
$.ajax({
type: "GET",
url: "http://download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=l1",
dataType: "text",
success: function(data) {USDEUR = data}
});
EDIT: It seems the url has access control issues, you may not be able to do this with a XHTTP request from the client. Is this data meant to be accessed as a public API?
Use JQuery Ajax
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
var USDEUR;
$.get("download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=l1", function(data){
USDEUR = $.parseXML(data);
}, "xml");
</script>
Related
I'm trying to send the data I gathered from my web app to a google spreadsheet.
I'm using the script from Martin Hawksey:
https://gist.github.com/mhawksey/1276293
I've set it up and did everything as shown in the manual. And I am getting data back, but it's showing up as undefined values:
This is the code I use to send the JSON string to my spreadsheet:
function sendData(){
var url = 'https://script.google.com/macros/s/AKfycby3SUJvfEjdHWVoEON0L5hN4uXod8M4Jv1LAIWH3Ny16MIUz9o/exec';
var data = JSON.stringify(member);
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
data: data,
success: function (response) {
console.log("succes! I sent this: " + data);
console.log("got this back: " + JSON.stringify(response));
},
});
}
This gives me a success message, it even tells me which row it was placed on.
This is the JSON string I'm sending:
{"Voornaam":"Name","Achternaam":"Name","Mail":"x#x.com","Verjaardag":"0/0/0000","Foto":"https://graph.facebook.com/xxxxx/picture?width=1020","School":"School X","Richting":"Course X"}
I even checked this JSON with a JSON parser online and it didn't return any errors.
For starters, I'm not entirely sure how to check which string I'm receiving at my spreadsheet. If it's still correct when it arrives. I tried logging it, but can't seem to get any response from the google logger.
If anyone could point out what I'm doing wrong, you would be greatly appreciated!
The Web script expects a JSON object. However, Ajax call is made with a string using the stringify function
var data = JSON.stringify(member);
Modifying the script to make the GET call with JSON object as is resolved the issue, like so
var data = member;
I am practicing ajax and want to send big amount of data to server (for instance I want to make tags for a post which can be up to 20 tags). Currently all I do is concatenate each tag with specific symbol between them and then in server I filter it and convert it to many tags again but I don't think that's the natural way. So what is the best way to send say, 30 - 40 entries to server with ajax optimally.
UPDATE (As some of the people suggested I am showing js code example):
$(document).ready(function(){
var tagsToSend = "tag1%tag2%tag3%tag4%tag5%tag6%tag7%tag8%tag9%tag10%tag11%tag12%tag13";
$.ajax({
url: "test.php",
method: "POST",
data: {
tags: tagsToSend
},
success: function(result){
alert(result)
}
});
})
So basically in server I'll just iterate over the given tags string and filter each tag. And I want more natural way.
I think the better way is to sending tags as a json array and not GET parameter. Something like this:
var postData = {};
postData['tagsToSend'] = ["tag1", "tag2", ...];
And inside your ajax config:
data: JSON.stringify(data)
Now, you can get a json in your php file and parse it into php array.
This can help you to have more readable and cleaner request to the server.
I have a searchbox that is working with a local Json data (in the same file) using a var but now I would like to use with an external url json file in the same way that it works before.
What I have now:
var data1 = [{"test_id":"1","test":"test","test2":"test2"}];
What I'm trying:
var data = $.ajax({
dataType: "json",
url: 'myjsonurl',
data: data
});
I've tried with getJSON and with other some recommendations but are not working as I expect, in the image you can see that I'm having the data in both ways but quite different and is not working in the searchbox.
Image: https://i.stack.imgur.com/kWKkz.png
You can find the searchbox here:
https://www.js-tutorials.com/javascript-tutorial/live-search-json-objects-data-using-jquery/
Is there any idea to get same data as I have now from an external file and use it into a var as the searchbox do?
Any ideas?
Thanks in advance,
The way you are doing is, what you are getting is XHR Object.
To get proper JSON response and to work on it, you can write a success function and handle response data there or just use getJSON.
For example:
$.getJSON('https://gist.githubusercontent.com/GeekAb/027c70bd21d006027cd91f538ae4694e/raw/68fda14df1b9fbf6835a02639aa210e88826d19d/SampleJSON',
function( data ) {
console.log(data);
console.log(data[0]);
console.log(data[0]['employee_age']);
});
You can check this Bin link https://jsbin.com/cixezewisi/edit?html,js,console
First off, you have a lot of options when it comes to importing data from an external file (some easier than others). The following list is from another stackoverflow post:
ES6 import
Node.js Require
Ajax
jQuery
I suggest checking out the link, as the poster gave great detail on these options.
Anyways, it looks like you are trying to implement this with Ajax. You basically got it down correctly. Based off the image, what your issue is that using ajax has stringified your data, which is expected. All you have to do is:
var data = $.ajax({
dataType: "json",
url: 'myjsonurl'
});
var parsedData = JSON.parse(data)
This will parse your data into the JS array you are looking for.
Im on project to make an app with codeigniter but i got stuck, when i want to pass same variable outside field via ajax into controller i got error the variable is not defined.
this is a example.
$("#form_status_update").submit(function() {
var date = new Date().toString();`
$.ajax({
type: 'POST',
url: "<?php echo base_url()?>socialcontroller/setdate",
data:date,
success: function(data) {
window.location.href = "<?php echo base_url()?>socialcontroller/ssetdate";
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
});
after passing some var i want to insert into my database.
and my question is how to pass a variable not field into controller via ajax thanks, i already search on google but i didnt geting the right answer :)
`
The line data:date, is wrong. You are passing up a number on the querystring and not a key/value pair.
It needs to be
data: {date : date},
or
data: "date=" + encodeURIComponent(date),
From jQuery Docs:
data
Type: PlainObject or String or Array
Data to be sent to the
server. It is converted to a query string, if not already a string.
It's appended to the url for GET-requests. See processData option to
prevent this automatic processing. Object must be Key/Value pairs. If
value is an Array, jQuery serializes multiple values with same key
based on the value of the traditional setting (described below).
Here is the code that help you with your problem
You can just adapt it with your code and it should work !
<script>
$(document).ready(function(){
$("button").click(function(){
var myDate = new Date();
$.ajax({
// Send with POST mean you must retrieve it in server side with POST
type: 'POST',
// change this to the url of your controller
url:"index.php",
// Set the data that you are submitting
data:({date:myDate}),
success:function(result){
// Change here with what you need to do with your data if you need of course
$("#div1").html(result);
}});
});
});
</script>
<body>
<div id="div1">
<p>Today date here</h2>
</div>
<button> Get Date< /button>
</body>
</html>
and your PHP code can be something like this !
<?php
// This line of code should get your data that you are sending
$data = $_POST['date'];
/// This code was just for checking purpose that it is returning the same value through ajax
$arr = array(
'receive_date'=>$data,
);
echo json_encode($arr);
I think this code can work with must of MVC framework if you are setting your controller URL as url parameter. Check also the Framework documentation about getting the data through POST !
your selector $("form_status_update") doesn't match a class or an id of the DOM.
and it doesn't match an html element either.
so this for sure gives you some (extra) problems.
couldnt you have tried running the date function at the php controller youre calling from the ajax function.
i dont see any specific reason as to why you have to send in date as the input parameter from the javascript function.
remove the date var and data field.
and in your php controller.
when you get the controller called.
run a date function in the php code and use the date from there.
I need your help with a big doubt.
Question: As I can create JSON file (with data) from JS code?
The reason is which I need use JSONP, and I wanna take that data from other domain (i.e. http://www.example.com/data/clients.json?callback=?), but this data are storage in a DB (WebSQL) and I need which that data is written in the json file (i.e. clients.json)
Please I need your help because three days ago I try do this, but I don't find yet the answer.
P.S.: Sorry for my english, not is my native language.
EDIT
Sorry my question is confused. I try again but for steps.
I need to write a JSON file with data or records from a DB (WebSQL). Actually my functions are working well (add record, update record, delete), but I need to put that data in a json file because, I'll use the next code for get the data from other domain.
(function($) {
var url = 'http://www.example.com/scripts/clients.json?callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.sites);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);