Parse the values from CSV file as JSON through Jquery AJAX - javascript

I am trying to get JSON data from Yahoo's Finance API.
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback", function(data) {
// I am parsing JSON string using data here
});
Problem is when when stock is close, I need to show last trade values. I found a link which returns values as a CSV file. So I need to download it and parse it with jQuery.
This is what I have done so far:
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback", function(data) {
if(data.query.results.quote.DaysLow == null && data.query.results.quote.DaysHigh == null){
//When stock is closed this section works
var date = data.query.results.quote.LastTradeDate;
var datesplit = date.split('/');
$.ajax({
type: "GET",
url: "http://ichart.finance.yahoo.com/table.csv?s=WRC&a="+ datesplit[1] +"&b="+ datesplit[0] + "&c="+ datesplit[2] +"&d="+ datesplit[1] +"&e="+ datesplit[0] +"&f="+ datesplit[2] +"&g=d&ignore=.csv",
dataType: "text",
success: function(data) {
console.log(data);
}
});
}
else{
//When stock is not closed this section works
//There is no problem in this section
}
});
This is the error message I get:
XMLHttpRequest cannot load
http://ichart.finance.yahoo.com/table.csv?s=WRC&a=18&b=9&c=2012&d=18&e=9&f=2012&g=d&ignore=.csv.
Origin null is not allowed by Access-Control-Allow-Origin.
Can you please help me for downloading CSV file?

I think there is no need of ajax you can simply call it like
document.location.href = "http://ichart.finance.yahoo.com/table.csv?s=WRC&a="+ datesplit[1] +"&b="+ datesplit[0] + "&c="+ datesplit[2] +"&d="+ datesplit[1] +"&e="+ datesplit[0] +"&f="+ datesplit[2] +"&g=d&ignore=.csv";
It will not reload page

You can do it by using any server side script
eg :-
$.ajax({
type: "GET",
url: "your-server-side-file.php",
dataType: "text",
success: function(data) {
console.log(data);
}
});
and in that server file your-server-side-file.php process the csv file parse the value. return with your own format.
For example php csv file parsing http://php.net/manual/en/function.fgetcsv.php

Related

How to use requiereJS to import local imput json file?

I want to load a json from local input file to my js script.
The json is imported and I can get the file object, but I can't properly get the JSON and parse it to a JS Object
I tried to use RequiereJS which seems to be the best and quickest solution but I can't make this line to work
require(['json!someFile.json'], function(data){
})
Here is my input in HTML :
<input type="file" class="custom-file-input" onchange="loadFile(this.file) accept="application/json">
And here my js file :
function loadFile(file) {
var myJson;
var url = URL.createObjectURL(file);
require(['json!'+url+''], function(data){
myJson = data;
}
}
Or this :
require(['json!'+file+''], function(data){
You can use ajax function from jQuery
$.ajax({
type: "Get",
url: "data.json",
dataType: "json",
success: function(data) {
},
error: function(){
alert("json not found");
}
});
Note: You need to have the file in server then only it will work.

Not receiving data from ajax to php

I want to send data from javascript to another php page where I want to display it. I found that I need to use Ajax to pass the data to php so I tried myself.
My file where is the javascript:
$('#button').on('click', function () {
$.jstree.reference('#albero').select_all();
var selectedElmsIds = [];
var selectedElmsIds = $('#albero').jstree("get_selected", true);
var i = 0;
$.each(selectedElmsIds, function() {
var nomenodo = $('#albero').jstree('get_selected', true)[i].text;
//var idnodo = selectedElmsIds.push(this.id);
var livellonodo = $('#albero').jstree('get_selected', true)[i].parents.length;
//console.log("ID nodo: " + selectedElmsIds.push(this.id) + " Nome nodo: " + $('#albero').jstree('get_selected', true)[i].text);
//console.log("Livello: " + $('#albero').jstree('get_selected', true)[i].parents.length);
i++;
$.ajax({
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo
},
success: function(data)
{
$("#content").html(data);
}
});
});
});
I want to send the data to another php page which consists of:
<?php echo $_POST["namenodo"]; ?>
But when I try to go to the page there's no data displayed.
This is a very basic mistake I think every beginner (including me) does while posting a data using ajax to another php page.
Your ajax code is actually posting the data to lamiadownline.php (if you are using the variables correctly) but you can't get that data by simply using echo.
Ajax post method post data to your php page (lamiadownline.php) but when you want to echo the same data on the receiver page (lamiadownline.php), you are actually reloading the lamiadownline.php page again which makes the $_POST["namenodo"] value null.
Hope this will help.
First of all you won't be able to see what you have post by browsing to that page.
Secondly, is this
<?php echo $_POST["namenodo"]; ?>
in the current page?
Otherwise, specify the url
$.ajax({
url: "lamiadownline.php",
type: "POST",
data: { 'namenodo': nomenodo,
'levelnodo': livellonodo},
success: function(data) {
$("#content").html(data);
}
});
//try this
$.ajax({
type: "POST",
url:"Your_php_page.php"
data: { namenodo: nomenodo levelnodo: livellonodo},
success: function(data)
{
$("#content").html(data);
}
});

Get php return value using ajax

I am having a form which gets value from the user and stores it to the database.
On submitting the form ,it calls the action.php file using ajax call.
e.preventDefault();
$.ajax({
type: "POST",
url: "action.php",
data: senData,
dataType: "JSON",
success: function(data) {
$("#name").val("");
$('.msg').fadeIn(500);
$('.msg').text("" + data.result + "");
}
});
The values are stored in the database without any errors, but I want to display a notification to the user after submitting the form inside the msg div.
In my action.php file I have added a JSON Encode statement to return a message too.
$msg = 'Thanks Yo Yo';
echo json_encode(array("result" => $msg));
But it is not working i.e, when I submit the form, it stores the data to the database and the webpage refreshes itself without displaying any message inside the .msg div.
Am I doing something wrong and is there a better way to do it??
You need to parse the JSON when it is returned to your javascript.
// Parse the response to JSON
var res = JSON.Parse(data);
$('.msg').text(res.result);
Your code should look like this.
e.preventDefault();
$.ajax({
type: "POST",
url: "action.php",
data: senData,
dataType: "JSON",
success: function(data) {
var res = JSON.Parse(data);
$("#name").val("");
$('.msg').fadeIn(500).text(res.result);
}
});

Ajax Get Url is not Responding

I'm trying to get some XML file from the net and i need to display that in my html page......
This is how my javascript file looks like:
$(document).ready(function(){
$(".update").append("<ul></ul>");
$.ajax({
type: "GET",
url: "https://www2.informatik.hu-berlin.de/~xing/Lib/Docs/jaxp/docs/tutorial/sax/samples/slideSample01.xml",
dataType: "xml",
success: function(xml){
$(xml).find('slide').each(function(){
var sTitle = $(this).find('title').text();
//var sPublisher = $(this).find('heading').text();
$("<li></li>").html(sTitle + ", " + "sPublisher").appendTo(".update ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
When i try to run this using this URL the browser gives an error saying "An error occurred while processing XML file"........................
But if i download the XML File and write it as following.... It will run the page without any errors.......
$.ajax({
type: "GET",
url: "data.xml",
dataType: "xml",
...................................
I also tried to use another online XML File same thing happened...... Anyone has an idea how to solve this???
Thank You!!!!!

HTTP error on adding large data using jquery ajax

I have created a good html/javascript program in displaying ajax in my jqgrid. But just recently, I noticed that when I try to save large or many data to save to my table line, it will return http:error.
I really don't understand whats wrong when I can successfully saved small numbers of lines. Someone told me that it was my html/javascript that has a problem since when I try to trace it with delphi(the one I used to create my webservice), it doesn't go into my code (when saving many lines), and will go into my code if only less than 10 line data that i will save (there's no error in tracing). Here's a data that I am sending to my webservice/html request:
{
"SessionID":"66KuzRH1w1sWCM188q4k8BTJb5ijG81v",
"operation":"add",
"transaction_date":"7/27/2011",
"supplier_id":"10000000108",
"wood_specie_id":"1",
"lines":[
{"plank_number":"1","thickness":"4","width":"6","length_t":"8","quantity":"1","board_foot":"16.00","wood_classification_id":"1","price":"15"},
{"plank_number":"2","thickness":"45","width":"6","length_t":"8","quantity":"1","board_foot":"180.00","wood_classification_id":"1","price":"15"},
.
.
.
.
{"plank_number":"22","thickness":"3","width":"6","length_t":"8","quantity":"1","board_foot":"12.00","wood_classification_id":"1","price":"15"},
{"plank_number":"23","thickness":"4","width":"6","length_t":"7","quantity":"1","board_foot":"14.00","wood_classification_id":"1","price":"15"}
],
"scaled_by":"JAYSON","tallied_by":"TALLIED BY","checked_by":"CKECKED BY","total_bdft":"582.84","final":""
}
here's the code in adding my line data:
function tallyAddData(){
var datas = {
"SessionID": $.cookie("SessionID"),
"operation": "add",
//"transaction_num":$('#tallyNo').val(),
"transaction_date":$('#tallyDate').val(),
"supplier_id":$('#supplierInput').attr("name"),
"wood_specie_id":$('#woodSpecie').attr("name"),
"lines":plank_data,
"scaled_by":$('#tallyScaled').val().toUpperCase(),
"tallied_by":$('#tallyTallied').val().toUpperCase(),
"checked_by":$('#tallyChecked').val().toUpperCase(),
"total_bdft":$('#tallyTotal').val(),
"final":"",
};
alert(JSON.stringify(datas));
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'update/tallyHdr',json:JSON.stringify(datas)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblTallyHdr').trigger('reloadGrid');
}
}
});
}
your are using the Query string to pass the data - the Query string size is limited (http://en.wikipedia.org/wiki/Query_string)
I recommend on passing the data as post:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
you can also read about Jquery post (http://api.jquery.com/jQuery.post/)

Categories