AJAX Form sends String out to a php script; takes back what's echoed

Discussion in 'JavaScript' started by DaEMoN33, Apr 19, 2007.

  1. #1
    Hi,

    I have a php script that takes a string, modifies it, and echoes it back.

    I would like to use the script through an AJAX form.

    Suppose I have the form in ajax.html and the script in script.php. How would I go on about sending the string inserted in ajax.html out to script.php, collecting the echoed string from script.php and document.write() it under the form in ajax.html?

    I have developed something but it's not working and I can't seem to figure out what it is.

    Any help is appreciated. Thanks!
     
    DaEMoN33, Apr 19, 2007 IP
  2. phper

    phper Active Member

    Messages:
    247
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #2
    You send can send the string to your script.php by using an XmlHttpRequest object. After you get the string back, you can do whatever you want to do with it, but not using document.write(), though. You may want to have a read a bit on DOM (Document Object Model).

    Also, this tutorial on Ajax may help you: http://www.php-etc.com/tutorials/Ajax/
     
    phper, Apr 19, 2007 IP
  3. DaEMoN33

    DaEMoN33 Active Member

    Messages:
    49
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    71
    #3
    The thing is, though, I am not exactly sure on how to send out the string to the script..
    Is the following the right way?

    I have the ajax function in itself, with the XTMHttpRequest and the browser compatibility 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("Error!");
    				return false;
    			}
    		}
    	}
    Code (markup):
    Then I have the onreadystatechange and I store the responseText in a variable. I then send the variable off to the script. Is this even remotely correct?
    
    	ajaxRequest.onreadystatechange = function(){
    		if(ajaxRequest.readyState == 4){
    			var try = ajaxRequest.responseText;
    		}
    	}
    	ajaxRequest.open("POST", script.php, true);
    	ajaxRequest.send(try);
    Code (markup):
     
    DaEMoN33, Apr 20, 2007 IP
  4. Aragorn

    Aragorn Peon

    Messages:
    1,491
    Likes Received:
    72
    Best Answers:
    1
    Trophy Points:
    0
    #4
    No that is not the way to send the variables. suppose you want to send the variables fruit and color with the values apple and red respectively, then use
    
    ajaxRequest.send('fruit=apple&color=red');
    
    Code (markup):
     
    Aragorn, Apr 21, 2007 IP