Change content of div onclick with Ajax - ajax

I want to change the content the div named john to the output from the php file when an image is clicked. I'm sure it's simple but I can't find an example that fits. Here's my code:
function ajaxFunction(){
var ajaxRequest;
ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("john").innerHTML=xmlhttp.responseText;
}
}
ajaxRequest.open("GET", "test.php", true);
ajaxRequest.send(null);
}
html
<img class='cross' src='images/cross.png' onclick="ajaxFunction();">
<div id='john'>john</div>
test.php
<?php echo "hello"; ?>

Looks to me like you've got a syntax error with your javascript. Your trying to get the responseText from xmlhttp but your XMLHttpRequest is stored in ajaxRequest
Try this
function ajaxFunction(){
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
document.getElementById("john").innerHTML=ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "test.php", true);
ajaxRequest.send();
}

may I suggest for cross browser/version, use:
var ajaxRequest = getXMLHttpRequest();
and then,
function getXMLHttpRequest() {
var re = "nothing";
try {re = new window.XMLHttpRequest();} catch(e1) {};
try {re = new ActiveXObject("MSXML2.XMLHTTP.4.0");} catch(e) {};
try {re = new ActiveXObject("Msxml2.XMLHTTP");} catch(e2) {};
try {re = new ActiveXObject("Microsoft.XMLHTTP");} catch(e3) {};
try {re = new ActiveXObject("MSXML2.XMLHTTP.3.0");} catch(ex) {};
if (re != "nothing") {return re;}
else {return null;};
};
as well as changing it to
ajaxRequest.responseText();

I've managed to solve it with the code below. This code also returns the ID of the element after getting "hello" from the php file.
<script language="javascript">
function calldislike(str){
if (str==""){
document.getElementById("john").innerHTML="";
return;
}
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("john").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?q="+str,true);
xmlhttp.send();
}
</script>
<img src='images/cross.png' onclick="calldislike(this.id);" id='3'>
<div id='john'>john</div>
test.php
<?php echo "hello".$_GET["q"]; ?>

Related

First AJAX project...(wont load text file inline)

This is my first time working with AJAX, and I cant seem to figure out WHY the .txt file will NOT load? but instead goes to a new page with just that text displayed) ie: not loading in the same page:
my index.html page:
<html>
<head>
<meta charset="utf-8">
<title>Learning Ajax</title>
</head>
<body>
<!-- my first AJAX script -->
<h1>Learning Ajax</h1>
Load Text Files
<script src="js/main.js"></script>
</body>
</html>
here is my main.js script:
var message = "Test";
(function() {
var link = document.getElementsByTagName("a")[0];
link.onClick = function(){
var xhr = new XMLHttpRequest();
//handle the 'onreadystatechange" event
//0 = un-initialized
//1 = loading
//2 = loaded (sent to server)
//3 = interactive (server is responding)
//4 = complete (request finished)
xhr.readystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
};
//open the request
xhr.open("GET", "files/ajax.txt", true);
//send the request
xhr.send(null);
return false;
};
};
})();
alert(message);
in my ajax.txt file.. I just have some random plain text: This is Ajax text to be loaded.
I am NOT running this locally, but through localhost using WAMP web server..
What am I missing? or overlooking here?
Tutorial link: tutsplus.com/lesson/the-simplest-ajax-script
to solve your problem:
Make this replacement to your code:
onClick -> onclick (js is case sensitive)
readystatechange -> onreadystatechange
then put this piece of code out of the onreadystatechange function:
//open the request
xhr.open("GET", "files/ajax.txt", true);
//send the request
xhr.send(null);
return false;
This is the new main.js:
var message = "Test";
(function() {
var link = document.getElementsByTagName("a")[0];
link.onclick = function(){
var xhr = new XMLHttpRequest();
//handle the 'onreadystatechange" event
//0 = un-initialized
//1 = loading
//2 = loaded (sent to server)
//3 = interactive (server is responding)
//4 = complete (request finished)
xhr.onreadystatechange = function(){
if((xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304)){
xhr.responseText;
var body = document.getElementsByTagName("body")[0];
var p = document.createElement("p");
var pText = document.createTextNode(xhr.responseText);
p.appendChild(pText);
body.appendChild(p);
};
return false;
};
//open the request
xhr.open("GET", "files/ajax.txt?aiai", true);
//send the request
xhr.send(null);
return false;
};
})();
alert(message);
I think its easier to do it like that:
first, HTML:
<html>
<head>
<meta charset="utf-8">
<title>Learning Ajax</title>
</head>
<body>
<!-- my first AJAX script -->
<h1>Learning Ajax</h1>
Load Text Files
<div id="textFiles"><!-- files display here --></div>
</body>
</html>
JS:
<script>
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
}
else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function loadText() {
var message = "Test";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
document.getElementById("textFiles").innerHTML = xmlhttp.responseText;
alert(message);
}
else{
document.getElementById("textFiles").innerHTML = "Loading Files...";
}
};
xmlhttp.open("POST",'files/ajax.txt',true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>

How would I go about doing this?

First I have my data encoded in the json_encode function.
Looks like this for example:
{"test":"test value"}
What I want to do is make test into a javascript variable where it can hold the data of "test value".
index.php (use json_encode here):
<?php
$foo = array('test' => 'test value');
echo json_encode($foo);
?>
example.html
<script type="text/javascript">
$.get('index.php', function(response) {
alert(response['test']);
// this will alert "test value"
}, 'json');
</script>
EDIT1: example.html (without-jQuery solution):
<script type="text/javascript">
window.onload = function() {
var request;
request = getHTTPObject();
request.onreadystatechange = sendData;
request.open("GET", "index.php", true);
request.send(null);
}
function sendData() {
if(request.readyState == 4){
var JSONtext = request.responseText;
var JSONobject = JSON.parse(JSONtext);
// notice how variables are used
var output = JSONobject.test;
alert(output); // displays "test value"
}
function getHTTPObject(){
var xmlhttp = false;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
</script>
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
straight from the jquery docs...
Objects are associative arrays. They store key/values pairs. So All you have to do is:
var test = function(){}
test["hello"] = "world";
This will set hello as a variable and world as its value.
you can test this by doing
alert(test.hello);
Replace hello and world with the json key and value
Hope this help more with this example:
I am using Jquery AJAX to go to index.php resource and return a json object.
index.php
<?php
$variables = array('hello' => 'world');
echo json_encode($variables);
?>
example.html
var test = function(){}
$.ajax({
url: index.php,
success: function(json) {
for(var key in json ){
var testVarName = key;
var testVarValue = json[key];
test[testVarName ] = testVarValue;
}
}
});
So now test object has variable hello and it value is world

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>

weird ajax behavior-commented code breaks the request?

I don't understand this. I have an innerHTML request.
<div id="targetDiv"></div>
One of the includes is:
<?php
echo ("Hello, world");
?>
and works fine, but if I do:
<?php
echo ("Hello, world");
?>
<!--
lots of code I'm trying to debug
-->
it doesn't work.
Why?
getData:
<script language = "javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID)
{
if(XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
It looks mostly likely to be a bug in your PHP code rather than your javascript code. I recommend that you type in the PHP script's URL into your browser and check if it produces the expected output. Better still I recommend that you install firebug. That will allow you to check each and every ajax request as it happens. Better still it will allow you to debug your javascript and inspect variables.

Permission Denied When using XMLHttpRequest.Open cross browser access

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.

Resources