In my index.html page I want to load a seperate ajax page when the app is loading,
what is the best way of doing that?
This is my index code:
loading ajax subpage here.....
And the subpage is just:
content..............
Thanks.
using JavaScript you can do that. You have to do that on page load. Here is an example in jQuery.
$(function(){
$('#content').load('/content.html');
});
As an example, you can call a javascript function when the body of your main page loads using the onload property of body:
<html>
<head>
...
</head>
<body onload="loadContent();">
...
</body>
</html>
Among your javascript functions, you will need your loadContent function as well as some functions that perform the HTTPRequest-related operations.
function loadContent()
{
var contentURL = "contentpage.xml";
http.Open("GET", contentURL, true);
http.onreadystatechange = useHttpResponse;
http.send(null);
}
var http = getXMLHTTPRequest();
function getXMLHTTPRequest()
{
try
{
req = new XMLHttpRequest();
}
catch (err1)
{
try
{
req = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (err2)
{
try
{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (err3)
{
req = false;
}
}
}
return req;
}
function useHttpResponse()
{
if (http.readyState == 4)
{
if (http.Status == 200)
{
var xml = http.responseXML;
// do something with loaded XML (such as populate a DIV or something)
}
}
}
You should check out some AJAX tutorials online for more complete information.
Use jQuery: www.jquery.com
There are loads of examples and docs on the website, as well as tons of tutorials on the web.
Good luck
Related
I'm trying to change my static php page to ajax. I don't have much information about it to be honest.
My problem is: When I load content into a div, my old php version works fine but when i use the ajax to get content into a div(that i found actually, you can find below) italian characters turns to �.
I browsed some other similar questions but I couldnt find useful information.
I use the header:
my sql coding is utf_unicode_ci
and I also realized when i add php header as utf 8, my php version characters brokes too.
I appriciate any kind of suggestions
Thanks
<script>
function createRequestObject()
{
var returnObj = false;
if(window.XMLHttpRequest) {
returnObj = new XMLHttpRequest();
} else if(window.ActiveXObject) {
try {
returnObj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
returnObj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return returnObj;
}
var http = createRequestObject();
var target;
// This is the function to call, give it the script file you want to run and
// the div you want it to output to.
function sendRequest(scriptFile, targetElement)
{
target = targetElement;
try{
http.open('get', scriptFile, true);
}
catch (e){
document.getElementById(target).innerHTML = e;
return;
}
http.onreadystatechange = handleResponse;
http.send();
}
function handleResponse()
{
if(http.readyState == 4) {
try{
var strResponse = http.responseText;
document.getElementById(target).innerHTML = strResponse;
} catch (e){
document.getElementById(target).innerHTML = e;
}
}
}
</script>
It would probably be the best if you use utf-8 for both your page and your ajax response. You could also try using '&#;'-notation for non-ascii characters.
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>
After several pieces of helpful advice from the members of this forum I'm getting closer to solving what should be a simple issue. I'm a complete newbie to AJAX.
Can someone please tell me why this piece of code works fine in Firefox 8 but not in IE 9? It works ONCE in IE but not again unless I close the browser and reopen!!??
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest;
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch(e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if (ajaxRequest.readyState == 4) {
}
}
ajaxRequest.open("GET", "disp_processTEXT.asp", false);
ajaxRequest.send(null);
}
//-->
</script>
The readystate is left blank as it is copied code which originally assigned a value to a div but I only want to run the database code in the asp page. Presumably this could have been deleted?
The code to be run in the asp page is
<%
Set MyConn = Server.CreateObject("ADODB.Connection")
MyConn.Open "dsn=xxx;uid=xxx;password=xxx;"
SQLString = "UPDATE dbo_tbl_printing_tempstore SET front_has_text1 = 'YES', front_text = 'help' WHERE id = 106567"
MyConn.Execute(SQLString)
MyConn.Close
Set MyConn = Nothing
%>
Please help me as this is driving me mad.
Many thanks
Switch to jQuery and its Ajax system as it should be cross browser compatable out the box, and saves you huge amounts of time:
Add a reference for jQuery:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
and switch to its Ajax method (place below the above):
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'disp_processTEXT.asp',
success: function(response) {
alert('It worked');
}
});
});
</script>
Update:
To bind to the onblur event using jQuery try this. Remove the onblur= attribute from your current code.
$(document).ready(function() {
$('#yourinput').on('blur', function(){
$.ajax({
url: 'disp_processTEXT.asp',
success: function(response) {
alert('It worked');
}
});
});
});
Demo: http://jsfiddle.net/qmPLj/
Try this. It has worked for me across all browsers but some Opera versions.
function GetXmlHttpObject(handler)
{
var objXmlHttp=null;
if(navigator.userAgent.indexOf("MSIE")>=0)
{
var strName="Msxml2.XMLHTTP";
if(navigator.appVersion.indexOf("MSIE 5.5")>=0)
{
strName="Microsoft.XMLHTTP";
}
try
{
objXmlHttp=new ActiveXObject(strName);
objXmlHttp.onreadystatechange=handler;
return objXmlHttp;
}
catch(e)
{
alert("Error. Scripting for ActiveX might be disabled");
return;
}
}
else //All other browsers
{
objXmlHttp=new XMLHttpRequest();
objXmlHttp.onload=handler;
objXmlHttp.onerror=handler;
return objXmlHttp;
}
}
var url= "http://www.example.com/";
xmlHttp=GetXmlHttpObject(stateChanged);
xmlHttp.open("GET", url , true);
xmlHttp.send(null);
Hi I can see this has been discussed but after perusing the issues/answers I still don't seem to be able to get even this simple AJAX call to bump out of ready state 1.
Here's the Javascript I have:
<script language="javascript" type="text/javascript">
var request;
function createRequest()
{
try
{
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
function loadClassesBySchool()
{
//get require web form pieces for this call
createRequest(); // function to get xmlhttp object
var schoolId = getDDLSelectionValue("ddlSchools");
var grade = getDDLSelectionValue("ddlGrades");
var url = "courses.php?grades=" + escape(grade) + "&schoolId=" + escape(schoolId);
//open server connection
request.open("GET", url, true);
//Setup callback function for server response
//+++read on overflow that some fixed the issue with an onload event this simply had
//+++the handle spitback 2 readystate = 1 alerts
request.onload = updateCourses();
request.onreadystatechanged = updateCourses();
//send the result
request.send();
}
function updateCourses()
{
alert('ready state changed' + request.readyState);
}
function getDDLSelectionValue(ddlID)
{
return document.getElementById(ddlID).options[document.getElementById(ddlID).selectedIndex].value;
}
</script>
The PHP is HERE just a simple print which if i navigate to in the browser (IE/Chrome) loads fine:
<?php
print "test";
?>
I'm quite new at this but seems like I can't get the most bare bones AJAX calls to work, any help as to how work past this would be greatly appreciated.
All I get out of my callback function 'updateCourses' is a 1...
Well after more digging I actually gave up and switched over to jQuery which should for all intents and purposes be doing the EXACT same thing except for the fact that jQuery works... I was just less comfortable with it but so be it.
Here's the jQuery to accomplish the same:
function loadCoursesBySchool(){
var grades = getDDLSelectionValue("ddlGrades");
var schoolId = getDDLSelectionValue("ddlSchools");
jQuery.ajax({
url: "courses.php?grades=" + grades + "&schoolId=" + schoolId,
success: function (data) {
courseDisplay(data);
}
});
}
function courseDisplay(response)
{
//check if anything was setn back!?
if(!response)
{
$("#ddlCourses").html("");
//do nothing?
}
else
{
//empty DLL
$("#ddlCourses").html("");
//add entries
$(response).appendTo("#ddlCourses");
}
}
I am trying to access XMLHTTPRequest.open Method I have even included netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
but still its not working.
I am using javascript and HTML to access the WebService.
Any Help would be really great
Code
<html>
<Head>
<Title>Calling A WebService from HTML </Title>
</Head>
<Body onload='GetDataFrmWS()'>
<form name="Form1" id="Form1" runat="server" method="post">
<div id="DisplayData" > </div>
<div id="Menu2"></div>
</form>
<script language='javascript'>
var objHttp;
var objXmlDoc;
function GetDataFrmWS()
{
alert('I M Here');
var func = getDataFromWS();
}
function getDataFromWS()
{
if(window.ActiveXObject)
{
try
{
objHttp = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (ex)
{
objHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
}
else if (window.XMLHttpRequest)
{
objHttp = new window.XMLHttpRequest();
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
}
strEnvelope = '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body>' +
' <HelloWorld xmlns="http://tempuri.org/">' +
' <Dummy xsi:type="xsd:string">Hello</Dummy>'+
' </HelloWorld>'+
'</soap:Body>' +
'</soap:Envelope>' ;
var szUrl;
szUrl = 'http://kamadhenu/Quoteme/GetCategories.asmx?op=HelloWorld';
objHttp.onreadystatechange = HandleResponse;
objHttp.open('POST', szUrl, true);
objHttp.setRequestHeader('Content-Type', 'text/xml');
objHttp.setRequestHeader('SOAPAction','http://tempuri.org/HelloWorld');
objHttp.send(strEnvelope);
}
function HandleResponse()
{
if (objHttp.readyState == 4)
{
if (window.ActiveXObject)
{
objXmlDoc = new ActiveXObject("Microsoft.XMLDOM");
objXmlDoc.async="false";
objXmlDoc.loadXML(objHttp.responseText);
var nodeSelect = objXmlDoc.getElementsByTagName("Menu1").item(0);
var Menu2=objXmlDoc.getElementsByTagName("Menu2").item(0);
document.getElementById('DisplayData').innerHTML=nodeSelect.text;
document.getElementById('Menu2').innerHTML=Menu2.text;
}
else
{
var Text=objHttp.responseText;
var parser=new DOMParser();
objXmlDoc = parser.parseFromString(Text,'text/xml');
var Value=objXmlDoc.documentElement.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].nodeValue;
var Menu2=objXmlDoc.documentElement.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[1].childNodes[0].nodeValue;
var Menu3=objXmlDoc.documentElement.childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[0].childNodes[1].childNodes[1].nodeValue;
document.getElementById('DisplayData').innerHTML=Value;
document.getElementById('Menu2').innerHTML=Menu2;
document.getElementById('Menu2').innerHTML+=Menu3;
}
}
}
</script>
<input type='Button' Text='Click Me' onclick='GetDataFrmWS()' value="Click Me!"/>
°
</Body>
</HTML>
Browser Independent code for XML HTTPRequest
I use the following code to create an XML object. It has been designed to handle all browsers (esp. IE and non IE)
/* Function to create an XMLHTTP object for all browsers */
function getXMLHTTPObject(){
var xmlHttp;
try{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} catch (e){
// Internet Explorer
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;
}
/* End Function */
P.S. You code in the question is not readable. Pls format it
There is a pretty concise example here
Try making your URL http://recpushdata.cyndigo.com/Jobs.asmx/InsertXML
PS. Your code is unreadable in StackOverflow.
As far as I know, the XMLHTTP request must point to a page on the same subdomain of the html page for the various browsers permissions.
One trick is to make another page on the same server in your preferred language and make it handle the request with the server's network.
Example:
from your HTML page you make a ajax request to mydomain.com/externalrequest.php?url=www.google.com
and that page will connect (fsock/cURL etc) to "url" and return it
If you are TRYING to go cross-domain with XHR, you can look into the JSONP method. Check JQuery docs for that.
Would require you to accept JSON response but it does work across domains.