Display contents in text file using ajax - ajax

I am new to using ajax (I am retaking my web engineering class this semester) and I am able to pull a text file from the server and am able to get it to display. It is displaying on my HTML page like this:
New York 8,143,197 Los Angeles 3,844,829 Chicago 2,842,518 ...
but i want it do display the cities in one column, and the population in another.
What can I do? I have also not learned about jquery yet.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
// Get which country the user selected
var radioArray = document.myForm.countries;
var i;
var value;
for (i = 0; i < radioArray.length; i++) {
if (radioArray[i].checked) {
value = radioArray[i].value;
}
}
if (value == "usa") {
xmlhttp.open("GET","http://localhost/~ercanbracks/usa.txt",true);
}
if (value == "canada") {
xmlhttp.open("GET","http://localhost/~ercanbracks/canada.txt",true);
}
if (value == "mexico") {
xmlhttp.open("GET","http://localhost/~ercanbracks/mexico.txt",true);
}
if (value == "russia") {
xmlhttp.open("GET","http://localhost/~ercanbracks/russia.txt",true);
}
xmlhttp.send();
}
</script>
</head>
<body onload="loadXMLDoc()">
<h1>Most populated cities in the world!</h1>
<form name="myForm" action="">
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="usa" checked>USA
<br/>
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="canada">Canada
<br/>
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="mexico">Mexico
<br/>
<input type="radio" name="countries"
onchange="loadXMLDoc()" value="russia">Russia
</form>
<div id="myDiv"></div>
</body>
</html>

You are assigning the whole response text to your element "myDiv" no matter what the response is. You need to first process the data from the response (xmlhttp.responseText) - in such way that you can separate city - population pairs, and based on how many rows of the pairs you get, you can for example create a new table element, and specify the rows and cells of the table.
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var dataToProcess = xmlhttp.responseText;
// process the data to get city-population pairs - assign them to an array for example
//...
// Create a new table element
var Table = document.createElement("Table");
// Foreach city-population pair, create one row and specify it's cells
for (var i = 0; i < YourArray.length; i++)
{
row = Table.insertRow(i);
cell1 = row.insertCell(0);
cell1.innerHTML = 'Your city value'; // YourArray[i]['City'];
cell2 = row.insertCell(1);
cell2.innerHTML = 'Your population value'; // YourArray[i]['Population'];
}
// Assign the table to a parent element
document.getElementById("your parent element").appendChild(Table);
// Be careful to which element you assign the new table element as a child, so that the page content don't need to be redrawn to make it visible
}
}
}

Related

XML data pasing

Hi I am trying to display data from XML file to unordered list. Any help would be great. I do have an XML file books data wherein trying to print or display the books author etc.
<!DOCTYPE html>
<html>
<style>
</style>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
report(this);
}
};
xmlhttp.open("GET", "cd_catalog.xml", true);
xmlhttp.send();
}
function report(xml){
var i;
var xmlDoc=xmlhttp.responseXML;
var table = "";
var x = xmlDoc.getElementByTagName("CD");
for(i=0; i<x.length; i++){
table+="<li>" + x[i].getElementByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</li>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
<body>
<ul id="demo"></ul>
<button type="submit" onclick="loadDoc()">RUUUUNNNNN</button>
</body>
</html>

How to integrate svg-edit to ASP.NET MVC application

I am about to integrate svg-edit to an ASP.NET MVC project.
Is there anyone who has a recommendation or tutorial on how to begin with?
Thank you.
I am answering my own question.
After a research, I recommend deploying the whole SVG-EDIT lib into mvc architecture, then modify the embed api as following:
This is my Partial View and JS file that call the embed api and put it into the iframe within the partial view:
document.write("<script type='text/javascript' src='~/Scripts/svg-edit/embedapi.js'></script>");
// Make sure to add the embedapi into the html file, becuase the intialization function runs actually in that file, all this call does is basically to take the iframe from html and inialize the api within that tag.
$(document).ready(function () {
// jquery selectro
$("#LoadSVG").click(function () {
$("#svg").append($('<iframe src="/Scripts/svg-edit/svg-editor.html" width="900px" height="600px" id="svgedit"></iframe>'));
});
});
#Scripts.Render("~/bundles/KSage")
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<header>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</header>
<input id="LoadSVG" type="button" value="LoadSVG" />
<input id="CloseSVG" type="button" value="CloseSVG" />
<input id="save" type="button" value="save" onclick="save()">
<input id="Add" type="button" value="AddNewTag!" onclick="AddNewElemnt()" />
<input id="LoadExample" type="button" value ="LoadExample" onclick="LoadExample()"/>
<body id ="mainBody">
<p id="svg"></p>
<p id="DivData"></p>
<p id="TestId"></p>
<p id="SavedData"></p>
</body>
</html>
Here I have a save and load functions ready for the module: There is so much work to do in order to perfect the algorithm, but since this was just a test project to figure out the possibility of integrating the module into the environment I put enough effort to understand that share the knowledge with the community:
Here is my cshtml file:
#Scripts.Render("~/bundles/KSage")
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<header>
</header>
<input id="LoadSVG" type="button" value="LoadSVG" />
<input id="CloseSVG" type="button" value="CloseSVG" />
<input id="save" type="button" value="save" onclick="save()">
<input id="Add" type="button" value="AddNewTag!" onclick="AddNewElemnt()" />
<input id="LoadExample" type="button" value ="LoadExample" onclick="LoadExample()"/>
<body id ="mainBody">
<p id="svg"></p>
<p id="DivData"></p>
<p id="TestId"></p>
<p id="SavedData"></p>
</body>
</html>
Here is the js file:
document.write("<script type='text/javascript' src='~/Scripts/svg-edit/embedapi.js'></script>");
document.write("<script src='~/Scripts/jquery-1.10.2.js'></script>");
$(document).ready(function () {
// jquery selectro
$("#LoadSVG").click(function () {
$("#svg").append($('<iframe src="/Scripts/svg-edit/svg-editor.html" width="900px" height="600px" id="svgedit"></iframe>'));
});
});
$(document).ready(function () {
// jquery selectro
$("#save1").click(function () {
$("#DivData").append("<b>Appended text</b>");
});
});
$(document).ready(function(){
$("#CloseSVG").click(function () {
$("#svg").hide();
});
});
function HandleSvgData(data,error) {
if (error) {
alert('Error:' + error);
} else {
$('#DivData').append(data);
alert(data);
}
}
function handleSvgData(data, error) {
alert("handling Data");
if (error) {
alert('error ' + error);
} else {
alert('Congratulations. Your SVG string is back in the host page, do with it what you will\n\n' + data);
}
}
function save1() {
alert("saving");
// svgCanvas.getSvgString()(handleSvgData);
$("#svgedit").append($('This is the test classed appended after DivDat'));
}
function AddNewElemnt()
{
var newElement = document.createElement("Test");
var newNode = document.createTextNode("This is my new node!");
newElement.appendChild(newNode);
var referenceElement = document.getElementById("mainBody");
var tagInsert = document.getElementById("TestId");
referenceElement.insertBefore(newElement, tagInsert);
// alert("added");
}
function Postt(data) {
}
function Post(data) {
var mainBody = document.getElementById("mainBody");
var SvgDataId = prompt("give me primary id");
var SvgUser = prompt("give me UserName");
var form = document.createElement("form");
form.setAttribute("id", "PostData");
form.setAttribute("action", "/SvgDatas/Create");
form.setAttribute("method", "post");
mainBody.appendChild(form);
var PostData = document.getElementById("PostData");
var InputSvgDataId = document.createElement("input");
InputSvgDataId.setAttribute("name", "SvgDataId");
InputSvgDataId.setAttribute("value", SvgDataId);
PostData.appendChild(InputSvgDataId);
var InputSvgUser = document.createElement("input");
InputSvgUser.setAttribute("name", "SvgUser");
InputSvgUser.setAttribute("value", SvgUser);
PostData.appendChild(InputSvgUser);
var InputData = document.createElement("input");
InputData.setAttribute("name", "Data");
InputData.setAttribute("value", data);
PostData.appendChild(InputData);
form.submit();
}
function save() {
var doc, mainButton,
frame = document.getElementById('svgedit');
svgCanvas = new EmbeddedSVGEdit(frame);
// Hide main button, as we will be controlling new, load, save, etc. from the host document
doc = frame.contentDocument || frame.contentWindow.document;
mainButton = doc.getElementById('main_button');
mainButton.style.display = 'none';
// get data
svgCanvas.getSvgString()(function handleSvgData(data, error) {
if (error) {
alert('error ' + error);
} else {
alert('Congratulations. Your SVG string is back in the host page, do with it what you will\n\n' + data);
Post(data);
}
});
}
/*
function BuidUrl(SVGUser) {
var uri = prompt("Give me url where the serach function lives, if empty then I will use Razor syntax to call within MVC architescture");
if (uri)
return uri;
else {
var urlHelper = ('http://localhost:53546/SvgDatas/Search?id='+SVGUser);
return urlHelper;
}
}
*/
function returnedData_IntializeEditor(data, status) {
if ((data != null) && (status == "success")) {
var frame = document.getElementById('svgedit');
svgCanvas = new EmbeddedSVGEdit(frame);
doc = frame.contentDocument || frame.contentWindow.document;
mainButton = doc.getElementById('main_button');
tool_Bottum = doc.getElementById("#tool_button");
mainButton.style.display = 'none';
// Open Data into the frame
// var svgexample = '<svg width="640" height="480" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><g><title>Layer 1<\/title><rect stroke-width="5" stroke="#000000" fill="#FF0000" id="svg_1" height="35" width="51" y="35" x="32"/><ellipse ry="15" rx="24" stroke-width="5" stroke="#000000" fill="#0000ff" id="svg_2" cy="60" cx="66"/><\/g><\/svg>';
svgCanvas.setSvgString(data.Data);
} else {
$("#svg").append("<li>There is not such a data available in the database!</li>");
}
}
function LoadExample() {
var SVGUser = prompt("Enter the SVG ID");
$.getJSON("http://localhost:53546/SvgDatas/Search?id=" + SVGUser, returnedData_IntializeEditor );
}
This is the model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace IntegrationOfSVG.Models
{
public class SvgData
{
public string SvgDataId { get; set; }
public string SvgUser { get; set; }
public string Data { get; set; }
}
}
Thank you SVG-EDIT community for the great tool.
Next I am planning to add a view mode to this module that opens the data from a sequal server and if the mode is admin, lets the user to edit the existing data. I will keep this posted updated.
1- One way is to remove the tools from the client side, but it has a certain limitation that is the fact that css does not adjust a
function RemoveTools() {
var frame = document.getElementsByClassName("iFrameHtmlTag")[0];
doc = frame.contentWindow.document;
if (doc != null) {
var Tools = [
'tools_top', 'tools_left', 'tools_bottom', 'sidepanels', 'main_icon', 'rulers', 'sidepanels', 'canvashadow'];
for (i=0; i<Tools.length;i++)
{
doc.getElementById(Tools[i]).style.display = "none";
}
} else
alert("Doc was null");
};
$(document).ready(function () {
$("#hide").click(function () {
RemoveTools();
});
});
It is an effective way, but there should be a better method to view the object with few parameters also to readjust the size of the window. I will continue with that topic too.

AJAX: I am unable to fetch the data from server side

I need to get output from my server side code but i am able to fetch it.
I have used script manager and script manager proxy control in master page.
How can i get the string that is being returned from the cs file
Here is my Default.aspx code
<asp:UpdateProgress runat="server">
<ProgressTemplate >
Loading..........
</ProgressTemplate>
</asp:UpdateProgress>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Label ID="lbl" Text="Enter Your Name" runat="server"></asp:Label>
<input type="text" id="txt" /><br />
<input type="button" id="btn" value="Submit" onclick="makeGetRequest()" />
<div id="description">Hello</div>
</ContentTemplate>
</asp:UpdatePanel>
<script language="Javascript" type="text/javascript" >
function createRequestObject() {
var tmpXmlHttpObject;
if (window.XMLHttpRequest) {
// Mozilla, Safari would use this method ...
tmpXmlHttpObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// IE would use this method ...
tmpXmlHttpObject = new ActiveXObject("Microsoft.XMLHTTP");
}
return tmpXmlHttpObject;
}
var http = createRequestObject();
function makeGetRequest() {
http.open('post', 'Default.aspx/greet',true);
//assign a handler for the response
http.onreadystatechange = processResponse;
//actually send the request to the server
http.send(null);
}
function processResponse() {
if (http.readyState == 4) {
var response = http.responseText.toString();
alert("Inside here before");
document.getElementById('description').innerHTML = response;
alert("Inside here after");
}
}
</script>
// my default.aspx.cs file
[WebMethod(EnableSession=false)]
public static string greet()
{
return "hello";
}
I am getting all contents of the page copied instead of getting response from it
the line var http = createRequestObject(); have to be the first line inside function makeGetRequest() function. anyway, i am posting a working code.
<script language="Javascript" type="text/javascript" >
function makeGetRequest() {
var http;
if (window.XMLHttpRequest) {
http = new XMLHttpRequest();
} else if (window.ActiveXObject) {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
var response = http.responseText.toString();
alert("Inside here before");
document.getElementById('description').innerHTML = response;
alert("Inside here after");
}
}
http.open('post', 'Default.aspx/greet', true);
http.send(null);
}
</script>

Finding the distance between 2 points using Google Maps API

I am trying to find the distance between 2 points, one being from user input and the other an address from my database. I have put together the code below, which seems to work (I have test variables in place so no database pulls are being made for testing), however I have hit a wall; I cannot figure out why I need to click the button twice for the output to show?
Any help is much appreciated
CODE BELOW:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API Example: Extraction of Geocoding Data</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
<!-- According to the Google Maps API Terms of Service you are required display a Google map when using the Google Maps API. see: http://code.google.com/apis/maps/terms.html -->
<script type="text/javascript">
//var globalAddr = new Array();
var globalName;
var xmlhttp;
var geocoder, location1, location2;
var distanceVal;
function initialize() {
geocoder = new GClientGeocoder();
}
function showLocation() {
geocoder.getLocations(document.getElementById("address1").value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the first address");
}
else
{
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
geocoder.getLocations(document.getElementById("address2").value, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the second address");
}
else
{
location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
calculateDistance();
}
});
}
});
}
function calculateDistance()
{
var glatlng1 = new GLatLng(location1.lat, location1.lon);
var glatlng2 = new GLatLng(location2.lat, location2.lon);
var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
var kmdistance = (miledistance * 1.609344).toFixed(1);
distanceVal = miledistance;
}
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function getData(str)
{
loadXMLDoc("getData.php?address="+str,function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var x = xmlhttp.responseText;
var dnames = x.split("~~~");
var daddr = x.split("^^^");
daddr.shift();
dnames.pop();
var testArray = new Array('85281','18657','90210');
var shortest = 999999;
for(var i = 0; i <= testArray.length-1; i++)
{
document.getElementById("address2").value = testArray[i];//daddr[i];
showLocation();
//i get a blank alert 3 times here the first time, then I get the a value the 2nd time.. makes no sense!
alert(distanceVal);
if (shortest > distanceVal)
{
shortest = distanceVal;
globalName = dnames[i];
}
}
document.getElementById("results").innerHTML = globalName + " " + shortest;
}
})
}
</script>
</head>
<body onload="initialize()">
<form>
<p>
<input type="text" id="address1" name="address1" class="address_input" size="40" />
<input type="hidden" id="address2" name="address2" />
<input type="hidden" id="distance" name="distance" />
<input type="button" name="find" value="Search" onclick="getData(document.getElementsByName('address1')[0].value)"/>
</p>
</form>
<p id="results"></p>
</body>
</html>
When you call showLocation() in your getData() callback, that sets off two geocoder calls and if both are successful calls calculateDistance().
However, both those geocoder calls take time. The first getLocations() sets off a geocode request and lets it continue, to be dealt with in its callback. Within that function, there's another request which is dealt with in its own callback.
While those are waiting for results, the code execution has carried on and reached alert(distanceVal) even though calculateDistance() hasn't been called yet. Consequently distanceVal isn't set yet.
When you click the button again, the global distanceVal will have been populated through all the callback functions, so (even though the second set of geocodes/callbacks have not completed), it will have a value to display. However, if you change the values you are testing, you will find it's displaying the old value which is now incorrect.
Everything which depends on values found in a callback function must be processed within that callback function. If you move the display of data into calculateDistance() everything will be fine, because the data is available to that function.

Convert normal links to Ajax dynamically

I have put together some code from various sources but javascript is somewhat unknown to me and I only seem to fail with the code I have so far..
What I want to do is convert every normal link on the page to ajax links and load the pages through ajax.
So far I only succeeded to transform the links from the initial page and load the content in a div. The problem is I don't have access to the content is loading in the div and the new content still has normal links instead of ajax.
Is there a way I can convert the new links within the content loaded in the div, every time the div changes?
Also what I don't know is, if the user clicks on the home button in the menu, it will load the content of index along with this script, and everything will become a loop. How can I prevent the code from loading in index if it loads inside the div?
If you suspect any other problems it may occur from this code can you please advice me what to change?
This is the code I have so far..
Thank you very much for any advice!
Inserted in the head tag:
<script type="text/javascript">
var xmlhttp;
if(window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
else if(window.ActiveXObject){ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
else{ }
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4)
{ document.getElementById("contentarea").innerHTML = xmlhttp.responseText; }
else{ document.getElementById("contentarea").innerHTML = ""; }
}
function loadPage(url){
document.getElementById("contentarea").innerHTML = "";
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
</script>
Inserted somewhere in the body:
<div id="contentarea"></div>
Inserted right before the body ends:
<script>
var oP = document.getElementsByTagName("a");
var ctr=0;
while(ctr < oP.length){
var oldHref = document.getElementsByTagName("a")[ctr].href;
document.getElementsByTagName("a")[ctr].href="javascript:loadPage('"+oldHref+"');";
ctr++;
}
</script>
here ja go.. whipped this up for you.. you can use document.links to get all anchor tags. I'm doing this on 'contentArea' only. Everything inside (function () { will only be called when the document is ready. Then, in the onreadystatechange event I call the function again to set the click event on any anchors that are returned in the resposne.
<script type="text/javascript">
var xmlhttp;
function loadPage(url){
document.getElementById("contentarea").innerHTML = "";
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
var parseAnchors = function(){
var anchors = document.getElementById("contentarea").links; // your anchor collection
var i = anchors.length;
while (i--) {
var anchor = anchors[i];
anchor.onclick = (function(url) {
return function() {
loadPage(url);
return false;
};
})(anchors[i].href);
anchor.href = "#";
}
};
(function () {
if(window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest(); }
else if(window.ActiveXObject){ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
else{ }
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4)
{ document.getElementById("contentarea").innerHTML = xmlhttp.responseText; }
else{ document.getElementById("contentarea").innerHTML = ""; }
parseAnchors();
}
window.onload = function () {
parseAnchors();
}
</script>

Resources