Jump to content

Ajax Post And Get


Redroest

Recommended Posts

Hey people I am new on this forum and I signed in with the hope to know more about AJAX. My goal is to make a website that is completely controlled by AJAX. So I started experimenting with some tutorials. (all from w3schools) The first function I successfully made was the GetXmlHttpObject(). Nothing difficult, just copy/paste.

<script language='JavaScript'><!--function GetXmlHttpObject(){  var xmlhttp;  if (window.XMLHttpRequest)  {	// code for IE7+, Firefox, Chrome, Opera, Safari	xmlhttp=new XMLHttpRequest();  }  else if (window.ActiveXObject)  {	// code for IE6, IE5	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }  else  {	alert("Your browser does not support XMLHTTP!");  }	return xmlhttp;}--></script>

The second function was also not a very big deal:

<script language='JavaScript'><!--//Send data to server, handle server-side scripts and send back datafunction UpdateSSGET(url, functionname){  xmlhttp=GetXmlHttpObject();  xmlhttp.onreadystatechange= function()   { 		var test = functionname;	eval(test + '(url)');	};  xmlhttp.open("GET",url,true);  xmlhttp.send(null);  }//--></script>

The above code sends the given url to the server-sided script and returns a output to the given function-name:

UpdateSSGET('index.php?key1=value1&key2=value2', 'ClientSideFunction');

for me the above codes works perfectly. Now I tried the same with the POST version:

<script language='JavaScript'><!--function TestPost(sendValues, url){	alert("Working alert function"); //The function is called because it gives this warning. Also both function values are send in the correct way  xmlhttp=GetXmlHttpObject();	xmlhttp.onreadystatechange= function() 	{	if(xmlhttp.readyState == 4)	{		  alert("tester"); //This alert refuses to show up	  }  	};		xmlHttp.open("POST", url, true);  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  xmlHttp.send(Sendvalues);	}//--></script>

The above script is called and also the variables: URL and sendValues are given in the correct way. Also the server-sided page exists. I made a file called test.php. Inside was a script:

<?php echo "test"; ?>

And I called the function:

TestPost('test1=testvalue&test2=testvalue2', 'test.php')

No matter what I try, it looks like the function not even tried to connect to the server-sided 'test.php'. With a little help from searching trough this forum, I installed Firebug. When I look at the requests, all my $_GET requests (connected trough my UpdateSSGET function) are visible, to bad it does not show any form of requesting test.php.I tried to make this explanation as clear as possible so I hope that you people are able to help me.

Link to comment
Share on other sites

Add an alert to see what the state is.

	xmlhttp.onreadystatechange= function() 	{	  alert(xmlhttp.readyState);	if(xmlhttp.readyState == 4)	{		  alert("tester"); //This alert refuses to show up	  }  	};

Or with Firebug, you can write them to the console instead:

	xmlhttp.onreadystatechange= function() 	{	  console.log(xmlhttp.readyState);	if(xmlhttp.readyState == 4)	{		  alert("tester"); //This alert refuses to show up	  }  	};

There are some additional ajax functions here:http://w3schools.invisionzone.com/index.ph...st&p=116840

Link to comment
Share on other sites

Made the alert as you said but the whole alert refuses to show up

<script language='javascript'><!--function TestPost(sendValues, url){   xmlhttp=GetXmlHttpObject();	xmlhttp.onreadystatechange= function() 	{	  alert(xmlhttp.readyState); //Also tested with alert("test");	if(xmlhttp.readyState == 4)	{		  alert("tester"); //This alert refuses to show up	  }  	};	xmlHttp.open("POST", url, true);  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");  xmlHttp.send(Sendvalues);}TestPost('test1=testvalue', 'test.php');//--></script>

Link to comment
Share on other sites

Well, to me it is a complete mystery, but I took the first script from the link that you gave me and converted it for my own use. It took me a few hours to figure this all out cause HEY I'm new! :) I also tryed to make this as Object Oriented as possible. Can someone comment on these functions, or maybe give some tips on how to make this better?

<script language='javascript'><!--function GetXmlHttpObject(){  var xmlhttp;  if (window.XMLHttpRequest)  {	// code for IE7+, Firefox, Chrome, Opera, Safari	xmlhttp=new XMLHttpRequest();  }  else if (window.ActiveXObject)  {	// code for IE6, IE5	xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }  else  {	alert("Your browser does not support XMLHTTP!");  }	return xmlhttp;}function sendRequest(url,functionname,postData) {  var xmlhttp = GetXmlHttpObject();  if (!xmlhttp) return;  var method = (postData) ? "POST" : "GET";  xmlhttp.open(method,url,true);  xmlhttp.setRequestHeader('User-Agent','XMLHTTP/1.0');  if (postData)	xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');  xmlhttp.onreadystatechange = function () 	{	if (xmlhttp.readyState != 4) return;	if (xmlhttp.status != 200 && xmlhttp.status != 304) 		{	  alert('HTTP error ' + req.status);	  return;	}	  var test = functionname;	eval(test + '(xmlhttp)');	//callback(xmlhttp);  }  if (xmlhttp.readyState == 4) return;  xmlhttp.send(postData);}//extract data from xmlhttp.responseText stringfunction GetResponseValues(datastring, key){  var regexS = key+"=([^]*)";  var results = datastring.match(regexS);  if( results == null )	{	return "";	}  else	{	return results[1];	}}//--></script>

I use this last function

GetResponseValues(datastring, key)

as a way to extract data from my server-sided output. All of my server-sided outputs are made like a normal web URL. (Nickname=Redroest&key2=value2). So my server outputs a long string of keys and values to a previous defined function and within that function:

<script language='javascript'><!--function TestFunction(xmlHttp){  var Nickname = GetResponseValues(datastring, 'Nickname');  //Its almost the same like the php version $_GET['Nickname']  alert("The server says that your nickname is "+Nickname);}sendRequest(test.php,"TestFunction","Nickname=Redroest&key2=value2");//--></script>

Link to comment
Share on other sites

The problems you are getting with the first posted script, relate to reference to 'xmlhtml' and sendValues variables.for instance:function TestPost(sendValues, url){xmlhttp=GetXmlHttpObject();when campared to: xmlHttp.open("POST", url, true); xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlHttp.send(Sendvalues); once these are corrected, and you pass the responseText value to a element such as div or span, it will work, see example below.<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /><title>Untitled Document</title><script type="text/javascript">/*<![CDATA[*//*---->*/function GetXmlHttpObject(){ var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } else { alert("Your browser does not support XMLHTTP!"); } return xmlhttp;}function TestPost(sendValues, url){ alert("Working alert function"); //The function is called because it gives this warning. Also both function values are send in the correct way xmlhttp=GetXmlHttpObject(); xmlhttp.onreadystatechange= function() { if(xmlhttp.readyState == 4) { alert("tester"); //This alert refuses to show up document.getElementById("response").innerHTML= xmlhttp.responseText; } }; xmlhttp.open("POST", url, true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send(sendValues);} TestPost('test1=testvalue', 'test.php');/*--*//*]]>*/</script> <style type="text/css"></style></head><body><div id="response"></div></body></html>

Link to comment
Share on other sites

Made the alert as you said but the whole alert refuses to show up
That means the readyState of the XHR object never changed.In this code:
<script language='javascript'><!--function TestFunction(xmlHttp){  var Nickname = GetResponseValues(datastring, 'Nickname');  //Its almost the same like the php version $_GET['Nickname']  alert("The server says that your nickname is "+Nickname);}sendRequest(test.php,"TestFunction","Nickname=Redroest&key2=value2");//--></script>

You need to quote the PHP script, that's a string value. You're also trying to use a datastring variable but it's not defined. Also, I'm not sure why you did this:var test = functionname;eval(test + '(xmlhttp)');If you send a reference to the callback function instead of the name of it, you can use the original code.

Link to comment
Share on other sites

First of all thanks dsonesuk for a explanation why my previous function didn't work. So if I take the correct conclusion, this means that I fist have to output the answer (trough innerHTML) and then the alert will also work?@justsomeguy:Fist of all: I indeed forgot to qoute test.php in my example.Second: you said that I forgot to define my datastring variable. I also forgot it in my example but it is defined in my real code. Tx anyway for checking up:)The reason why I used the below script was as follows:The tutorial on the w3schools website show a line like this:xmlhttp.onreadystatechange=Statechanged;In this case statechanged is a function but it cannot contain any parameters. I begun searching on Google for a solution (not knowing that it is possible to return (in this case) callback() so I tried:

var test = functionname;eval(test + '(xmlhttp)');

This is a piece of the code that I found by searching on Google and it works fine to me. (can't remember the website where it came from)I did not notice in the example how you guys solved that problem, but it looks much nicer and it is shorter so I will start using this now. :)

Link to comment
Share on other sites

it was sending these values using xmlHttp.open("POST", url, true); xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlHttp.send(Sendvalues);which had wrong variable references (should have been 'xmlhttp')and looking for a state change of xmlhttp.onreadystatechange= function() { alert(xmlhttp.readyState); //Also tested with alert("test"); if(xmlhttp.readyState == 4) { alert("tester"); //This alert refuses to show up } };which it would never find.once it was corrected it could now find the values, and link to test.php page, and display the alert message.I just added a reference to div's innerhtml to show the content from test.php

Link to comment
Share on other sites

Well all functions work perfectly in Firefox but only my page calling function refuses to operate in IE. Below are the functions used to call pages:

var XMLHttpFactories = [	function () {return new XMLHttpRequest()},	function () {return new ActiveXObject("Msxml2.XMLHTTP")},	function () {return new ActiveXObject("Msxml3.XMLHTTP")},	function () {return new ActiveXObject("Microsoft.XMLHTTP")}];function GetXmlHttpObject() {  var xmlhttp = false;  for (var i=0;i<XMLHttpFactories.length;i++) {	try {	  xmlhttp = XMLHttpFactories[i]();	}	catch (e) {	  continue;	}	break;  }  return xmlhttp;}function sendRequest(url,callback,postData) {  var xmlhttp = GetXmlHttpObject();  if (!xmlhttp) return;  var method = (postData) ? "POST" : "GET";  xmlhttp.open(method,url,true);  xmlhttp.setRequestHeader('User-Agent','XMLHTTP/1.0');  if (postData)	xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');  xmlhttp.onreadystatechange = function () 	{	if (xmlhttp.readyState != 4) return;	if (xmlhttp.status != 200 && xmlhttp.status != 304) 		{	  alert('HTTP error ' + req.status);	  return;	}	  callback(xmlhttp);  }  if (xmlhttp.readyState == 4) return;  xmlhttp.send(postData);}function SelectPage(xmlhttp){  var page = xmlhttp.responseText;  document.getElementById("MemberAdmin").innerHTML=page;}

I call the pages with the following links:

  echo "<a href='#'><input type='image' src='images/admin/adduser.png' title='Nieuw lid registreren' Onclick='sendRequest(\"admin.php?module=members&task=register\", SelectPage);'></a>";  echo "<a href='#'><input type='image' src='images/admin/userlist.png' title='Lijst met geregistreerde gebruikers' Onclick='sendRequest(\"admin.php?module=members&task=memberlist\", SelectPage);'></a>";

When I run this with Firefox it works perfectly, but in IE it refuses to work. Strange thing is that every other AJAX script based on the functions above do work in IE.

Link to comment
Share on other sites

Add some alerts to track what IE is doing.

function sendRequest(url,callback,postData) {  alert('sendRequest');  var xmlhttp = GetXmlHttpObject();  if (!xmlhttp) return;  var method = (postData) ? "POST" : "GET";  xmlhttp.open(method,url,true);  xmlhttp.setRequestHeader('User-Agent','XMLHTTP/1.0');  if (postData)	xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');  xmlhttp.onreadystatechange = function () 	{	alert('readyState: '  + xmlhttp.readyState);	if (xmlhttp.readyState != 4) return;	if (xmlhttp.status != 200 && xmlhttp.status != 304) 		{	  alert('HTTP error ' + req.status);	  return;	}	  callback(xmlhttp);  }  if (xmlhttp.readyState == 4) return;  xmlhttp.send(postData);}function SelectPage(xmlhttp){  alert('SelectPage');  alert('responseText: ' + xmlhttp.responseText);  alert('responseXML: ' + xmlhttp.responseXML);  var page = xmlhttp.responseText;  document.getElementById("MemberAdmin").innerHTML=page;}

Link to comment
Share on other sites

Well below is the html/php code that has to be called:

<?phpfunction register(){ 	echo "<p>";  echo "<form action='admin.php?module=members&task=SaveUser' method='post' name='NewUser'>";	echo "<center><h2>Nieuw lid registreren</h2></center>";	echo "<table align='center'>";	echo "  <tr><td>Voornaam:</td><td>		   <input type='text' style='border-color: red;' name='Firstname'id='error'		Onblur='CheckValueCS(this.name);'></td></tr>";	echo "  <tr><td>Achternaam:</td><td>		 <input type='text' style='border-color: red;' name='Lastname' id='error'		Onblur='CheckValueCS(this.name);'></td></tr>";	echo "  <tr><td>Email adres:</td><td>		<input type='text' style='border-color: red;' name='UserMail' id='error'		Onkeyup='sendRequest(\"admin.php?module=members&task=CheckRegisterForm\", CheckValueSS, \"key=\"+this.name+\"&value=\"+this.value);'></td></tr>";  echo "  <tr><td>Gebruikersnaam:</td><td>	 <input type='text' style='border-color: red;' name='Nickname' id='error'		Onkeyup='sendRequest(\"admin.php?module=members&task=CheckRegisterForm\", CheckValueSS, \"key=\"+this.name+\"&value=\"+this.value);'></td></tr>";  echo "  <tr><td>Wachtwoord:</td><td>	 <input type='password' style='border-color: red;' name='UserPass' id='error'		Onkeyup='CheckValueCS(this.name);'></td></tr>";	echo "  <tr><td>Wachtwoord herhalen:</td><td><input type='password' style='border-color: red;' name='repeatpassw' id='error' Onblur='CheckValueCS(this.name);'></td></tr>";  echo "  <tr><td colspan='2' align='center'>  <input type='button' name='SubmitRegister' value='Registreren' Onclick='CheckErrors()'></td></tr>";	echo "</table>";	echo "</form>";	echo "</p>";}?>

Strange thing is that when I call the code like below, it will work and give "test" as output innerHTML:

<?phpfunction register(){   echo "test";/*	echo "<p>";  echo "<form action='admin.php?module=members&task=SaveUser' method='post' name='NewUser'>";	echo "<center><h2>Nieuw lid registreren</h2></center>";	echo "<table align='center'>";	echo "  <tr><td>Voornaam:</td><td>		   <input type='text' style='border-color: red;' name='Firstname'id='error'		Onblur='CheckValueCS(this.name);'></td></tr>";	echo "  <tr><td>Achternaam:</td><td>		 <input type='text' style='border-color: red;' name='Lastname' id='error'		Onblur='CheckValueCS(this.name);'></td></tr>";	echo "  <tr><td>Email adres:</td><td>		<input type='text' style='border-color: red;' name='UserMail' id='error'		Onkeyup='sendRequest(\"admin.php?module=members&task=CheckRegisterForm\", CheckValueSS, \"key=\"+this.name+\"&value=\"+this.value);'></td></tr>";  echo "  <tr><td>Gebruikersnaam:</td><td>	 <input type='text' style='border-color: red;' name='Nickname' id='error'		Onkeyup='sendRequest(\"admin.php?module=members&task=CheckRegisterForm\", CheckValueSS, \"key=\"+this.name+\"&value=\"+this.value);'></td></tr>";  echo "  <tr><td>Wachtwoord:</td><td>	 <input type='password' style='border-color: red;' name='UserPass' id='error'		Onkeyup='CheckValueCS(this.name);'></td></tr>";	echo "  <tr><td>Wachtwoord herhalen:</td><td><input type='password' style='border-color: red;' name='repeatpassw' id='error' Onblur='CheckValueCS(this.name);'></td></tr>";  echo "  <tr><td colspan='2' align='center'>  <input type='button' name='SubmitRegister' value='Registreren' Onclick='CheckErrors()'></td></tr>";	echo "</table>";	echo "</form>";	echo "</p>";*/}?>

but when I try the code like below it also refuses to come up:

<?phpfunction register(){ echo "test with alinea tags";	echo "<p>";echo "test in alinea tag";/*  echo "<form action='admin.php?module=members&task=SaveUser' method='post' name='NewUser'>";	echo "<center><h2>Nieuw lid registreren</h2></center>";	echo "<table align='center'>";	echo "  <tr><td>Voornaam:</td><td>		   <input type='text' style='border-color: red;' name='Firstname'id='error'		Onblur='CheckValueCS(this.name);'></td></tr>";	echo "  <tr><td>Achternaam:</td><td>		 <input type='text' style='border-color: red;' name='Lastname' id='error'		Onblur='CheckValueCS(this.name);'></td></tr>";	echo "  <tr><td>Email adres:</td><td>		<input type='text' style='border-color: red;' name='UserMail' id='error'		Onkeyup='sendRequest(\"admin.php?module=members&task=CheckRegisterForm\", CheckValueSS, \"key=\"+this.name+\"&value=\"+this.value);'></td></tr>";  echo "  <tr><td>Gebruikersnaam:</td><td>	 <input type='text' style='border-color: red;' name='Nickname' id='error'		Onkeyup='sendRequest(\"admin.php?module=members&task=CheckRegisterForm\", CheckValueSS, \"key=\"+this.name+\"&value=\"+this.value);'></td></tr>";  echo "  <tr><td>Wachtwoord:</td><td>	 <input type='password' style='border-color: red;' name='UserPass' id='error'		Onkeyup='CheckValueCS(this.name);'></td></tr>";	echo "  <tr><td>Wachtwoord herhalen:</td><td><input type='password' style='border-color: red;' name='repeatpassw' id='error' Onblur='CheckValueCS(this.name);'></td></tr>";  echo "  <tr><td colspan='2' align='center'>  <input type='button' name='SubmitRegister' value='Registreren' Onclick='CheckErrors()'></td></tr>";	echo "</table>";	echo "</form>";*/	echo "</p>";}?>

Link to comment
Share on other sites

Well, you were correct. It is a bug in IE. It is always that same browser that causes problems! I found a nice workaround for it:

function SelectPage(xmlhttp){  var newdiv = document.createElement("div");  newdiv.innerHTML = xmlhttp.responseText;  var container = document.getElementById("MemberAdmin");  container.innerHTML="";	container.appendChild(newdiv);}

First of all, I use the DOM to create a block level element. Then update the innerHTML property of this newly-created element. And then I insert the updated element into the document using a DOM method like appendChild.The good thing is that this will work in almost every browser. The downside is that it is much slower in loading than just using innerHTML.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...