How to get server time using javascript - javascript

I am changing my question What is missing or wrong in this code When user type something in the textboxt onother texbox supposed to get server time But nothing happens.I am so inexperience with programming.Can you plase help
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
Response.Write(DateTime.Now.ToShortTimeString());
Response.End();
}
<script type="text/javascript">
function ajaxFunction() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
document.getElementById("user").value = xmlHttp.responseText;
}
else {
document.getElementById("label").innerHTML = "wait";
}
xmlHttp.open("GET", "Default.aspx", true);
xmlHttp.send(null);
}
}
</script>
<title></title>
</head>
<body>
<input id="user" type="text" onkeyup="ajaxFunction()"/>
<p>
<input id="time" type="text" /></p>
<div id="label">
</div>
<p>
</p>
</body>
</html>

You misplaced the call to actually start the request
function ajaxFunction() {
var xmlHttp;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
document.getElementById("user").value = xmlHttp.responseText;
} // closes the if
else {
document.getElementById("label").innerHTML = "wait";
} // closes the else
} // closes the function() for onreadystatechange
// call the stuff
xmlHttp.open("GET", "Default.aspx", true);
xmlHttp.send(null);
}

Related

PHP ajax call failure

I am new to ajax and trying to create AJAX->PHP connection. I am using the following code
file1.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<input type="text" id='demo'>
<input type="button" onclick='ajaxCall()' value='23' >
<script>
function ajaxCall()
{
document.getElementById('demo').value="343434";
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.requeststate==4 && xmlhttp.status==200){
document.getElementById('demo').value="4444343434";
document.getElementById('demo').value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>
</body>
</html>
and the corresponding test.php
<?php
echo "me";
?>
Now when I click the button, the value of textbox is changing to 343434 but not changing on AJAX call, even it does not change to 4444343434. I'm currently runnning php 5.5.6 on ubuntu 14.04LTS.
Change xmlhttp.requeststate to xmlhttp.readyState
Try use the following crossbrowsing function
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
And change xmlhttp = new XMLHttpRequest(); to xmlhttp = new getXmlHttp();
And this work without jQuery.

How to retrieve an element from an ajax call

I want to retrieve all elements from an ajax call, then insert them into another element without:
using jquery (I just want to use pure JavaScript)
creating a new element to contain the ajax response
Here's what I have tried:
index.php
<!DOCTYPE HTML>
<head>
<script type="text/javascript">
function loadPage() {
var ajax = new XMLHttpRequest();
ajax.open('GET', 'test.php', true);
ajax.onreadystatechange = function (){
if(ajax.readyState === 4 && ajax.status === 200){
document.getElementById('output').appendChild( ajax.responseText ) ;
}
};
ajax.send();
}
loadPage();
</script>
</head>
<body>
<div id="output">
<h1>Default</h1>
</div>
</body>
</html>
test.php
<h1>
its work
</h1>
<div>
<h2>
its work2
</h2>
</div>
I already googled it, but the answer was always to use jQuery.
Node.appendChild requires a Node object as an argument. What you're getting from test.php is a string. Try using innerHTML instead
document.getElementById('output').innerHTML = ajax.responseText;
As of XHR level 2, you can simply attach an onload handler to XHR instead of checking the readyState and status properties.
ajax.onload = function() {
document.getElementById('output').innerHTML += this.responseText;
}
have you looked at this
http://w3schools.com/ajax/ajax_examples.asp
http://w3schools.com/ajax/tryit.asp?filename=tryajax_first
I think the most of the examples that you find use jquery because jquery makes it cross browser
try this one
function loadPage(){
var strURL="test.php";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('output').value=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("POST", strURL, true);
req.send(null);
}
}
function getXMLHTTP() { //function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}

Simple AJAX example - load data from txt file

I'm trying to do a basic AJAX tutorial to read data from a file, hello.txt, into my webpage. hello.txt and my current html webpage are in the same directory. Does anyone know what I'm doing wrong? Nothing happens when I load the page.
<!DOCTYPE html>
<head><title>Ajax Test</title>
<script type="text/javascript">
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "hello.txt", true);
xmlHttp.addEventListener("load", ajaxCallback, false);
xmlHttp.send(null);
function ajaxCallback(event){
alert( "Your file contains the text: " + event.target.responseText );
}
</script>
</head>
<body>
</body>
</html>
here is a function i always use for simple async get ajax:
1.use onload as it's shorter to write and as you don't need to add multiple eventhandlers.
2.don't do syncronous ajax.
js
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
example
http://jsfiddle.net/9pCxp/
extra info
https://stackoverflow.com/a/18309057/2450730
full html
<html><head><script>
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function alertTxt(){
alert(this.response)
}
window.onload=function(){
ajax('hello.txt',alertTxt)
}
</script></head><body></body></html>
Here is your answer.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var allText = this.responseText;
alert(allText);
}
};
xhttp.open("GET", "filename.txt", true);
xhttp.send();
The below code may be useful for someone...
<!DOCTYPE html>
<html>
<body>
<h1>Load Data from text file </h1>
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "info.txt", true);
xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;
}
</script>
</body>
</html>
Open an empty .PHP file or .ASPX file (or just any server-side language that can run javascript)
Paste this code between "head" tags.
<script>
var xmlhttp;
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 myFunction() {
loadXMLDoc("hello.xml", function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
});
}
</script>
As you see, javascript is referring to "hello.xml" file to get information from.
Open an empty XML file inside the project folder you have created in. Name your XML file as "hello.xml"
Paste this code to your XML file.
<?xml version="1.0" encoding="utf-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Run your php (or .aspx) file on localhost.
Click on button, your page must acquire the XML data into your website.
function Go() {
this.method = "GET";
this.url = "hello.txt";
if (window.XMLHttpRequest && !(window.ActiveXObject)) {
try {
this.xmlhttp = new XMLHttpRequest();
}
catch (e) {
this.xmlhttp = false;
}
// branch for IE/Windows ActiveX version
}
else if (window.ActiveXObject) {
try {
this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
this.xmlhttp = false;
}
}
}
if (this.xmlhttp) {
var self = this;
if (this.method == "POST") {
this.xmlhttp.open("POST", this.url, true);
}
else {
//remember - we have to do a GET here to retrive the txt file contents
this.xmlhttp.open("GET", this.url, true);
}
this.xmlhttp.send(null);
//wait for a response
this.xmlhttp.onreadystatechange = function () {
try {
if (self.xmlhttp.readyState == 4) {
if (self.xmlhttp.status == 200) {
if (self.xmlhttp.responseText != null) {
self.response = self.xmlhttp.responseText;
alert(self.xmlhttp.responseText);
}
else {
self.response = "";
}
}
else if (self.xmlhttp.status == 404) {
alert("Error occured. Status 404: Web resource not found.");
}
else if (self.xmlhttp.status == 500) {
self.showHtmlError("Internal server error occured", "Status: " + self.xmlhttp.responseText);
}
else {
alert("Unknown error occured. Status: " + self.xmlhttp.status);
}
}
}
catch (e) {
alert("Error occured. " + e.Description + ". Retry or Refresh the page");
}
finally {
}
};
}
}
//Use the function in your HTML page like this:
Go();
</script>

JavaScript xmlhttp read from feed

I'm trying to use javascript and read from http://search.yahooapis.com/ WebSearchService /V1/webSearch?appid=YahooDemo &query=persimmon&results=2 using xmlhttp. I'm getting an error because it cannot read
<script type="text/javascript">
url="http://search.yahooapis.com/ WebSearchService /V1/webSearch?appid=YahooDemo &query=persimmon&results=2";
var xmlhttp = null;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
if ( typeof xmlhttp.overrideMimeType != 'undefined')
{
xmlhttp.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert('Perhaps your browser does not support xmlhttprequests?');
}
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert("success");
}
else
{
alert("failure");
}
};
</script>
Unless your web site is hosted on search.yahooapis.com you're probably encountering the Same Origin Policy.
This is causing your outgoing request to return with a 404 status code:
You should be using JSONP instead of XMLHttpRequest:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript file download</title>
<script type="text/javascript">
function yahooApi(resp) {
var scriptEl = document.getElementById("yahooApiJsonP");
scriptEl.parentNode.removeChild(scriptEl);
console.log(resp);
}
window.onload = function() {
var scriptEl = document.createElement("script");
scriptEl.id = "yahooApiJsonP";
scriptEl.src = "http://search.yahooapis.com/WebSearchService/V1/webSearch?output=json&callback=yahooApi&appid=YahooDemo&query=persimmon&results=2";
document.body.appendChild(scriptEl);
};
</script>
</head>
<body>
<p>This is a test</p>
</body>
</html>
This will send the request, which will return a 200 OK status:
It also looks like this service has been shut down:

xmlHttpRequest issues in a Google-like autosuggestion script

I am trying to build up an autosuggestion search field similar to Google Suggestion (or Autosuggestion?).
I am using pure javaScript/AJAX and 2 files: index.php and ajax-submit.php (is the file where I will actually query the database). But for moment I am simply echo a text for debugging.
There are a few issues:
Issue 1: The issue is the firebug outputs: xmlhttp is not defined as soon as I type something in the search input [solved, see below].
Issue2: I would like also to echo the content of the search input something like this:
echo $_GET['search_text'];
or
if(isset($_GET['search_text'])) {
echo $search_text = $_GET['search_text'];
}
but I get the following error: *Undefined index: search_text in ajax-submit.php*
So here is my function suggest call:
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
And here is my function suggest():
<script type="text/javascript">
//function does not needs params because is unique to the input search_text
function suggest() {
//browser object check
if(window.xmlHttpRequest) {
xmlhttp = new xmlHttpRequest();
}
else if (window.ActiveXObject) {
//console.log("error");
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
//when the onreadystatechange event occurs
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementByID('results').innerHTML = xmlhttp.responseText;
}
}//end onready
xmlhttp.open('GET', 'ajax-submit.php', true);
xmlhttp.send();
}//end suggest
</script>
and here is my php ajax-submit file:
<?php
echo 'Something';
?>
Can someone help me debug? It might be a scope issue but I have no clue.
The second question would be how would you normally debug an Ajax request in Firebug?
Thanks
Actually, it is
XMLHttpRequest()
not
xmlHttpRequest()
To have a true cross-browser compliant XHR object creation, go with this:
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
var xhr = ( function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
Use:
new XMLHttpRequest
not
new xmlHttpRequest
I wrote a better implementation: cross-browser/more readable code, function splits. Below is the code. Unfortunately tough reads php echo text it won't read the variable search_text, I don't know why:
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php?search_text="+document.search.search_text.value");
}
</script>
and HTML code:
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and ajax-submit.php:
<?php
//echo 'Something';//'while typing it displays Something in result div
echo $_GET['search_text'];
?>

Categories

Resources