Using AJAX functionality within our SAP BSP

First of all please don't be afraid of AJAX, AJAX is your friend as the implementation of which is very simple and can be a very powerful way of actually performing additional functionality. It also provides the ABAPer with a way of dynamically updating an HTML screen incorporating more ABAP code and less javascript code. Yes Javascript is very powerfull and yes you can add ABAP code within your Javascript code so that for example different js code can be executed based on ABAP variables.

<% case runtime->page_name.
when 'index.html'.%>
<script language="javascript" type="text/javascript">
function stopRKey(evt) {
....
<% endcase.%>

But when you want to capture values using javascript i.e. document.getElementById("firstName").value it is then not possible to pass this value to your ABAP code and process it and then pass any returning value back to the html fields via javascript i.e. document.getElementById("firstName").value == 'new value';

This is where AJAX comes in handy, it basically allows you to call a javascript function which then uses basic javascript functionality to capture the fields on screen. It then passes these values to a second htm page where you can process them within the second screens event handler using ABAP code. This second page can then display new HTML code based on the processing of these values and any additional abap code. This HTML code will replace that contained within a specified div tag on the initial page.

This is also all done without re-drawing the screen so depending on processing performed will all happen without the user seeing a screen refresh.

So basically the example I am going to show now has an initial screen with staff search fields on it and when you press the search button it triggers an ajax which captures the values entered by the user and displays a relevant list of staff/pernr records.

Step 1 - Create new BSP Application
Using SE80 create BSP Application (I.e. ZTESTAJAX).

Step 2 - Create new page (index.htm)
Right click on BSP object name and select create->page (with flow logic) and give it the name 'index.htm'.

Step 3 - Populate 'Layout' tab
Insert the following HTML code into the index.htm layout section.

  <%@page language="abap" %>
<%@extension name="htmlb" prefix="htmlb" %>
<html>
 <head>
  <title>BSP AJAX call</title>
    <script type="text/javascript" src="js/staff_ajax.js"></script>
 </head>
 <body>
    <form action="#">
      <fieldset>
        <label for="forename">Forename:</label>
        <input id="forname" type="text" /><br>
        <label for="surname">Surname:</label>
        <input id="surname" type="text" /><br>
        <label for="personnelno">Personnel No.:</label>
        <input id="personnelno" type="text" /><br>
        <label for="hits">No. of results to return:</label>
        <input id="hits" type="text" value="100" /><br>
        <a class="btn-icon" href="#" onclick="staffSearch();"> Search</a>
        <div id="staffResults">
          <h3>Results</h3>
          <table>
            <thead>
              <tr>
                <th>Forename</th>
                <th>Surname</th>
                <th>Personnel No.</th>
                <th>Contract Start Date</th>
                <th>Contract End Date</th>
                <th>Location (Org Unit)</th>
                <th>Employment Status</th>
                <th>Employee Group</th>
                <th>Action</th>
              </tr>
            </thead>
          </table>
        </div>
    </form>
 </body>
</html>


Step 4 - Create .js file
Right click on BSP object name and select create->page (with flow logic) and give it the name 'js/staff_ajax.js'. This will create the file 'staff_ajax.js' within the folder called 'js'.


Step 5 - Populate 'Layout' tab
Insert the following javascript code into the staff_ajax.js layout section.

  <%@page language="abap" %>
function staffSearch()
{
    var v_value = document.getElementById("forname").value;
    var v_lname = document.getElementById("surname").value;
    var v_staffid = document.getElementById("personnelno").value;
    var v_hits = document.getElementById("hits").value;
    staffAJAXReplace('staff_search.html', 'staffResults', v_value, v_lname, v_staffid, v_hits);
}
function staffAJAXReplace( v_page, v_id, v_value, v_lname, v_staffid, v_hits )
{
 var xmlHttp;
try
  {
  // Firefox, Opera 8.0+, Safari
   xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
    // Internet Explorer
     try
     {
       xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
     }
   catch (e)
     {
        try
         {
           xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
       catch (e)
         {
          alert("Browser does not support AJAX!");
          return false;
        }
     }
  }
xmlHttp.onreadystatechange= function()
  {
    if(xmlHttp.readyState==4)
      {
          document.getElementById(v_id).innerHTML=xmlHttp.responseText;
      }
    }
  xmlHttp.open("GET",v_page+"?v_value="+v_value+"&v_lname="+v_lname+"&v_staffid="+v_staffid+"&v_hits="+v_hits,true);
    xmlHttp.send(null);
}


Step 6 - Create new page (staff_search.htm)
Right click on BSP object name and select create->page (with flow logic) and give it the name 'staff_search.htm'. This creates the updated HTML code after the ajax functionality has been called.

Step 7 - Populate 'Layout' tab
Insert the following HTML code into the staff_search.htm layout section.

  <%@page language="abap" %>
        <h3>Results</h3>
        <table >
          <thead>
            <tr>
              <th>Forename</th>
              <th>Surname</th>
              <th>Personnel No.</th>
              <th>Contract Start Date</th>
              <th>Contract End Date</th>
              <th>Location (Org Unit)</th>
              <th>Employment Status</th>
              <th>Employee Group</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
          <% data: wa_staff like line of it_staff.
             loop at it_staff into wa_staff.%>
            <tr>
              <td><%=wa_staff-vorna%></td>
              <td><%=wa_staff-nachn%></td>
              <td><%=wa_staff-pernr%></td>
              <td><%=wa_staff-cbeg%></td>
              <td><%=wa_staff-cend%></td>
              <td><%=wa_staff-orgeh%></td>
              <td><%=wa_staff-stat2%></td>
              <td><%=wa_staff-persg%></td>
              <td><a  href="?OnInputProcessing(staff<%=wa_staff-pernr%>,<%=wa_staff-orgeh%>,<%=wa_staff-vorna%>,<%=wa_staff-nachn%>)"
onclick="PassValues();"> Select</a></td>
            </tr>
           <%endloop.%>
          </tbody>
        </table>

Step 8 - Type Definitions Tab
Define structure to store staff records

types: begin of t_staff,
  pernr type pa0002-pernr,
  vorna type pa0002-vorna,
  nachn type pa0002-nachn,
  orgeh type pa0001-orgeh,
  stat2 type pa0000-stat2,
  persg type pa0001-persg,
  cbeg  type pa0615-cbeg,
  cend  type pa0615-cend,
 end of t_staff.
types: tt_staff type STANDARD TABLE OF t_staff.

Step 9 - Page Attributes Tab
Add the following page attributes to the page attributes tab

it_staff	TYPE	TT_STAFF
v_hits		TYPE	STRING
v_lname		TYPE	STRING
v_staffid	TYPE	STRING
v_value		TYPE	STRING

Step 10 - Event Handler Tab -> OnInitialization
The below code captures the values passed within the ajax call within staff_ajax.js

data: r_vorna type range of pa0002-vorna,
      r_nachn type range of pa0002-nachn,
      r_staffid type range of pa0002-pernr,
      wa_vorna like line of r_vorna,
      wa_nachn like line of r_nachn,
      wa_staffid like LINE OF  r_staffid .
v_value   = request->get_form_field( 'v_value' ).
v_lname   = request->get_form_field( 'v_lname' ).
v_staffid = request->get_form_field( 'v_staffid' ).
v_hits    = request->get_form_field( 'v_hits' ).
TRANSLATE v_value TO UPPER CASE.
TRANSLATE v_lname TO UPPER CASE.
if not v_value is INITIAL.
wa_vorna-low = v_value.
wa_vorna-option = 'EQ'.
wa_vorna-sign = 'I'.
append wa_vorna to r_vorna.
endif.
if not v_lname is INITIAL.
wa_nachn-low = v_lname.
wa_nachn-option = 'EQ'.
wa_nachn-sign = 'I'.
append wa_nachn to r_nachn.
endif.
if not v_staffid is INITIAL.
wa_staffid-low = v_staffid.
wa_staffid-option = 'EQ'.
wa_staffid-sign = 'I'.
append wa_staffid to r_staffid.
endif.
select a~stat2 a~pernr
       b~orgeh b~persg
       c~vorna c~nachn
       d~cbeg d~cend
    up to v_hits rows
    into CORRESPONDING FIELDS OF TABLE it_staff
   from pa0000 as a inner join pa0001 as b
      on b~pernr eq a~pernr
  inner join pa0002 as c
     on c~pernr eq a~pernr
     inner join pa0615 as d
     on d~pernr eq a~pernr
  where a~begda le sy-datum and
        a~endda ge sy-datum and
        b~begda le sy-datum and
        b~endda ge sy-datum and
        c~begda le sy-datum and
        c~endda ge sy-datum and
        d~begda le sy-datum and
        d~endda ge sy-datum and
        c~VNAMC in r_vorna  and
        c~NCHMC in r_nachn  and
        a~pernr in r_staffid .

Step 11 - Activate and test
Save everything and press the activate button. If all is ok when you test the application it should open up a browser window and display your newly created BSP. You can place a break-point in the OnInputProcessing event of the staff_search.htm page and check that the values from the original page(index.htm) are coming through to here and that the correct values are being returned in th layout when you press the search button.

When you first execute the application you will be presented with the search fields


Simply enter your search criteria and press the search link


Related Articles

Javascript to capture when a user closes or leaves sap bsp html page
Close BSP Session (type 'Pluggin HTTP') including when in SAP portal
SAP BSP to auto select region when user selects country using HTML and Javascript
HTML and Javascript code to force enter key to perform tab
JavaScrip command getElementById useful examples
MVC BSP input field - Demonstrate how to retrieve a value entered into text input field
Allowing multiple instances of a BSP application to be run by a user
Execute Standard SAP Transaction from BSP using dynamically created shortcut
Uplaod file within SAP BSP application using HTML and ABAP coding
UUseful SAP BSP application code - ABAP, HTML, HTMLB, Javascript, CSS
Creating a BSP Application class to help store and pass data betwenn your BSP pages
Training Course and Workshop Booking Form
BSP checkboxes using HTML and the OnInputProcessing BSP Event
BSP checkboxes using HTML and the OnInputProcessing BSP Event
Check HTML checkbox is checked using Javascript within your SAP BSP
BSP Dropdown List - create a BSP dropdown list which allows user selection!!
ABAP BSP to allow user to select from SAP HR org structure - CSS file
Java script to display tree structure on your SAP BSP web page
Create a Simple BSP - Simple BSP to display text and call section BSP page using HTML
SAP BSP Training course booking - Creating an example training course booking form using BSP
Creating an SAP BSP which executes an ABAP report to retrieve data for use within BSP application
org selection BSP - detials.htm page
Display page of the SAP BSP example application to store favourite tcodes as a cookie
Execute.htm page of the SAP BSP example application to store favourite tcodes as a cookie
Favourites cookie bsp - initial page to display input fields and retrieve user input
BSP using cookies - Demonstrate use of cookies within a BSP to store user favourits
ABAP Export data to memory - Demonstrate use of ABAP program to retrieve data for use in BSP
MVC BSP HTMLB input field - Demonstrate how to retrieve a value entered into text input field
BSP development using standard HTML code instead of Business HTML (HTMLB)
Business HTML (HTMLB) - List of business HTML tags you can use within your BSP
Adding JavaScript to BSP (HTML) pages - Shows how to add javascript to your BSP pages
Example JavaScript code which can be added to your BSP application
BSP MIME Objects for Org. search application
Call onInputProcessing event from SAP BSP page via href or button
Organisation selection BSP - close internet window using javascript
Organisation selection BSP - get server side cookie ( get_server_cookie )
orgaisation selection BSP - set and get server side cookie ( set_server_cookie )
Display orgaisation selection BSP
BSP which allows HR Organisation Structure search and selection using javascript
Organisation update program - get server side cookie ( get_server_cookie )
BSP to capture user entry into HTML input fields
Capture BSP radiobutton selection using HTML and the OnInputProcessing BSP Event
BSP checkboxes using HTML and the OnInputProcessing BSP Event
Stateful and stateless BSP applications
Get user entry into HTML input fields with SAP BSP
Javascript to capture when a user closes or leaves sap bsp html page
Creating a BSP using the Model View Controller ( MVC ) technique
Using SAP Model View Controller (MVC) development techniques to develop BSPs
Adding a JavaScript date selection field to a BSP
Creating a BSP using the Model View Controller ( MVC ) technique
Creating a BSP using the Model View Controller(MVC) technique
Creating a BSP using the Model View Controller ( MVC ) technique
Retrieve value from input text field within a model view controller ( MVC) BSP
Web Application Development - Example code and information on development using BSP
SAP BSP / Business Server Pages combine ABAP and other web technologies such as HTML, CSS
BSP development screen - developing application using business server pages
Standard Program created in SE38 or SE80