Highcharts : How to use setData with a string obtained by ajax? - javascript

I would like to update my chart using ajax but the setData method need an array and I only have a string so it doesn't work.
here is my code
$(".chooseService a").click(function() {
$("span.currentService").html($(this).html());
$.get('http://localhost:8080/dashboard/ws/charge/repartition/jour/'+$(this).html(),
function(data) {
// setData (Array<Mixed> data, [Boolean redraw])
chartDay.series[0].setData(data);
});
});
data is a formatted string like
[[1356995280000,183.0],[1356995520000,573.0],[1356995760000,243.0]]
Would someone have any idea ?

You may parse your JSON string into the variable data.
data = JSON.parse(data);
If you have trouble using the JSON method:
http://caniuse.com/json

when you return the result from the server side you can format the content to be a JSON type
header ('Content-type: text / json');
header ('Content-type: application / json');
Then you can convert this result to evaluate it properly the javascript from the client side.
jQuery.parseJSON (this.responseString);
If you want an array like this in can use this reference

Related

Parse json from php in js

I have array in my php file:
$invoices_arr = [];
foreach ($invoices as $key=>$invoice){
$invoices_arr[$key]['id']=$invoice->get_id();
$invoices_arr[$key]['code_text']=$invoice->get_code_text();
$invoices_arr[$key]['invoice_name']=$invoice->get_invoice_name();
$invoices_arr[$key]['status_invoice']=$invoice->get_status_invoice();
$invoices_arr[$key]['attachments']=$invoice->get_attachments();
}
echo json_encode(['invoices'=>$invoices_arr]);
My ajax call:
$.ajax({
data:{lead_id:$("#lead_id").val()},
url: sJSUrlGetAllLeadInvoices,
success: function (data) {
var obj = jQuery.parseJSON(data);
$("#all_invoice_table tbody").empty();
$(obj.invoices).each(function(key,value){
$('#all_invoice_table').append('<tr><td>'+value.invoice_name+'</td><td class="invoice_status">'+value.status_invoice+'<td>attt</td><td><button id="'+value.id+'" class="edit_invoice_'+value.id+'">Edit invoice</button</td><td><button class="send_invoice_btn_'+value.id+'">Send invoice</button></td><td><img class="delete_invoice_'+value.id+'" src="/images/icons/delete.gif"></td><td class="invoice_hidden_column_'+value.id+'">'+value.code_text+'</td></tr>');
});
}
});
In field value.attachments there is php serialize array, for example, string "a:1:{i:0;s:36:"../../pdf_invoices/2017-10-10015.pdf";}" .
How can I convert this string to array in js?
I try do it:
var mas=JSON.parse(value.attachments);
But I get error SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
How can I solve it? Thanks for any help.
Maybe you should unserialize inside PHP code before encode in json
You don't need to parse the result with jQuery.parseJSON because jQuery do it for. If you inspect data using console.log() you will see that is a Javascript object ready for to use.
You need to pass datatype as json.
you can use jQuery parse method for parsing json response.
datatype:json

Read JSON String Shown In URL Using Javascript

i am trying to create a simple web app that gets the latitude and longitude stored in a JSON string and uses them to place markers on a google map. Currently, I have a program on a server which retrieves a JSON string with data when a URL is entered into a web browser. The JSON string produced is as follows:-
{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}
What method could i use in JavaScript that would allow me to get the JSON string that is produced?
P.S I know I will need to parse the text afterwards to make a JSON Object, this is something that can be done afterwards.
Use the Jquery library's get method to request the data from the server. Here is a link to a simple W3 tutorial : http://www.w3schools.com/jquery/ajax_get.asp
Your code will look something like this:
$("button").click(function(){
$.get("/your/server/url",function(data){
var result = JSON.parse(data);
// Process result.employees
});
});
You could use
var x = JSON.parse('{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}');
and then access it with:
x["employees"][0]["lat"];
try this for normal strings:
JSON.parse(str)
or if you're using AJAX to get that Json you can use as following:
$.get(..,'json')
OR
$.post(..,'json')

d3.csv.parse only parses first line of csv string

I'd like to allow a user to populate a textbox with a csv string (sample shown below) and then parse with d3.csv.parse.
x,y,series,size
2,-0.083014839,Group 0,0.883928284
-9,0.355697349,Group 0,0.149154477
5,-0.256459661,Group 0,0.066308001
3,-0.243723214,Group 0,0.388138931
-7,0.776456119,Group 4,0.481110901
When I grab the val() within the textbox it's only able to save the first row of the csv string to a variable in javascript and then errors out. How do I save the whole csv string to a variable so I can send to d3.csv.parse?
This was happening with me. The problem was using the d3.csv.parse() in the same way I was using d3.csv(). For example:
d3.csv("data.csv", function(error, data) {
//Do something with the data
}
So, I tried to use d3.csv.parse like this:
d3.csv.parse(variable_with_csv, function(data) {
//Do something with the data
}
But this is WRONG. The second parameter is an accessor not the call back with the data. The correct way to do what you want is simply get the data directly:
data = d3.csv.parse(variable_with_csv)

getting json data from localhost to use in D3

I'm creating a D3 bubble chart, using json data. I'm using sinatra for my app, and my json data is available at localhost:4567/data.json
I tried using
var myData = [];
$.get('data.json', function(data) {
myData = data;
console.log(myData);
.......
and I get the correct values in the javascript console, but the bubble chart does not render. (The rest of the code works if I copy and paste the data from 'data.json' and set it to a var, but it does not work if I use the $get method).
Do you have any ideas on how I could access this json data from localhost:4567?
Much appreciated,
Tim
I think what is probably going on is that jquery isn't automatically parsing the data as a JSON object due to missing MIME headers in the response from your server. Try using getJSON instead.
you can simply use
d3.json('data.json', function(data) {
myData = data;
console.log(myData);
.......
to read the json file

Incorrect JSON data format

I am trying to create some JSON to be used for displaying a chart using Highcharts
http://www.highcharts.com/
I have copied one of their examples:
http://www.highcharts.com/stock/demo/basic-line
Click "View Options" under the graph to see the source. There is also a JSFiddle there to play with
If I copy that locally it all works fine.
The problem is when I try to use my own data source.
I have an ASP.Net MVC controler which is spitting out a list of arrays, just like their data source. However, that doesn't work.
Their datasource looks like this
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
and they retrieve it like this
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
So I thought I'd take a step back and copy thier data exactly and put it in a text file on my server and try that:
So I tried this
$.getJSON('/data.txt', function (data) {
and this
$.get('/data.txt', function (data) {
but neither work
I have also tried using both JSON.parse and jQuery.parseJSON after retrieving the data, but again - that doesn't seem to work
I am also wondering what the ? is at the start of their data
Their data looks like this
?([[<some data>],[some data]]);
I don't get any error message, the graph just doesn't display
any ideas?
SOLVED IT
Just need to retrive the data and turn it into an array and pass it to the chart.
Needs to be an array, not JSON
That datasource is ouputting JSONP, which is for cross-domain AJAX requests. It's not valid 'raw' JSON because of that extra callback(...) wrapper.
Read up about it here: http://api.jquery.com/jQuery.ajax/ under the 'dataType' section.
As you say in your tags, it's not JSON, it's JSONP. Do not parse it, catch it with a callback. Use jQuery.getScript to do it, and define function callback(data). Inside that function, data should contain the (parsed) object. Also, replace the ? in the URL with callback (or whatever you named your function) - ? is not a valid identifier in JavaScript, so ?([....]) is nonsense.

Categories