AJAX Tutorial

From MapbenderWiki

Jump to: navigation, search

A very simple and basic AJAX application. What we are trying to do is fire an AJAX request with a two strings as parameters. These strings will be concatenated on the server side, and returned to the client side, where the new string will be alerted.

Contents

load AJAX module

AJAX-Modul has to be loaded in the GUI, see AJAX for instructions.

client side

create a file and invoke an AJAX request with JavaScript. In Mapbender, there are three wrapper functions available

  1. mb_ajax_post(url, param, callback)
  2. mb_ajax_get(url, param, callback)
  3. mb_ajax_json(url, param, callback)

if your module is loaded within an iframe, don't forget to write

parent.mb_ajax_post( ...

Parameters

url

url is a string containing the path and file name of the server side script, for example

"../php/demo.php" 

param

param is a Javascript object, use the shortcut object notation {}, for example

{name1:"Hallo", name2:"Welt"}

you can also use variables instead of numbers or strings; like this

var welt = "Welt";

mb_ajax_post("../php/demo.php", {name1:"Hallo", name2:welt}, ...

callback

callback is a function with two parameters, result and status

result is the output of the file specified in url,

function(result, status) {
    if (status == "success") {
        document.body.innerHTML = result;
    }
}

POST, GET, JSON

mb_ajax_post sends the parameters via POST.

mb_ajax_get sends the parameters via GET.

mb_ajax_get sends the parameters via GET and interprets result as a JS object. So result really is an object, not a String.


Example

so a complete AJAX call may look like this. name1 and name2 will be concatenated in demo.php and returned to the callback function as result:

mb_ajax_post("../php/demo.php", {name1:"Hallo", name2:"Welt"}, function(result, status) {
    if (status == "success") {
        document.body.innerHTML = result;
    }
});

server side

create a .php file.

import parameters

if you used an POST request, import the parameters like this

$name = $_POST["name"];

if you used GET or JSON, try this

$name = $_GET["name"];

Avoid the php function import_request_variables! Avoid $_REQUEST if possible, as it is ambiguous.

send correct output headers

HTML

if you are just sending a string, use html header

header("Content-type: text/html;");

(as JSON is also a string, use html headers as well.)

XML

if you are sending an XML, use this

header("Content-type: application/xhtml+xml");

JSON

header('Content-type: application/x-json');

send data

Just send whatever you are willing to send via echo in php, for example

echo $name . " " . $name2;

Example

<?php
    $name1 = $_POST["name1"];
    $name2 = $_POST["name2"];

    header("Content-type: text/html;");
    echo $name1 . $name2;
?>
Personal tools