EToS
{ ADMIN }
posts: 13
last: 24-Sep-2008
TITLE: Run Javascript and Pass HTML replacement via AJAX simultaneously
DESCRIPTION: Have ajax run new javascript code and replace html in one single function
Submitted: 02-Aug-2008 17:12:45 ( 15w 4d 0h ago ) Language: AJAX (*.js *.xml)
Views: 115 Lines of Code: 140 LINES
Rating:
rate: star1
star2
star3
star4
star5
dstar1
dstar2
dstar3
dstar4
dstar5  ( rated! )
  { 5.00 / 5 }
Difficulty: Intermediate
Bookmark
Introduction

passing javascript and html via ajax

Recently I have found that i am using AJAX more and more with the sites that i develop, most people usually use AJAX to pass HTML back to a webpage, however i wanted to pass back Javascript aswell and have that actually run on the page without having to reload. However depending on whether your sending HTML or Javascript your AJAX function will need to change how it responds to the AJAX response.

To fix this ive made an ajax function which splits the AJAX response and runs the HTML half inside a hidden ajax div, and takes the second half of the AJAX response and runs it inside Javascript's eval() function.

Here is the code for the AJAX function:

/* This function contacts server side using regular ajax */

function ajaxFunction(returnDiv, url, params, posttype) {
    var ajaxRequest;    // Main ajax var

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // IE
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }

  // function to receive data from server
  ajaxRequest.onreadystatechange = function() {//Call a function when the state changes.
      if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {

          returnData = ajaxRequest.responseText;

          document.getElementById("ajaxLoading").style.display = 'none';

          //split return string into html and javascript code
          var seperateData = new Array();
          seperateData = returnData.split("@@@@@@@@@@@@@@@@@@@@@@@@@@1234@@@@@@@@@@@@@@@@@@@@@@@@@@");

          eval(seperateData[1]);                                                 //  eval js code
          document.getElementById(returnDiv).innerHTML = seperateData[0];        //  html code

      }
  }

  if(posttype == "GET"){
    ajaxRequest.open("GET", url+"?"+params, true);
    ajaxRequest.send(null);
  }else if(posttype == "POST"){
    ajaxRequest.open("POST", url, true);

    // send header info with request
    ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajaxRequest.setRequestHeader("Content-length", params.length);
    ajaxRequest.setRequestHeader("Connection", "close");

    ajaxRequest.send(params);
  }
}

retrunDiv = a <div id="here"></div>   that you want HTML to come back through.

url = is the path to your PHP server file that processes the request before returning back data via AJAX. similar to action field with html forms...    ie: url could be:   "/include/process.php"

params = are the parameters to be passed to the url. for example you could pass into the parameter values like:   name=Barack&surname=Obama&party=democrats   (more below on how ive done this in my code)

posttype = either POST or GET depending on that kind of data your sending to your url PHP page. GET is basically for just retrieving data whereas POST may involve anything, like storing or updating data, or sending an email for example.

 

Now we need to call the ajaxFunction with:

function ajaxSendFunction(data, from, html, forms, go, here) {

    //ajaxLoading on
    document.getElementById("ajaxLoading").style.display = 'block';
       
    var params = "ajaxrequest=1" +
                 "&data=" + data +
                 "&from=" + from +
                 "&html=" + html +
                 "&forms=" + forms +
                 "&go=" + go +
                 "&here=" + here;

    ajaxFunction("ajaxDiv", "/include/process.php", params, "POST");
}
This Function basically takes HTML form information, formats to params information and turns on an ajax icon (you'll need to add one on your page called ajaxLoading)

It is called from a HTML form button with:

<input type="button" name="Submit" value="Submit" onclick="javascript:ajaxSendFunction(

       yourFormName.data.value)

       yourFormName.from.value)

       yourFormName.html.value)

       yourFormName.forms.value)

       yourFormName.go.value)

       yourFormName.here.value);" />

NB: some people might say this function could be merged with the ajaxFunction, however i have kept it seperate and passing values into ajaxFunction in order allow for other code to be added later, such as pre-ajax code which needs to be run before the ajax. If i merged the functions then it would make the ajaxFunction rather messy and less reusable across the site.

 

Finally, now that you have a ajaxFunction to deal with your AJAX request, you'll need a PHP file on the server end (the url address mentioned above) to respond back with HTML data and JavaScript:

   if(isset($_POST['ajaxrequest'])){              //  check ajaxrequest parameter is 1
      $this->procAjaxRequest();
   }

   /* procAjaxRequest - takes parameters, processes them and replies with HTML and JS to be executed */
  
   function procAjaxRequest(){
      global $session, $form, $database;

      // Here you would process the form information
      // ie:  $retval = someOtherFunction($_POST['param_name_here'], $_POST['param_name_here'].... etc);

      /* Output to Ajax */
     
      if($retval){    //  if response from someOtherFunction() was true..   could just add if(true) to run anyway

          //  html
            $retdat  = "<b>test</b>";   // html to send back to div on page
              
          //  add html/js seperator (anything unique. a comma for example would be silly as it might be part of the html text)
          $retdat .= "@@@@@@@@@@@@@@@@@@@@@@@@@@1234@@@@@@@@@@@@@@@@@@@@@@@@@@";

          //  javascript
              $retdat .= "document.getElementById("ajaxDiv").style.display = 'block';";
      }
      // failed
      else{
          //  if fail dont change a thing
      }

       echo $retdat;   //echo data via ajax
   }

so for example you could have a div like:    <div id="ajaxDiv" style="display: none"></div>         hidden and with no text, and once the ajax returns it would now equal <b>test</b>  and no longer be hidden. In a real example this could be a success box showing data was sent etc.

The Javascript ajaxFunction takes the returned data from the PHP file, hides the ajaxLoading image/div, splits the html and javascript (using the seperator), adds the html to the returnDiv, and then finally executes the returned Javascript code inside the eval() function.

The result means that you can output both HTML and Javascript with ease from one single function  :)