Drawind Dynamic series and points with Highchart and ajax - javascript

I try to get several series of data from employees and get them drawed through HighCharts.
I don't know the company till the user click, so then I get trough ajax all the employees and their data (points).
I have a select box where I choose the company. Once done, I call via AJAX/jQuery the server to get data added to HighChart:
$("#company").change(function(){
$.ajax({
type: 'POST',
dataType: 'json',
url: xxxxx,
async: false,
data: { company: company},
success: function(data) {
$.each(data, function(val, text) {
alert (val);
alert (text);
chart2.addSeries({
name: val,
data: text
});
});
}
...
Data I get from the server trough Firebug is in this way:
{"Employee1":[["1356908400000","10.00"],["1359586800000","11.00"], ["1362006000000","12.00"],["1364684400000","13.45"]],"Employee2":[["1356908400000","10.00"],["1359586800000","11.00"],["1362006000000","12.00"],["1364684400000","13.45"]]}
Employee1 and Employee2 should be the series.
However when I call addseries method I get this error:
Uncaught Highcharts error #14: www.highcharts.com/errors/14
It seems data doesn't like to Highcharts.
When I debug through alerts, I get this:
alert (val)->Employee1
alert (text)=1356908400000,10.00,1359586800000,11.00,1362006000000,12.00,1364684400000,13.45
This example is working fine when I put data without ajax.
Any idea?

I've found the answer :-)
text is an array so I need another $.each to read it and format the result:
success: function(data) {
$("html").css('cursor','auto');
$.each(data, function(val, text) {
counter = 0;
$.each(text, function() {
if (counter==0) {
employee_data= "[" + this + "]";
}
else{
employee_data= employee_data + "," + "[" + this + "]";
}
counter=1
});
employee_data = "["+ + "]";
chart.addSeries({
name: val,
data: employee_data
});
});
},

Related

How to use pass ajax data that is displaying in html?

I have a question, that I can't seem to find the 'best' solution for my question.. I have an AJAX call that displays data in the DOM, via jQuery.
JSON
[{
"id":"123"
},
{ "id":"456"
}]
JS
$(document).ready(function() {
$.ajax({
url: 'get/data',
dataType: 'json',
data: '{}',
success: function(data) {
var html = '';
$.each(data, function(i) {
html += '<p>My ID: ' + data[i].id + '</p>';
}
$('#id').append(html);
},
error: function(err) {
console.log(err);
}
})
});
As you can see I am displaying that data here. I would like to pass that ID to another AJAX call by selecting a checkbox and pushing a button or perhaps clicking a link. Whats the best way to accomplish this?
EDIT: I apologize, my actual issue is related to array data. I have updated the code. I am displaying an JSON array in the html now, and I want to pass the id of the user/row that I click?
Thanks,
Andy
$(document).ready(function() {
var resid;
$.ajax({
url: 'get/data',
dataType: 'json',
data: '{}',
success: function(data) {
resid = data.id;
var html = '';
html += '<p>My ID: ' + data.id + '</p>'; $('#id').append(html);
},
error: function(err){
console.log(err);
}
});
$('link').click(function () {
// pass id to second ajax
});
});
try jquery-template
https://github.com/codepb/jquery-template
hope help you

Populating JSON array to drop down reserved word column name conflict

This is the first time ill use JSON. I used the json_encode(myarrayhere) to return array value as shown below.
There is a corresponding value on change of selected value on dropdown.
I verified that I get the array data by using alert(dataArray) and it returns like this
[{"title":"First"},
{"title":"Second"},
{"title":"Third"} ]
I used the word title as column name for a table I'm using in my database.
But the problem now is how to properly populate them in a drop down. I tried to do value.title but it looks like that title is a reserved word/method in php
$.ajax({
type: 'POST',
data: {ctgy: selected},
url: 'awts.php' ,
datatype: 'json',
success: function (dataArray) {
alert(dataArray);
var items = '';
$.each(result,function(name,value) {
items += "<option value='"+value.title+"'>"+value.title)+"</option>";
});
$("#dropdownselectid").html(items);
}
});
Thanks in advance.
Firstly, if you check the console you'll see that you have a syntax error. You have an extra ) when you append value.title to the HTML string.
Secondly, your $.each() call is attempting to loop through result when your data is in a variable named dataArray.
Try this:
$.ajax({
type: 'POST',
data: { ctgy: selected },
url: 'awts.php',
datatype: 'json',
success: function(dataArray) {
var items = '';
$.each(dataArray, function(name, value) {
items += '<option value="' + value.title + '">' + value.title + '</option>';
});
$("#dropdownselectid").html(items);
}
});
Working example

Trying to populate Select with JSON data using JQUERY

It looks like everything has gone fine retrieving the data from the ajax call, but I having trouble to fill the select with the JSON content, it keeps firing this error in the console:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in [{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]
The JS is this
function populateSelect(et_id){
$.ajax({
url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
type: "get", //send it through get method
data:{et_id:et_id},
success: function(response) {
var $select = $('#newStatus');
$.each(response,function(key, value)
{
$select.append('<option value=' + key + '>' + value + '</option>');
});
},
error: function(xhr) {
//Do Something to handle error
}
});
}
The JSON looks like this:
[{"0":"1","s_id":"1","1":"RTG","s_name":"RTG"},{"0":"2","s_id":"2","1":"IR","s_name":"IR"},{"0":"3","s_id":"3","1":"NCR","s_name":"NCR"},{"0":"4","s_id":"4","1":"RIG","s_name":"RIG"},{"0":"5","s_id":"5","1":"VND","s_name":"VND"}]
I think you need something like this.
function populateSelect(et_id){
$.ajax({
url: "http://localhost/new_dec/modules/Utils/searchAvailableStatus.php",
type: "get", //send it through get method
data:{et_id:et_id},
success: function(response) {
var json = $.parseJSON(response);
var $select = $('#newStatus');
$.each(json ,function(index, object)
{
$select.append('<option value=' + object.s_id+ '>' + object.s_name+ '</option>');
});
},
error: function(xhr) {
//Do Something to handle error
}
});
}
Assuming your server side script doesn't set the proper Content-Type: application/json response header you will need to parse the response to Json.
Then you could use the $.each() function to loop through the data:
var json = $.parseJSON(response);

Javascript failing in external file only

Can anyone tell me why I get an error on the 2nd line saying 'unexpected string' but works fine when I have it directly on my view (i'm using MVC 3, not that it makes a difference):
function getUsers(processId) {
$.ajax({
url: "#Url.Action('GetProcessApprovers', 'Risk')",
data: { processId: processId },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
var items = "<option value=\"\">-- Please select --</option>"
if (data != "") {
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
}
$("#ProcessOwnerId").html(items);
}
});
};
Because your url: "#Url.Action('GetProcessApprovers', 'Risk')", only executes in the context of the view, not in an external JS file. It's razor code.
You need to pass the url to the Javascript in some other way, perhaps as a parameter of your function.
getUsers(processId, ajaxUrl)
Another way would be to write out the url from the HtmlHelper into a data attribute in your view and then pick it up in your Javascript.
HTML
<div id="someContainer" data-url="#Url.Action('GetProcessApprovers', 'Risk')">...
JS
var url = $("#someContainer").attr("data-url");
Your url parametre is has the issue.
please change it like this:
url: '#Url.Action("GetProcessApprovers", "Risk")',
Hope it works

Javascript / JQuery loop through posted ajax data string to assign new values to

I have a function which updates a database via ajax. My issue is then how to update the data displayed on the page to show updated details. The POST data can vary and therefore the datastring would be something like this:
var dataString = '[name resource we are editing]=1' +
'&para1='+ para1 +
'&para2=' + para2+
'&para3=' + para3
I want the function below to split or loop through each of the POST variables in the datastring to update the text of an element on the page. I cannot figure out how.
function editAccount(dataString, details, form){
status = $(".status");
$.ajax({
type: "POST",
url: "<?php echo BASE_PATH; ?>/edit/",
data: dataString,
success: function(response) {
$.each(response, function(key, value) {
success_code = key;
message = value;
});
if(success_code == 1){
status.text(message).addClass("valid");
//show details and hide form
$("#" + details).show();
$("#" + form).hide();
//HOW to do below?
//update details being displayed with datasource data
//loop through dataString to assign eg. $('#para1')text(para1);
} else {
status.text(message).addClass("invalid");
}
},
error: function(response){
status.text("There was a problem updating your details into our database. Please contact us to report this error.").addClass("invalid");
}
});
}
As mentioned in a previous comment, I would suggest declaring the dataString variable as an object:
var dataString = { '[name resource we are editing]' : 1,
'para1': para1,
'para2': para2,
'para3': para3
}
Now it'll be much easier to loop over the params, just using the function each, for instance, which you already use in your code:
$.each(dataString, function(key, value) {
// Do stuff with each param
});
EDIT:
As #Qpirate suggests, you also can use the javascript for loop:
for(var key in dataString){
// value => dataString[key]
}

Categories

Resources