tags:

views:

47

answers:

2

I stored data in MySQL database using AJAX and it is working. But I face a problem to retrieve data using AJAX.

My coding for storing data (its a posting comment page):

function sendMail(form_id) {
    // Do a client-side check; if it passes, then move on; 
    // otherwise, report an error to the user

    //if (!validatePage(form_id)) return;
    if(!checkMail(document.getElementById('txtEmail').value))
    {
        document.getElementById('txtEmail').focus();
        return false;
    }
    window.scrollTo(0,0);
    divId = "results";
    var str = "";
    var elem = document.getElementById(form_id).elements;
    for (var i = 0; i < elem.length; i++) {
        if (
            (elem[i].type == "hidden") || 
            (elem[i].type == "text") || 
            (elem[i].type == "textarea")
        ) {
            // Text field
            str += elem[i].id + "=" + escape(encodeURI(trimField(elem[i].id))) + "&";
        }
        else if (elem[i].type == "checkbox") {
            // Check box
            if (elem[i].checked) {
                str += elem[i].id + "=on&";
            }
            else {
                str += elem[i].id + "=off&";
            }
        }
        else if (elem[i].type == "select-one") {
            // Drop-down menu (SELECT)
            var sel = elem[i];
            str += sel.id + "=" + sel.options[sel.selectedIndex].value + "&";
        }
    }
    str = str.substring(0, str.length-1);
    str = str.replace(/%250A/g,"\n") // Make sure that line breaks get transmitted properly
    if (form_id == "contact_form") {
        form_page = "sendMail.php";
    }
    AjaxRequest(form_page, str, "post");
}

// Make the AJAX request
function AjaxRequest(url, parameters, type) {
    http_request = false;
    if (window.XMLHttpRequest) {
        // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            // set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
        }
    }
    else if (window.ActiveXObject) {
        // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e) {
            }
        }
    }
    if (!http_request) {
        alert("Cannot create XMLHTTP instance");
        return false;
    }
    if (type == "post") {
        // POST
        http_request.open('POST', url, true);
        http_request.onreadystatechange = AjaxRequestCb;
        http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        http_request.setRequestHeader("Content-length", parameters.length);
        http_request.setRequestHeader("Connection", "close");
        http_request.send(parameters);
    }
    else if (type == "get") {
        // GET
        http_request.open('GET', url + parameters, true);
        http_request.onreadystatechange = AjaxRequestCb;
        http_request.send(null);
    }
    // if...else
}

// AJAX Callback
function AjaxRequestCb() {
    if (
        http_request.readyState == 1 || 
        http_request.readyState == 2 || 
        http_request.readyState == 3
    ) {
    }
    else if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            result = http_request.responseText;
            document.getElementById(divId).innerHTML = result;
            // If CAPTCHA failed, then repopulate it
            if (result.indexOf("CAPTCHA") > -1) {
                Recaptcha.reload();
            }
            else {
                // Clear form after email has been sent
                document.forms["contact_form"].reset(); // Not robust, I know (will modify later)
                Recaptcha.reload(); // Display a new CAPTCHA
            }
        }
        else {
            alert("Callback failed. There was a problem with the request.");
        }
    }
}

// Remove any unneccessary whitespace
function trimField(field) {
    re = /(^\s*)([^\b]*\S)(\s*$)/;
    if (re.test(document.getElementById(field).value)) {
        document.getElementById(field).value = document.getElementById(field).value.replace (re, "$2");
        return document.getElementById(field).value;
    }
    else {
        document.getElementById(field).value = "";
        return "";
    }
}

// The phone field shows how the user should input a phone number; 
// on the first focus, the value will be cleared so the user can 
// enter a phone number
function clearField(field_id) {
    if (first_time) {
        document.getElementById(field_id).value = "";
        first_time = false;
    }
}
+2  A: 
  1. Your AJAX will query a PHP page with some GET or POST parameters (those parameters could be something like search filters or anything else revelent to your project). You don't always need parameters, but you will usually need some in most projects.
  2. This PHP page will then query the MySQL database based on these parameters.
  3. Finally this PHP page will output data in a parsable format like XML, JSON... Or you could also output HTML direcly but it's less portable.
  4. Then the JavaScript interpret the AJAX response (the data outputted by PHP based on the data received from MySQL).

You can see a tutorial here on Tizag or just Google it...

AlexV
Added some tutorials to my answer.
AlexV
A: 

Ajax just means "Making an HTTP request without leaving the current page". It is only concerned with the communication between the webserver and the browser. You still get a normal HTTP request (which, in this case, presumably causes a PHP program to run).

The issues of connecting to a database and getting data from it using PHP are the same for an Ajax request as any other request.

The only difference is that you will probably want to output something other than a complete HTML document.

David Dorward