ASP.net run javascript in client context - javascript

The scenario:
1) User logs in using a browser tab.
2) user opens a new tab and navigates to my web application.
3) my web application executes following javascript to retrieve the user Email from his logged in session:
<script type="text/javascript" >
var xmlHttp = new XMLHttpRequest();
try
{
xmlHttp.open("GET", "https://www.someserver.com/api/getinfo.aspx?EMAIL", false);
xmlHttp.send(null);
}
catch (err) { alert(err.message);}
var data = xmlHttp.responseText;
if (data != "")
{
var json = JSON.parse(data);
alert(json.EMAIL);
}
else { alert(document.body.textContent);}
</script>
4)The problem: if I add this script into the markup of my page.aspx , then run the application with above steps, I fail to retrieve the Email, while if I copy and paste the URL "https://www.someserver.com/api/getinfo.aspx?EMAIL" in a new tab the browser displays the JSON response with Email correctly , what am I missing here?

Related

Webpage reloading on entering correct values

I've ran into an weird problem. I have created a login page which send data to a PHP page which return some response code like "00000" for ok "404" for not found etc. I have tested my server with Postman tool and found server is working perfectly fine. When my html send data to server server responds with response code. If the response code comes wrong html alert's it. However if I enter correct credentials and when server respond with success , My login page reloads for no reason.
Here's my javascript
function validatelog(){
var user_email_log=document.getElementById("user_email_log").value;
var user_pass_log=document.getElementById("user_pass_log").value;
if (user_email_log&&user_pass_log!=null)
{
var hr = new XMLHttpRequest();
var url = "../logic/login.php";
var vars =
"user_email_log="+user_email_log+"&user_pass_log="+user_pass_log;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var saman = hr.responseText.trim();
if(saman=="00000"){
alert(saman);
}else if (saman == "404"){
alert("Failed with 404");
}
else{
alert(saman);
}
}
}
hr.send(vars);
}
}
And my html looks like this
<input id="user_email_log"/>
<input id="user_pass_log"/>
<button onclick="validatelog();">Log in</button>
Add type="button" to the button:
<button type="button" onclick="validatelog();">Log in</button>
When it is not specified, it is the same as type="submit", and this will cause your page to reload.
if you use jquery you could do this.
$(document).on('click', 'button', function(e) {
e.preventDefault();
$.get('url')
})
I think the page is reloading because that is the default behavior.

Error when I click on href link with internet explorer 11

I have already checked this link Error when using js in href ie 11 but it does not resolve my problem.
My link is located on an application A and when I click on my link, I send an information to an application B:
Here is my link located on Application A:
<a target="_blank" href="javascript:displayInfinityPage({{userName}});">{{l10n "Data access"}} </a>
Here is my JavaScript function:
//Posts the username back to Application B
function displayInfinityPage(username){
window.opener.postMessage(username,"*");
}
This is how I receive data on Application B:
function onMessageApp(e) {
if (e.data != "1") {
var consumerPageSearchOpened = ((document.getElementById('DEBTOR_ID')) ? true:false);
if (e.origin == "http://10.1.92.3:9090" && consumerPageSearchOpened) {
document.getElementById("ID").value = e.data;
document.getElementByName("subcommand").click();
} else {
alert("Application B is rejecting message from "+e.origin+");
}
} else if (e.data == 1) {
alert("Update status");
command=collections.changeicstatus&i3_status=0
var url = document.getElementById("curSession").value+'?command=collections.changeicstatus&i3_status=0';
command=collections.changeicstatus&i3_status=0';
window.location = url;
window.opener.location.href = url;
}
}
window.addEventListener("message",onMessageApp,true);
This is the error I get:
this page can't be displayed make sure the web address //ieframe.dll/dnserror.htm# is correct
And Application A is opening a new tab with "javascript:displayInfinityPage({{147852}});" appears in the address bar instead of populating 147852 in Application B ("ID" field)
I have The same problem.
The error is: This page can’t be displayed.
Make sure the web address //ieframe.dll/dnserror.htm# is correct.

HTML and Android don't work together

Here is what I am trying do:
Save sensor info from Android tablet to txt file online
Open a webpage to read that data continuously using ajax calls
Note: Website and Android app are running simultaneously
Android part:
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://.../save.php");
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
Log.i("postData", response.getStatusLine().toString());
//Could do something better with response.
}
catch(Exception e)
{
Log.e("log_tag", "Error1: " + e.toString());
}
JS part
setInterval("DisplayBall()", 500);
function DisplayBall()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById("TotalTime").value = 0;
//alert(xmlHttp.responseText);
AssignResult(xmlHttp.responseText);
}
}
//xmlHttp.open("GET", "TINBCoordinates.txt", true);
//xmlHttp.send();
xmlHttp.open("GET", "read.php", true);
xmlHttp.send();
}
Why do these two interfere & make my program unresponsive?
Switch to using PhoneGap.js it will save you a lot of time.

HTML entities not recognized and not displayed when retrieved from ajax

This happens in all tested browsers (Chrome, Firefox, Opera ...)
Some HTML entities are are swallowed and not displayed when retrieved from ajax. The same HTML entity is displayed when it is hardcoded in the HTML source file.
Here is the actual output: (the entity is not display nether in the web page nor in the console)
Here is the expected output:
Here is the javascript that retrieves the entity:
<html><head><script type="text/javascript"> function injectEntity(){ var xhr = new XMLHttpRequest(); xhr.open("POST", "entity.php", true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ var doc = xhr.responseXML; console.log(xhr.responseText); var div = document.getElementById("container"); div.appendChild(doc.getElementById("the-entity")); } } xhr.send(null); }</script></head><body> inject the following entity: ’ <div id="container"> </div></body></html>
And here is the php file that is used to retrieve the entity:
<?phpheader('Content-type: application/xml; charset=UTF-8');$xml = new DOMDocument('1.0', 'utf-8');$tag = $xml->createElement('b','’');$tag->setAttribute("id","the-entity");$xml->appendChild($tag);echo $xml->saveXML();?>
You want ’, not ’ (which is an unprintable control character)

Reading Server Side file with Javascript

Does anyone know of a tutorial on how to read data from a server side file with JS? I cant seem to find any topics on this when I google it. I tried to use but it does not seem to work. I just want to read some data from a file to display on the page. Is this even possible?
var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();
To achieve this, you would have to retrieve the file from the server using a method called AJAX.
I'd look into JavaScript libraries such as Mootools and jQuery. They make AJAX very simple use.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
<script type="text/javascript">
//This event is called when the DOM is fully loaded
window.addEvent("domready",function(){
//Creating a new AJAX request that will request 'test.csv' from the current directory
var csvRequest = new Request({
url:"test.csv",
onSuccess:function(response){
//The response text is available in the 'response' variable
//Set the value of the textarea with the id 'csvResponse' to the response
$("csvResponse").value = response;
}
}).send(); //Don't forget to send our request!
});
</script>
</head>
<body>
<textarea rows="5" cols="25" id="csvResponse"></textarea>
</body>
</html>
If you upload that to the directory that test.csv resides in on your webserver and load the page, you should see the contents of test.csv appear in the textarea defined.
You need to use AJAX. With jQuery library the code can look like this:
$.ajax({ url: "test.csv", success: function(file_content) {
console.log(file_content);
}
});
or if you don't want to use libraries use raw XMLHTTPRequest object (but you I has different names on different browsers
function xhr(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
} catch(e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
req = xhr();
req.open("GET", "test.cvs");
req.onreadystatechange = function() {
console.log(req.responseText);
};
req.send(null);
UPDATE 2017 there is new fetch api, you can use it like this:
fetch('test.csv').then(function(response) {
if (response.status !== 200) {
throw response.status;
}
return response.text();
}).then(function(file_content) {
console.log(file_content);
}).catch(function(status) {
console.log('Error ' + status);
});
the support is pretty good if you need to support browser that don't support fetch API you can use polyfill that github created

Categories