Retriving JSON values from asp.net response with jQuery - javascript

I'm working on a small project. Mostly to gain some understanding because I am a complete web noob. Which may or may not be apparent in the following question(s).
My end result is fetching a bunch of values from a database. Putting them into a JSON object and then using some jQuery/JavaScript to work with the data. I've been doing a ton of reading, been through tons of posts on here but I can't find something as it relates to my problem.
I'm working in VS2010 C#. I'm bound by IE7 on the client side, but I can test with Firefox. I'm also working on localHost for now.
My JavaScript is as follows.
function plotMarkers() {
var pathStart = new String(window.location);
var newPath = pathStart.replace("Default.aspx", "getMarkers.aspx");
alert(newPath);
$("#statusDiv").html('JSON Data');
$.getJSON(newPath, function (data) {
alert("Loading JSON");
$.each(data, function (index, elem) {
var myLatlng = new google.maps.LatLng(elem.lat, elem.lng);
var marker = new gogle.maps.Marker({
position: myLatlng,
title: elem.title
});
marker.setMap(map);
});
}, function () { alert("loaded") });}
I don't get any Javascript errors in Firefox, but I do in IE7. The alert("Loading JSON") never fires anywhere. I've never seen it.
My getMarkers.aspx code
public partial class getMarkers : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
JavaScriptSerializer jsonSer = new JavaScriptSerializer();
List<marker> markerList = new List<marker>();
markerList.Add(new marker(-34.397, 150.644, "Test"));
markerList.Add(new marker(-50, 150.644, "Test2"));
string sJSON = jsonSer.Serialize(markerList);
Response.ContentType = "application/json";
Response.Write(sJSON);
}
}
I can click the link in "statusDiv" and it takes me to the aspx page. I get an error in IE7 but it works fine in Firefox. The JSON that is parsed back to me in those pages is correct. I copy and pasted the response in another function and the plotter put the two pins on my map.
The code does not seem to enter the $.getJSON function.
There is a problem with IE7 (or a problem in general) with how my getMarkers.aspx is set up. Googled some tutorials and this is where I ended up. I might be completely wrong in my approach. Or I missed something I was supposed to do. I can't seem to find that specific tutorial, it must have been closed on accident amidst my furious 2 day and counting Google adventure.
Firefox getMarkers.aspx displays the JSON as the first line followed by the html. Just plaintext in the browser.
IE7 displays an XML error and tells me the JSON string isn't allowed at the top level of the document. I did read some articles about IE7 always trying to parse XML with an elaborate workaround. Which I can't do, because I don't know how many clients will be using it. Is there a better way to do what I'm doing?
If anyone could point me in the direction I need to go I would greatly appreciate it. Hopefully my post isn't too convoluted.

You probably want a Response.End() at the end of your page load method, so that the rest of the web page isn't rendered after your JSON.

It looks to me, for starters, that you need the json2 library to handle the issues with IE7.
As for firing your function - I can't see anywhere where plotMarkers() is actually called, it's only defined?

Are you trying to display markers on a map in an existing page when the #statusDiv link is clicked ?
If so, you're doing it wrong : dont put a link in #statusDiv, just make sure the getJSON function is called when you click on it. try this :
function plotMarkers() {
var pathStart = new String(window.location);
var newPath = pathStart.replace("Default.aspx", "getMarkers.aspx");
alert(newPath);
$("#statusDiv").text('JSON Data');
$("#statusDiv").on('click',function(){
$.getJSON(newPath, function (data) {
alert("Loading JSON");
$.each(data, function (index, elem) {
var myLatlng = new google.maps.LatLng(elem.lat, elem.lng);
var marker = new gogle.maps.Marker({
position: myLatlng,
title: elem.title
});
marker.setMap(map);
});
}, function () { alert("loaded") });
});
}

Related

Google Apps Script JSON.Parse causing 'could not connect to server' on debug

I'm by no means what I would call a "developer" but dabble quite a bit. I'm working on some Apps Script code to query an API and push the results into SQL. I have most of the bits working but I've noticed that while I'm debugging in the Apps Script editor, when I step into the following line of code, the editor throws the "could not connect to server message at the top.
var response = UrlFetchApp.fetch(clientApiURL,options);
var resultSet = JSON.parse(response.getContentText()); <-- this is the line that is crashing the IDE
Anyone know how to better debug this? When I'm not debugging it, the code seems to behave and function properly. But with this API, not all objects are formatted the same way, so I like to use the debugger to inspect them. I can do that when the editor crashes.
Any help/insight would be super appreciated. I've also pasted below the value of response.getContentText()
{"result":{"lead":[{"id":"332","accountID":null,"ownerID":null,"companyName":"","title":null,"firstName":"RYAN","lastName":"CAVANAUGH","street":null,"city":null,"country":null,"state":null,"zipcode":null,"emailAddress":"email#here.com","website":null,"phoneNumber":null,"officePhoneNumber":null,"phoneNumberExtension":null,"mobilePhoneNumber":null,"faxNumber":null,"description":null,"campaignID":"789934082","trackingID":"202003_5e6fa18a87853a69eb306910","industry":null,"active":"1","isQualified":"1","isContact":"1","isCustomer":"1","status":"4","updateTimestamp":"2020-05-08 20:24:48","createTimestamp":"2020-05-03 20:23:29","leadScoreWeighted":"23","leadScore":"26","isUnsubscribed":"0","leadStatus":"customer","persona":"","product_5e554b933fb5b":""}]},"error":null,"id":"5222020","callCount":"215","queryLimit":"50000"}
This will reproduce the error:
function test(){
var obj={"result":{"lead":[{"id":"332","accountID":null,"ownerID":null,"companyName":"","title":null,"firstName":"RYAN","lastName":"CAVANAUGH","street":null,"city":null,"country":null,"state":null,"zipcode":null,"emailAddress":"email#here.com","website":null,"phoneNumber":null,"officePhoneNumber":null,"phoneNumberExtension":null,"mobilePhoneNumber":null,"faxNumber":null,"description":null,"campaignID":"789934082","trackingID":"202003_5e6fa18a87853a69eb306910","industry":null,"active":"1","isQualified":"1","isContact":"1","isCustomer":"1","status":"4","updateTimestamp":"2020-05-08 20:24:48","createTimestamp":"2020-05-03 20:23:29","leadScoreWeighted":"23","leadScore":"26","isUnsubscribed":"0","leadStatus":"customer","persona":"","product_5e554b933fb5b":""}]},"error":null,"id":"5222020","callCount":"215","queryLimit":"50000"}
var resultSet = JSON.parse(obj);
}
Taking a look at the problem:
function test(){
var obj={"result":{"lead":[{"id":"332","accountID":null,"ownerID":null,"companyName":"","title":null,"firstName":"RYAN","lastName":"CAVANAUGH","street":null,"city":null,"country":null,"state":null,"zipcode":null,"emailAddress":"email#here.com","website":null,"phoneNumber":null,"officePhoneNumber":null,"phoneNumberExtension":null,"mobilePhoneNumber":null,"faxNumber":null,"description":null,"campaignID":"789934082","trackingID":"202003_5e6fa18a87853a69eb306910","industry":null,"active":"1","isQualified":"1","isContact":"1","isCustomer":"1","status":"4","updateTimestamp":"2020-05-08 20:24:48","createTimestamp":"2020-05-03 20:23:29","leadScoreWeighted":"23","leadScore":"26","isUnsubscribed":"0","leadStatus":"customer","persona":"","product_5e554b933fb5b":""}]},"error":null,"id":"5222020","callCount":"215","queryLimit":"50000"}
var resultSet = JSON.parse(JSON.stringify(obj));
}
but so what the point of the parse is to return an object from a string not from object.
But I do see the problem. 'Cannot connect to the server'
I found that this does seem to work know:
function test(){
var obj='{"result":{"lead":[{"id":"332","accountID":"","ownerID":"","companyName":"","title":"","firstName":"RYAN","lastName":"CAVANAUGH","street":"","city":"","country":"","state":"","zipcode":"","emailAddress":"email#here.com","website":"","phoneNumber":"","officePhoneNumber":"","phoneNumberExtension":"","mobilePhoneNumber":"","faxNumber":"","description":"","campaignID":"789934082","trackingID":"202003_5e6fa18a87853a69eb306910","industry":"","active":"1","isQualified":"1","isContact":"1","isCustomer":"1","status":"4","updateTimestamp":"2020-05-08 20:24:48","createTimestamp":"2020-05-03 20:23:29","leadScoreWeighted":"23","leadScore":"26","isUnsubscribed":"0","leadStatus":"customer","persona":"","product_5e554b933fb5b":""}]},"error":"","id":"5222020","callCount":"215","queryLimit":"50000"}';
var resultSet = JSON.parse(obj);
var end="is near";//I just put this here to have a place to stop with debugger running
}
I replaced all of the null s with "".

Getting GeoJSON from Google Spreadsheets

I would like to have an option to save the geoJSON file from Google Spreadsheets.
The issue has been raised here:
https://gis.stackexchange.com/questions/140995/publishing-google-sheet-to-web-as-geojson-file
although the plugin available here:
https://github.com/mapbox/geo-googledocs/
doesn't work because the geocode receiving the error message:
https://github.com/mapbox/geo-googledocs/issues/42
UiApp has been deprecated. Please use HtmlService instead.
I tired to combine the existing code, provided by this plugin with the code proposed as a way to fixing this issue:
https://gist.github.com/hidrodixtion/c3a6b6ba7af624d1800625efb7a40fbd
The code name is Geo.js as per the plugin provided above
I put the function doGet above the Geocoders as per below:
// Global variables
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
var ss = SpreadsheetApp.getActiveSpreadsheet(),
sheet = ss.getActiveSheet(),
activeRange = ss.getActiveRange(),
settings = {};
var geocoders = {
yahoo: {
... another part of the code available here:
https://raw.githubusercontent.com/mapbox/geo-googledocs/master/MapBox.js
unfortunately it doesn't work.
It seems like I don't know where I must superseed the depreciated UiApp function with the HTML service.
The problem is, that I don't know what part of the code in the Geo plugin should be replaced. It might be really helpful as the plugin can do the geocoding either.
My another part of combination was as follows:
I changed the code:
// Create a new UI
var app = UiApp.createApplication()
.setTitle('Export GeoJSON')
.setStyleAttribute('width', '460')
.setStyleAttribute('padding', '20');
into:
var app = HtmlService.createHtmlOutput().setWidth(800).setHeight(600);
.setTitle('Export GeoJSON') //line 105
.setStyleAttribute('width', '460')
.setStyleAttribute('padding', '20');
but once I save now I get this:
Syntax error. (line 105, file "Geo")
I picked up this code from here:
https://gist.github.com/hidrodixtion/c3a6b6ba7af624d1800625efb7a40fbd
line 141
Does anybody knows how to fix this issue?

jQuery: Controller function not being executed correctly with ajax

I am programming a web application in C# MVC which dynamically loads information from a server in order to improve the speed.
Currently I have some errors and I am unable to diagnose why these are causing issues so I'll try my best to explain what's happening:
This div is created many times and grabs the ID for each project.
<div>
Open:
#{string JiraKey = item.JiraProjectKey;}
<span id="JiraOpen" onload="GetOpenJira"></span>
</div>
Then in the span, the script GetOpenJira is initiated:
<script id="GetOpenJira">
var url = "/HicVault/Projects/GetNumJiraOpenByKey";
var key = $('#JiraKey').val();
$.get(url, { input: key }, function (data) { $("#JiraOpen").html(data) });
</script>
This script SHOULD asynconously ask the controller to complete the function GetNumJiraOpenByKey with the JiraKey being used as a parameter. The function in the controller is:
[HttpGet]
public ActionResult GetNumJiraOpenByKey(string JiraProjectKey)
{
var sJql = "project = \"" + JiraProjectKey + "\" and status = \"Open\"";
var resultFieldNames = new List<string> { "resolution" };
Issues issues = new JiraClient(new JiraAccount()).GetIssuesByJql(sJql, 0, 1000, resultFieldNames);
return PartialView(issues.total);
}
Essentially this function returns an int once it has counted all of the issues for that particular project. I would like this to be done with AJAX using jQuery to load these values after the page has been loaded to vastly increase speed. (Currently without AJAX, pages take >30 sec to load).
Thanks if anyone can help.
EDIT: I suppose I should ask a question, currently with this code the page loads and after around 5 seconds, a server 500 error appears in the console stating there is an Internal Server Error. I know this is a general error, going in deeper points to the line:
"$.get(url, { input: key }, function (data) { $("#JiraOpen").html(data) ".
I am guessing either the logic of my work isn't possible in Razor MVC + JS, or I am getting the fundamentals of jQuery ajax get wrong?
rewrite your script as following...
<script id="GetOpenJira">
var url = "/HicVault/Projects/GetNumJiraOpenByKey";
var key = $('#JiraKey').val();
$.get(url, { JiraProjectKey: key }, function (data) { $("#JiraOpen").html(data) });
</script>

JavaScript to save MAFF in Firefox

I am experimenting with iMacros to automate as task that Firefox will do. I simply want to save the current page with the MAFF extension. The JavaScript that the iMacros forum has lead me to, is this:
// I stuck these variable in just to try something.
var doc = "http://www.traderjoes.com";
var file = "C:\\Export\\Test.maff";
var format = "MAFF";
// I stuck these variable in just to try something.
var MafObjects = {};
Components.utils.import("resource://maf/modules/mafObjects.jsm",
MafObjects);
var jobListener = {
onJobComplete: function(aJob, aResult) {
if (!Components.isSuccessCode(aResult)) {
// An error occurred
} else {
// The save operation completed successfully
}
},
onJobProgressChange: function(aJob, aWebProgress, aRequest,
aCurSelfProgress,
aMaxSelfProgress,
aCurTotalProgress,
aMaxTotalProgress) { },
onStatusChange: function(aWebProgress, aRequest, aStatus,
aMessage) { }
};
var saveJob = new MafObjects.SaveJob(jobListener);
saveJob.addJobFromDocument(doc, file, format);
saveJob.start();
I was only getting an error on line 26 because this was sample code. With the little JavaScript I know I tried to add some variables on the lines before the code starts. The thing is that when I try to search for syntax example for the method .addJobFromDocument I don’t find much, just like two results. Is this a method of JavaScript? Usually with things from the DOM you will get a great deal of information on them.
Does anybody know a way of automating the save of MAFF of the current open tab in Firefox and then closing the browser? iMacros was something I came to and glad to see it features but really I just want to automate from a command line the saving of a URL as a MAFF archive The doc (that I got from iMacros forum) also had these code snippets but I don’t have much idea how to use them. Thanks
var fileUri = Components.
classes["#mozilla.org/network/io-service;1"].
getService(Components.interfaces.nsIIOService).
newFileURI(file);
var persistObject = new MafObjects.MafArchivePersist(null, format);
persistObject.saveDocument(doc, fileUri);
Also:
var doc = gBrowser.contentDocument;
var file = Components.classes["#mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("C:\\My Documents\\Test.maff");
var format = "TypeMAFF";

Google Map API V3: Parsing an XML document

I'm trying to update my Google Maps API web application that I had running fine under version two. Version three seems not only to have broken everything but also has placed the burden of writing one's own versions of a lot of missing API functions that are no longer there.
Soooo, what was a relatively simple adaptation of their "store locator" example under version two has turned into a gigantic headache.
More specifically, my problem is parsing the XML document that my PHP/mySQL code returns after the user has entered some data into the web page and sent it off to the server. I know that the test data that I've been entering works because, 1. it worked flawlessly under V2, and 2., If I hardcode it into the PHP page and then load that page I get the expectant XML document loaded in my browser (Firefox 3.6.13 running on Snow Leopard).
Update: After very careful tracing with Firebug I've discovered that "downloadUrl" function from here is returning the data correctly.
However, it looks like the function "GXml.parse(data)" ( from here) isn't processing the returned XML. I'm pasting that code below:
function GXml(){}
GXml.value=value;
GXml.parse=parse;
function value(node){
if(!node){
return"";
}
var retStr="";
if(node.nodeType==3||node.nodeType==4||node.nodeType==2){
retStr+=node.nodeValue;
}else if(node.nodeType==1||node.nodeType==9||node.nodeType==11){
for(var i=0;i<node.childNodes.length;++i){
retStr+=arguments.callee(node.childNodes[i]);
}
}
return retStr;
}
function parse(textDoc){
try{
if(typeof ActiveXObject!="undefined"&&typeof GetObject!="undefined"){
var b=new ActiveXObject("Microsoft.XMLDOM");
b.loadXML(textDoc);
return b;
}else if(typeof DOMParser!="undefined"){
return(new DOMParser()).parseFromString(textDoc,"text/xml");
}else{
return Wb(textDoc);
}
}
catch(c){
P.incompatible("xmlparse");
}
try{
return Wb(textDoc);
}
catch(c){
P.incompatible("xmlparse");
return document.createElement("div");
}
}
function P(){}
P.write=function(a,b){}
;P.writeRaw=function(a){}
;P.writeXML=function(a){}
;P.writeURL=function(a){}
;P.dump=function(a){}
;P.incompatible=function(){}
;P.clear=function(){}
;
function Wb(a){
return null;
}
I dont bother parsing XML anymore.. much easier to convert it to JSON and stream it directly into objects.. one example:
Is this the fastest way to parse my XML into JavaScript objects using jQuery?
Duncan.
I'm having the same problems, but I found this after a little bit of search. I haven't followed the tutorial through all the way yet, but I thought I'd go ahead and share it.
http://code.google.com/apis/maps/articles/phpsqlsearch_v3.html
Mia

Categories