SitePoint Sponsor

User Tag List

Results 1 to 9 of 9
  1. #1
    SitePoint Zealot
    Join Date
    Mar 2006
    Posts
    133
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Unhappy 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:

    Code:
    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);
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        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:
    Code:
    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

  2. #2
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code:
     //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.
    Tab-indentation is a crime against humanity.

  3. #3
    SitePoint Zealot
    Join Date
    Mar 2006
    Posts
    133
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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_...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.

  4. #4
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Me01273 View Post
    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.
    Where do you call post_reply() ?
    Tab-indentation is a crime against humanity.

  5. #5
    SitePoint Zealot
    Join Date
    Mar 2006
    Posts
    133
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I call it from a form:

    PHP Code:
    <?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>

  6. #6
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Me01273 View Post
    I call it from a form:

    <form method="POST" onsubmit="post_reply('pages/process.php','main');">
    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.
    Tab-indentation is a crime against humanity.

  7. #7
    SitePoint Zealot
    Join Date
    Mar 2006
    Posts
    133
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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:

    Code:
    <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

    David


    EDIT:

    I fixed it!!!

    I left this line in from when I copied the text from the GET command:
    Code:
    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!

  8. #8
    SitePoint Guru
    Join Date
    Sep 2006
    Posts
    731
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Me01273 View Post

    EDIT:

    I fixed it!!!

    I left this line in from when I copied the text from the GET command:
    Code:
    urlsize = oldurl.length-3;
    Of course oldurl doesn't exists, so it was stopping!
    So you were developing without using the error console...
    Tab-indentation is a crime against humanity.

  9. #9
    SitePoint Zealot
    Join Date
    Mar 2006
    Posts
    133
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    error console? I don't know what that is. Can you explain please? It sounds like it might be very helpful.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •