Ajax post request not working

Hi everybody,

I’m having a bit of trouble getting this Ajax post request to work properly.
The whole js file contains my GET function, which works fine, but I can’t seem to get the post one working. It hangs on the line I’ve highlighted when I call it:

var xmlhttp=false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
 	try {
 		 xmlhttp = new XMLHttpRequest();
 	} catch (e) {
 		 xmlhttp=false;
 	}
}

if (!xmlhttp && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
	} catch (e) {
		xmlhttp=false;
	}
}


var please_wait = "Loading...";

function open_url(oldurl, targetId) {
  if(!xmlhttp)return false;
    var e=document.getElementById(targetId);if(!e)return false;
    if(please_wait)e.innerHTML = please_wait;
    urlsize = oldurl.length-3;
    if (oldurl.indexOf('php') == urlsize)
		{
    url = oldurl + '?rannum=' + Math.floor(Math.random()*100001);
    } else {
    url = oldurl + '&rannum=' + Math.floor(Math.random()*100001);
    }
    xmlhttp.open("GET", url, true);
    xmlhttp.onreadystatechange = function() { response(url, e); }
    try{
      xmlhttp.send(null);
    }catch(l){
    while(e.firstChild)e.removeChild(e.firstChild);//e.innerHTML="" the standard way
    e.appendChild(document.createTextNode("request failed"));
  }
}

function post_reply(url, targetId) {
  if(!xmlhttp)return false;
    var e=document.getElementById(targetId);if(!e)return false;
    if(please_wait)e.innerHTML = please_wait;
    urlsize = oldurl.length-3;
    //params = "pid=2&title=ThisIsIt";
    xmlhttp.open("POST", url, true);
  [COLOR="Red"]  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");[/COLOR]
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.onreadystatechange = function() { response(url, e); }
    try{
      xmlhttp.send(params);
    }catch(l){
    while(e.firstChild)e.removeChild(e.firstChild);//e.innerHTML="" the standard way
    e.appendChild(document.createTextNode("request failed"));
  }
}

function response(url, e) {
  if(xmlhttp.readyState != 4)return;
    var tmp= (xmlhttp.status == 200 || xmlhttp.status == 0) ? xmlhttp.responseText : "<h2><font color=\\"red\\">Error: \\"" + xmlhttp.status+" "+xmlhttp.statusText + "\\"</font></h2><h3>Please let a member of admin know that the link/function you used doesn't work.</h3><h3><a href=\\"javascript:void(0);\\" onclick=\\"open_url('pages/pages.php','main');\\">Homepage</a></h3>";
    var d=document.createElement("div");
    d.innerHTML=tmp;
    setTimeout(function(){
      while(e.firstChild)e.removeChild(e.firstChild);//e.innerHTML="" the standard way
      e.appendChild(d);
    },10)
}

As you can see from the code, when I call something like:

open_url('pages/home.php','main');

it works fine, but the post_reply() function just hangs.

I’m getting quite frustrated with this. Can anyone give it an eyeball check to see if I’ve done something wrong or missed something please?

Many thanks
David

 //params = "pid=2&title=ThisIsIt";
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);

Since params is undefined, params.length must be generating a console error.

When params is defined, I get the same problem, plus it actually get’s stopped on the line above params.length (I put in alert()'s either side and only one showed). I //'d the params line to see if it would fix the problem, but it didn’t, I just forgot to take out the // before I posted.

I’m not a real expert on the subject of Ajax and have managed to alter the GET according to this page: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

I did follow that ^ guide word for word for the code I’ve posted above, but I don’t quite understand all of it.

Can anyone else shed any light on this?

Many thanks
David

p.s. I’ll try and edit the original post to take out the //
EDIT: can’t edit my original post.

Where do you call post_reply() ?

I call it from a form:

<?php
if ($_GET['type']=="new") {
			$title="";
			$location="";
			$pagetext="";
			$button="Submit";
			print "<h1>Create new page</h1>";
		} elseif ($_GET['type']=="existing") {
			$pid=$_GET['id'];
			$query1 = mysql_query("SELECT * FROM authpages WHERE id='$pid'");
			$query2 = mysql_query("SELECT * FROM authpagetext WHERE pid='$pid' ORDER BY date DESC LIMIT 1");
			$row1 = mysql_fetch_array($query1);
			$row2 = mysql_fetch_array($query2);
			$title=$row1['title'];
			$location=$row1['location'];
			$pagetext=$row2['pagetext'];
			$button="Update";
			print "<h1>Edit existing page</h1>";
		}
		?>
			<form method="POST" onsubmit="post_reply('pages/process.php','main');">
			<p>Page Title:<br />
			<input type="text" name="title" value="<?=$title?>" size="30"></p>
			<p>Location:<br />
			<input type="text" name="location" value="<?=$location?>" size="50"></p>
			<p><input type="checkbox" name="command" value="yes" />Show in command list</p>
			<p>Page text:<br />
			<textarea rows="25" name="pagetext" cols="120"><?=$pagetext?></textarea></p>
			<p><input type="submit" value="<?=$button?>" name="action"> &nbsp; <input type="submit" value="Cancel" name="action"></p>
			</form>

Now the problem is obvious - you’re initialising an asychronous request but doing nothing to prevent the form being submitted. Consequently the document is dismissed before the request can complete.
If you’re retrieving data for display or just displaying the result of the submission, you shouldn’t be trying to submit a form.

I don’t think that’s it either. I changed my form so it doesn’t submit anymore, and put the javascript call in the onclick function on the button like so:

<form name="EditForm">
			<p>Page Title:<br />
			<input type="text" name="title" value="<?=$title?>" size="30"></p>
			<p>Location:<br />
			<input type="text" name="location" value="<?=$location?>" size="50"></p>
			<p><input type="checkbox" name="command" value="yes" />Show in command list</p>
			<p>Page text:<br />
			<textarea rows="25" name="pagetext" cols="120"><?=$pagetext?></textarea></p>
			<p><input type="Button" value="<?=$button?>" name="action" onclick="post_reply('pages/process.php','main');"> &nbsp; <input type="Button" value="Cancel" name="action" onclick="open_url('pages/pages.php','main');"></p>
			</form>

Same problem. When I change post_reply(‘pages/process.php’,‘main’); to open_url(‘pages/process.php’,‘main’); process.php loads. So the problem must be with the ajax POST code somewhere.

I’m still scratching my head :confused:

David

EDIT:

I fixed it!!! :smiley:

I left this line in from when I copied the text from the GET command:

urlsize = oldurl.length-3;

Of course oldurl doesn’t exists, so it was stopping!
Yay, I’m happy now. Thanks for all your help Logic Ali!

So you were developing without using the error console…

error console? I don’t know what that is. :confused: Can you explain please? It sounds like it might be very helpful.