Updating Dygraph with ajax - ajax

I have below code which pull data from mysql using ajax json and draw Dygraph chart which it works fine but when my problem is updating the chart.
When I try to update the graph I am getting this error:
Uncaught ReferenceError: g is not defined
which is already defined
all these code are in document ready fucntion
// get data from server
$.ajax({
type: 'POST',
url: 'php/proccess.php',
data: {
type: "jobgraph",
job: job
},
dataType: "json",
success: function(response) {
//console.log(response);
var i = 0;
$.each(response, function(key, value) {
test[i] = [new Date(value[0]), value[1] / 1000, value[2]];
i++;
});
if (test) {
document.addEventListener("mousewheel", function() {
lastClickedGraph = null;
}, false);
document.addEventListener("click", function() {
lastClickedGraph = null;
}, false);
if (response) {
var g = new Dygraph(document.getElementById("noroll"),
test, {
labels: ["Date", "Voltage", "Temp"],
digitsAfterDecimal: 3,
interactionModel: {
'mousedown': downV3,
'mousemove': moveV3,
'mouseup': upV3,
'click': clickV3,
'dblclick': referesh,
'mousewheel': scrollV3
}
}
);
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
alert('Internal error: ' + jqXHR.responseText);
} else {
console.log(errorThrown);
}
},
});
// update Data every 2 second by pulling new data from mysql server
window.intervalId = setInterval(function() {
$.ajax({
type: 'POST',
url: 'php/proccess.php',
data: {
type: "jobgraph",
job: job
},
dataType: "json",
success: function(response) {
//console.log(response);
var i = 0;
$.each(response, function(key, value) {
test[i] = [new Date(value[0]), value[1] / 1000, value[2]];
i++;
});
//console.log(test);
g.updateOptions({
'file': test
});
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 500) {
alert('Internal error: ' + jqXHR.responseText);
} else {
console.log(errorThrown);
}
},
});
}, 2000); </pre>
//end update

In your setup, you define the graph with:
var g = new Dygraph(...
var limits the scope of g, so it's not accessible in your later call. Make the g variable available globally, or in a variable that you pass between functions.

Related

webapi 2 key delta patch update

Using le framework here
http://blog.longle.net/2014/03/04/harness-the-power-of-asp-net-mvc-web-api-odata-kendo-ui-requirejs-to-build-an-easy-maintainable-spa-for-the-net-developer-published/
and here
Web API + OData - PATCH request 400 error
how to send key delta in patch update of WebAPI 2 odata where kendo datasource "batch: true"
AcceptVerbs("PATCH", "MERGE")]
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Company> patch)
The key is always empty!!!
Does WebAPI odata supported by kendo?
Since it is a very specific task, I have only one tweak that is working for Repository Pattern provided by Le framework shown in the above mentioned link.
define(['kendo', 'testModel'],
function (kendo, testModel) {
var svcUrl = '/odata/modelURL';
var ds_test = new kendo.data.DataSource({
type: 'odata',
transport: {
read: {
//async: false,
url: svcUrl,
dataType: 'json'
},
update: {
url: function (data) {
return svcUrl + '(' + data.models[0].ID + ')';
},
dataType: 'json',
type: 'PATCH'
},
create: {
url: function (data) {
return svcUrl + '(' + data.models[0].ID + ')';
},
dataType: 'json',
type: 'PATCH'
},
destroy: {
url: function (data) {
return svcUrl + '(' + data.models[0].ID + ')';
},
dataType: 'json',
type: 'PATCH'
},
parameterMap: function(data, operation) {
if (operation != 'read') {
var model = kendo.stringify(data.models[0]);
return model;
};
return data.models;
}
},
batch: true,
serverPaging: true,
serverSorting: true,
serverFiltering: true,
pageSize: 10,
schema: {
data: function (data) { return data['value']; }, //{ return data.value; },
total: function (data) { return data['odata.count']; },
model: testModel
//parse: function(response) {
// var f = ds_appl_home.options.schema.model.fields;
// $.each(response, function (key, value) {
// if (!(key.toString() in f)) {
// delete response[key];
// }
// });
// return response;
//}
},
error: function (e) {
...
}
});
return ds_test;
});

Call multiple ajax calls

$.ajax({
url: "",
jsonpCallback: 'item',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
var markup = "";
$.each(data.list, function(i, elem) {
dbInsert(elem['itemCode'], elem['description'], elem['price']);
});
},
error: function(request, error) {
alert(error);
}
});
I have the above type of different ajax calls with different urls. How can I run each Ajax call, one after another?
You can do something like this.
$('#button').click(function() {
$.when(
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('one is done')
}
}),
$.ajax({
url: '/echo/html/',
success: function(data) {
alert('two is done')
}
})
).then( function(){
alert('Final Done');
});
});
fiddle
Keep track of the urls still to send, and have the success inline function of one ajax request go and call the next.
var urls = [...];
var runNextAjax = function() {
var url = urls.pop();
$.ajax({
url: url,
... other settings, as before ...
success: function(data) {
... do what you want with the data ...
if (urls.length > 0) runNextAjax();
},
error: function(req, err) {
... do what you want with the error ...
if (urls.length > 0) runNextAjax();
}
});
};
// Start the sequence off.
runNextAjax();
The above code acts on the data as it arrives, if you want to cache it all and act on it all at the end, store each result in an array, then process the array in a function that gets called at the end:
var dataAccumulator = [];
var displayAllData = function() {
for (int i = 0; i < dataAccumulator.length; ++i) {
var data = dataAccumulator[i];
... process the data into HTML as before ...
}
};
var urls = [...];
var runNextAjax = function() {
var url = urls.pop();
$.ajax({
url: url,
... other settings, as before ...
success: function(data) {
// Store the data we received
dataAccumulator.push(data);
if (urls.length > 0) runNextAjax();
else displayAllData();
},
error: function(req, err) {
... do what you want with the error ...
if (urls.length > 0) runNextAjax();
else displayAllData();
}
});
};
// Start the sequence off.
runNextAjax();

wrong ajax callback invoked using cordova

In my jqm app I make a POST using jQuery $.ajax sending and receiving json data. Everything is fine in the browser and on iPhone; on Android I noticed that when this server response is like this:
{ "code" : 500,
"errorMsg" : "bla bla bla",
"errors" : null,
"status" : "INTERNAL_SERVER_ERROR",
"success" : false
}
the ajax invokes the "error" callback and not the "success". This happens only on android and only if I include corova-2.0.0. js on the project. Any help?
I'm using cordova-2.0.0 with jqm 1.3.1 and jQuery 1.9.1
Here's my code:
var ajax = $.ajax({
type: "post",
url: url,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: data,
timeout: 30000
});
var success = function (d) {
if(d.success==true && obj.success)
obj.success(d.data);
else
{
var msg = parseErrors(d);
console.log(msg);
//open page passing results
obj.msgBus.fire("RequestResult", {
callback: function(){ obj.msgBus.fire("Welcome");},
success: false,
text: msg
});
}
};
var error = function (xhr, status, e) {
console.log('error ajax url:[' + url + '] status:[' + status + '] error:[' + e + ']');
if (obj.error) {
if ((typeof e == 'string'))
obj.error({
statusText: e,
code: xhr.statusCode,
text: xhr.responseText
});
else {
e = $.extend(e, {
statusText: status
});
obj.error(e);
}
}
};
var complete = function () {
if (obj.complete) {
obj.complete();
}
};
var parseErrors = function(d){
console.log( d);
if(d.errors==null){
return d.errorMsg;
}
else
{
var res="";
for (var i=0;i< d.errors.length;i++){
res+= "{0}: {1} <br/>".format( d.errors[i].field, d.errors[i].errorMsg);
}
return res;
}
};
ajax.success(success).error(error).complete(complete);
where data is an object like this:
{
"date" : 1371679200000,
"idBeach" : "1",
"idStuff" : 3,
"idUser" : "8",
"numStuff" : 1
}
Try this, it works for me
$.ajax({
async: false,
type: "POST",
url: "Your_URL",
dataType: "json",
success: function (data, textStatus, jqXHR) {
$.each(data, function (i, object) {
alert(obj.Data);
});
},
error: function () {
alert("There was an error loading the feed");
}
});

Trying to access Instagram API using jQuery

I'm trying to use the Instagram API and I'm making AJAX requests in a do-while loop until the next_url is null. All I want this code to do is to fetch all the followers by making continuous requests until it's done. What is wrong in this code?
When I remove the do-while loop it doesn't gives me an error, but as soon as a I use the AJAX request within a loop, it never stops. Clearly the $next_url string is not changing to the newly fetched next_url - why? What is wrong?
$(document).ready(function(e) {
$('#fetch_followers').click(function(e) {
var $next_url = 'https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100';
var $access_token = '{access-token}';
var $is_busy = false;
var $count = 0;
do {
while($is_busy) {}
$.ajax({
method: "GET",
url: $next_url,
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$is_busy = true;
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
$next_url = data.pagination.next_url;
},
error: function(jqXHR, textStatus, errorThrown) {
$is_busy = true;
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
},
complete: function() {
++$count;
$is_busy = false;
}
});
} while($next_url !== '' || $count <= 50);
});
});
After I failed in my logic, I added the $count variable that can break the do-while loop, because the do-while loop was running infinitely. After adding it, it still runs infinitely, and I have no idea why.
Have the function call itself in the ajax success callback with the new url as a parameter:
$(document).ready(function() {
$('#fetch_followers').click(function() {
var $access_token = '{access-token}';
pollInstagram('https://api.instagram.com/v1/users/{user-id}/followed-by?access_token={access-token}&count=100');
});
});
function pollInstagram(next_url, count) {
$.ajax({
method: "GET",
url: next_url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function(data) {
$.each(data.data, function(i, item) {
$("#log").val($("#log").val() + item.id + '\n');
});
$("#log").val($("#log").val() + data.pagination.next_url + '\n');
// If the next url is not null or blank:
if( data.pagination.next_url && count <=50 ) {
pollInstagram(data.pagination.next_url, ++count);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//alert("Check you internet Connection");
$("#log").val($("#log").val() + 'Error\n');
}
});
}​

How do I update foreign key with odata json

Expected behavior: User clicks on Register button and record is created in related entity. This has worked up til now but now we have requirement to update the foreign key based on a lookup on the current form. How do I accomplish this? The pasted code below throws error in browser "Error on the creation of record; Error – Bad Request"
// JScript source code
CreateButton = function () {
var fieldTable = crmForm.all.new_registerbutton_d;
var html = "<TABLE border=0 cellSpacing=0 cellPadding=0><TBODY><TR><TD width=0px>" + fieldTable.innerHTML + "</TD><TD width=200><INPUT style='BACKGROUND-COLOR: #d8e8ff' onclick=Button_OnClick() value='Register' type=button></TD></TR></TBODY></TABLE>";
fieldTable.innerHTML = html;
document.all.new_registerbutton.style.display = 'none';
crmForm.all.new_registerbutton_c.innerText = "";
}
Button_OnClick = function () {
//var new_se_registration = new Object();
var invitationName = Xrm.Page.getAttribute("new_name").getValue();
//new_se_registration.new_name = invitationName;
var invitationGUID = Xrm.Page.data.entity.getId().replace('{', '').replace('}', '');
alert(invitationGUID);
var value = new Array();
value[0] = new Object();
value[0].id = invitationGUID;
value[0].name = invitationName;
//var invitation = {
//id: invitationGUID, name: invitationName, entityType: "new_se_registration"
//};
//var invitation= { Id: invitationGUID, LogicalName: "new_se_registration", Name: invitationName };
//value[0].entityType = Xrm.Page.data.entity.getEntityType();
//new_se_registration.new_new_se_invitation_new_se_registid.setValue([{ id: invitationGUID, name: invitationName, entityType: "new_se_registration"}]);
//new_se_registration.new_new_se_invitation_new_se_registid = invitation;
//new_se_registration.new_eventname= Xrm.Page.getAttribute("new_eventname").getValue();
//new_invitationid is the Event id
var lookupItem = new Array;
lookupItem = crmForm.all.new_invitationid.DataValue;
var eventname = lookupItem[0].name;
//new_se_registration.new_eventname = eventname;
lookupItem = crmForm.all.new_invitationid.DataValue;
var new_se_registration = {
new_new_se_invitation_new_se_registid: {
__metadata: { type: "Microsoft.Crm.Sdk.Data.Services.EntityReference" },
Id: invitationGUID,
LogicalName: invitationName
},
new_name: invitationName,
new_eventname: eventname
};
//alert ( eventname);
// end Ek - adding event name
//deleteRecord(new_se_registration.new_name, "new_se_registrationSet");
var reg = Xrm.Page.getAttribute("new_registered").getValue();
if (reg == null) {
reg = "N";
}
if (reg != "Y") {
//Xrm.Page.getAttribute("new_registered").setValue("Y");
//alert(reg);
//return;
createRecord(new_se_registration, "new_se_registrationSet", RegisterCompleted, null);
Xrm.Page.getAttribute("new_registered").setValue("Y");
//Xrm.Page.data.entity.attributes.get("new_registered").setSubmitMode("always");
//Xrm.Page.data.entity.save();
}
else {
alert("\"" + Xrm.Page.getAttribute("new_name").getValue() + "\" has been registered already.");
}
}
function RegisterCompleted(data, textStatus, XmlHttpRequest) {
var new_se_registration = data;
Xrm.Page.data.entity.save();
alert("\"" + Xrm.Page.getAttribute("new_name").getValue() + "\" has been registered successfully.");
}
function checkDuplicate() {
alert("test");
}
function deleteRecord(id, odataSetName) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + id + "')",
beforeSend: function (XMLHttpRequest) {
//XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("Record deleted successfully!");
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert("Error while deletion – " + errorThrown);
}
});
}
function createRecord(entityObject, odataSetName, successCallback, errorCallback) {
var jsonEntity = window.JSON.stringify(entityObject);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (successCallback) {
successCallback(data.d, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
alert("Error on the creation of record; Error – " + errorThrown);
}
});
}
Solved. Case sensitivity. Was using wrong case for new_new_se_invitation_new_se_registId.
var new_se_registration = {
new_new_se_invitation_new_se_regist**I**d: {
__metadata: { type: "Microsoft.Crm.Sdk.Data.Services.EntityReference" },
Id: invitationGUID,
LogicalName: invitationName
},
new_name: invitationName,
new_eventname: eventname
};

Resources