I have the following AJAX function that has 2 variables i.e. sTitle, sValue. I need these two variables to be added to an Array in the format of ArrayName[sTitle, sValue]. I have tried this using a for loop but couldn't get the result I expected. I'm hoping to use this array to draw a Google chart. The data source is an XML.
I'm trying to implement this For Loop and array within the AJAX Call.
So how can I solve this matter?
AJAX Function
$(document).ready(function() {
$.ajax({
type: "GET",
url: "ChartData.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Pie').each(function() {
var sTitle = $(this).find('Title').text();
var sValue = $(this).find('Value').text();
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
You can do it like this
var values = [];
function callback(val) {
// Do something with the array here
};
$(document).ready(function() {
$.ajax({
type: "GET",
url: "ChartData.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Pie').each(function() {
var sTitle = $(this).find('Title').text();
var sValue = $(this).find('Value').text();
values.push([sTitle, sValue]);
});
callback(values);
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
});
Related
I'm using an $.ajax(); request to make a call to my controller. Inside the console.log();, it's correctly displaying all of the data coming in but when I try to display it on the browser via $('#displayCoins').text(item.oldCoins); - only the very last piece of data if being displayed instead of all of the data.
What am I doing wrong and how can I go about rectifying this in terms of displaying all of the data on the browser?
$.ajax({
type: "GET",
url: '/my/endpoint',
dataType: "html",
success: function (response) {
var resp = response;
var respParsed = $.parseJSON(resp);
$.each(respParsed, function(i, item) {
console.log(item.oldCoins);
$('#displayCoins').text(item.oldCoins);
});
}
});
The problem that you are having is you are REPLACING the text every time through the loop instead of appending it.
One solution is to append the data to an array, then output it to the DOM via a single join.
$.ajax({
type: "GET",
url: '/my/endpoint',
dataType: "html",
success: function (response) {
var resp = response;
var respParsed = $.parseJSON(resp);
oldCoins = [];
$.each(respParsed, function(i, item) {
console.log(item.oldCoins);
oldCoins.push(item.oldCoins);
});
$('#displayCoins').text(oldCoins.join("\n"));
}
});
I am using JQuery UI for autocompletion where I take input and ping a server with that input and end create an array to be given to the source of autocomplete. Right now it works perfect sometimes, but when i print the people array sometimes not all the source data shows up on the screen that is shown in console.
let input =$("<input type='text'/>")
.appendTo('#dynamic-form-elements');
input.autocomplete({
source: [] // Initially empty
}).on('input', function () {
$.ajax({
url: "https://lookmeup/json/person/" + input.val(),
dataType: "json",
success: function (parsed_json) {
let people = [];
let results = parsed_json.data;
for (i = 0; i < results.length; i++) {
people.push(results[i][1])
}
console.log(people)
input.autocomplete('option', 'source', people);
}
});
})
You need to include the "minLength:" attribute in the autocomplete so it waits til you hit the minimum length before it performs the ajax.
You can see this in use here:
https://jqueryui.com/autocomplete/#remote-jsonp
The final code should look like this:
input.autocomplete({
source: function(req, response) {
$.ajax({
url: "https://lookmeup/json/person/" + req.term,
dataType: "json",
success: function (parsed_json) {
// do the stuff here and call response callback
}
});
},
minlength: 3
})
You should do this, use source as function: https://jqueryui.com/autocomplete/#remote
input.autocomplete({
source: function(req, response) {
$.ajax({
url: "https://lookmeup/json/person/" + req.term,
dataType: "json",
success: function (parsed_json) {
// do the stuff here and call response callback
}
});
}
})
I have a function that is called multiple times which uses jquery to fetch different JSON from an API.
I have been trying to get a cumulative count of part of that JSON. Here is sort of what I have:
getTheData(aBlah,bBlah,cBlah);
getTheData(aStuff,bStuff,cStuff);
function getTheData(aBlah,bBlah,cBlah){
$.ajax({
url: 'https://my.url.com/aBlah?bBlah?cBlah',
type:"GET",
data: { fields: "subdata" },
dataType: "jsonp",
contentType:"application/json",
jsonpCallback: myCallback,
success: function(data){
console.log(data.subdata.length);
'the rest of the code'
});
}
I am trying to get a cumulative total of data.subdata.length but I'm not sure how to go about getting it.
This is a classic use case for closures:
var closure = function(){
var counter = 0;
function getTheData(aBlah,bBlah,cBlah){
$.ajax({
url: 'https://my.url.com/aBlah?bBlah?cBlah',
type:"GET",
data: { fields: "subdata" },
dataType: "jsonp",
contentType:"application/json",
jsonpCallback: myCallback,
success: function(data){
counter += data.subdata.length;
'the rest of the code'
});
}
function getcount(){
return counter;
}
return {
getTheData:getTheData,
getcount:getcount
}
};
var myClosure= closure();
myClosure.getTheData(aBlah,bBlah,cBlah);
myClosure.getTheData(aStuff,bStuff,cStuff);
var count = myClosure.getcount();
This helps control the scope of the counter variable. So you can do things like:
var myClosure= closure();
myClosure.getTheData(aBlah,bBlah,cBlah);
myClosure.getTheData(aStuff,bStuff,cStuff);
var count = myClosure.getcount();
//counter in the new closure is zero
var newClosure = closure();
newClosure.getTheData(aBlah,bBlah,cBlah);
newClosure.getTheData(aStuff,bStuff,cStuff);
var totallyNewCount = myClosure.getcount();
I'm trying to make a log parser, that updates the log every 10 seconds. It's mostly functional, but when I try to update it, it just appends the whole log again, instead of just the new data.
My Javascript:
$(document).ready(function() {
var data;
var lines;
$.ajax({
async: false,
type: 'GET',
url: 'test.log',
success: function(log) {\
data = log;
lines = data.split("\n");
console.log("Received log");
}
});
function updateLog()
{
$.ajax({
async: false,
type: 'GET',
url: 'test.log',
success: function(log) {
data = log.replace(data, "");
lines = log.split("\n");
console.log("Received log");
}
});
$.each(lines, function(n, elem)
{
$('#text').append('<div>' + elem + '</div>');
});
}
$.each(lines, function(n, elem)
{
$('#text').append('<div>' + elem + '</div>');
});
setInterval(function(){updateLog();}, 10000);
});
Example test.log content:
Hello
How are you?
But instead of it only adding potential new lines, it just copies the whole thing even though I think it shouldn't happen because of the replace, which is supposed to take the old data and change it into '' in the new data (only leaving new lines).
It looks to me like you save only the new part of last request to data, so you are actually only replacing the part of the log that was new the last time you updated the log by an empty string. Moreover, you are not using data but log (which is the full log) to compute lines, and are appending all the lines in lines to your div.
I think something like this should work:
$(document).ready(function() {
var processed_data = '';
function updateLog() {
$.ajax({
async: false,
type: 'GET',
url: 'test.log',
success: function(log) {
var new_data = log.replace(processed_data, '');
processed_data = log;
console.log("Received log");
var lines = new_data.split('\n');
$.each(lines, function(n, elem) {
$('#text').append('<div>' + elem + '</div>');
});
}
});
}
updateLog();
setInterval(function(){updateLog();}, 10000);
});
Note that I also got rid of some of the code duplication that was in your example by just calling updateLog() on load instead of copying its contents.
It would also probably be more efficient to just keep track of the length of the part of the log that is already printed. Something like this:
$(document).ready(function() {
var processed_data_length = 0;
function updateLog() {
$.ajax({
async: false,
type: 'GET',
url: 'test.log',
success: function(log) {
var new_data = log.substring(processed_data_length, log.length);
processed_data_length = log.length;
console.log("Received log");
$.each(lines, function(n, elem) {
$('#text').append('<div>' + elem + '</div>');
});
}
});
}
updateLog();
setInterval(function(){updateLog();}, 10000);
});
Strings are immutable, so the log variable isn't updated by the .replace() call. Your ajax should probably look like:
$.ajax({
async: false,
type: 'GET',
url: 'test.log',
success: function(log) {
data = log.replace(data, "");
lines = data.split("\n");
console.log("Received log");
}
});
Hello Fellow Developers,
I have a SSN textbox that onblur calls a function which does an ajax request to a Web Method to decide if an employee has been previously hired.
The Web Method returns a TermedEmployee Object to the success callback, but I'm unsure how to parse the object.
$('#<%=FormView1.FindControl("SSNField").ClientID%>').blur(hideValue);
hideValue = function (ev) {
var $this = $(this);
$this.data('value', $this.val());
$('#<%=FormView1.FindControl("hiddenSSN").ClientID%>').val($this.val());
var data2Send = '{"SSN": ' + $this.val() + ' }';
$.ajax({
type: "POST",
url: "AuthforHire.aspx/EmployeeisRehire",
data: data2Send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var obj = JSON.stringify(result.d);
if (obj.IsTermed) {
$('#%=RadWindowRehire.ContentContainer.FindControl("TextBoxTermID").ClientID%>').val(arg.d);
var wndWidth = 900;
var wndHeight = 500;
var wnd = window.radopen(null, "RadWindowRehire");
}
},
error: function (xhr) {
alert('Form update failed. '); //error occurred
}
});
Below is a minified version of my webMethod, which works correctly
[System.Web.Services.WebMethod]
public static TermedEmployee EmployeeisRehire(string SSN)
{
TermedEmployee termedEmp = new TermedEmployee();
// Db call to get necessary data.
termedEmp.Name = dr["name"];
termedEmp.TermDate = Convert.ToDateTime(dr["TermDate"].ToString());
......
}
So How Can I extract Name, TermDate,StartDate, ReasonforTerm, etc from the object returned to the callback function?
Thank you in advance!
The first line in your success callback is:
var obj = JSON.stringify(result.d);
Which is trying to serialize what ASP.Net will already have serialized for you.
Change this to:
var obj = result.d;
And you will then have access to obj.Name, obj.TermDate and all the other properties by name.