Sending data to a MySQL database with AJAX / XmlHtttpRequest

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
Loki
Forum Commoner
Posts: 25
Joined: Wed Jun 03, 2009 9:23 pm

Sending data to a MySQL database with AJAX / XmlHtttpRequest

Post by Loki »

I've looked through a few tutorials and don't completely understand this, if anyone could look at my code and tell me what exactly I need to change, I'd be grateful.

Edit: I suppose it'd be helpful if you knew what I was trying to do.

Basically, I have a form in the index file, and a sql database that simply consists of an auto_increment id field, and a value field. I want the data from the input form to be put into the value field in the database as a new entry, without refreshing the page, when the button is clicked.

index file:

Code: Select all

 
<script language="javascript">
function getXhrObject() {
    var xhrObject = false;
    // Most browsers (including IE7) use the 3 lines below
    if (window.XMLHttpRequest) {
        xhrObject = new XMLHttpRequest();
    }
    // Internet Explorer 5/6 will use one of the following
    else if (window.ActiveXObject) {
        try {
        xhrObject = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(err) {
                try {
                xhrObject = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(err) {
                xhrObject = false;
                }
        }
    }
    return xhrObject;
}
 
var ajaxCapable = getXhrObject();
if (ajaxCapable) {
// perform some Ajax functionality here
    function sendCatch(data) {
    //actually send the data to the php script
        //loading message
        document.write('Sending...');
        //send
        ajaxCapable.onreadystatechange = checkServerResponse;
        ajaxCapable.open("POST", "send.php", true);
        ajaxCapable.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        ajaxCapable.send("data="+data.value);
    }
    
    function displayMessage(el) {
    //display success or fail message
        if(el == 'SUCCESS') {
            document.write('Data sent successfully');
        } else {
            document.write('There was an error sending the data');
        }   
    }
 
    function doUpdate(data) {
        if (sendCatch(data)) {
            displayMessage('SUCCESS');
        } else {
            displayMessage('FAIL'); 
        }
    }
}
</script>
<input id="data" type="text" name="data" />
<br />
<script language="JavaScript">
var thedata = document.getElementById('data').value;
</script>
<input type="button" onclick="doUpdate(thedata);" value="Send Data" />
 
send.php

Code: Select all

 
<?php
function doConnect() {
//connects to the database
    $con = mysql_connect("localhost","user","pass");
    if (!$con)
    {
        die('Database Connection Error: ' . mysql_error());
    }
    mysql_select_db("ajax", $con);
}
doConnect();
$data = $_POST['data'];
$data = mysql_real_escape_string($data);
$query = "INSERT INTO ajax VALUES(NULL, '" . $data . "')";
mysql_query($query) or die(mysql_error());
?>
 
Loki
Forum Commoner
Posts: 25
Joined: Wed Jun 03, 2009 9:23 pm

Re: Sending data to a MySQL database with AJAX / XmlHtttpRequest

Post by Loki »

I've changed the script (edited above) but it still wont do anything at all.
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Sending data to a MySQL database with AJAX / XmlHtttpRequest

Post by kaszu »

Problem is that data which is sent is an empty string

Code: Select all

<input id="data" type="text" name="data" /><br /><!-- 1 -->
<script language="JavaScript">
var thedata = document.getElementById('data').value; //<!-- 2 -->
</script>
<input type="button" onclick="doUpdate(thedata);" value="Send Data" /><!-- 3 -->
1) When page is loaded input "data" value is empty string
2) Script is executed as soon as it's loaded by browser (that's right after input 'data' is created), so thedata value is set to empty string
3) When button is clicked doUpdate is called passing empty string as argument

Solution is to get data when button is clicked:

Code: Select all

function doUpdate() {
    var data  = document.getElementById('data').value;
    if (sendCatch(data)) {
        displayMessage('SUCCESS');
    } else {
        displayMessage('FAIL');
    }
}
Also sendCatch doesn't return a value, so following condition will always fail

Code: Select all

if (sendCatch(data)) {
and 'FAIL' message will be shown, even if data was sent successfully.

You should install Firebug, under 'Console' tab you can see all AJAX calls, sent data and response.
Loki
Forum Commoner
Posts: 25
Joined: Wed Jun 03, 2009 9:23 pm

Re: Sending data to a MySQL database with AJAX / XmlHtttpRequest

Post by Loki »

How do I make it return a value based on whether it failed or not?

I do have firebug installed, I'm just not very experienced with Javascript.


Also, for some reason it reloads the page with only the word "Sending..." and it just sits there continuously loading and never enters the data. I'd like it to just print the word sending after the input box, and then a success message when it's done.
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Sending data to a MySQL database with AJAX / XmlHtttpRequest

Post by kaszu »

sendCatch doesn't and can't return ajax result since this is asynchronous

Code: Select all

function doUpdate() {
    var data  = document.getElementById('data').value;
    sendCatch(data);
    displayMessage('Loading...');
}
In function checkServerResponse (which you haven't posted) call displayMessage with needed message if ajax request readyState changes to 4 (complete).
To display message after input, place <span> element after input and in displayMessage change the content of the span (innerHTML method) to the needed message.
Loki
Forum Commoner
Posts: 25
Joined: Wed Jun 03, 2009 9:23 pm

Re: Sending data to a MySQL database with AJAX / XmlHtttpRequest

Post by Loki »

Most of this I just followed from a half-baked tutorial.

I think I need to study up on Javascript/AJAX a bit more before I try to take this any further.
Post Reply