views:

47

answers:

1

I have a website built across a series of pages and scripts, and I'm trying to link them together using Ajax. I was told the easiest way to send back to the server was using jQuery, so I'm trying that out but I can't seem to get it to work. My three files are as follows, with the methods in question being the lines containing onclick() and the MySQL query in file 3.

Here's the page itself:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Penelope, Upgraded</title>

    <script type="text/javascript" src="jLaser.js"/>
    <script type="text/javascript" src="jquery.js"/>


    <?php

        require_once 'mysqlSheep.php';
        require_once 'background.php';

        $hour = date("G");
        $hour = mysql_real_escape_string($hour);

        mysql_query("INSERT INTO time( hour ) VALUES (".$hour.")
                    ON DUPLICATE KEY UPDATE hits = hits+1")
                    or die ("MySQL Error: ".mysql_error());
    ?>
</head>

<body id="<?php echo day() == 1 ? 'day' : 'night'; ?>">
    <button type="button"
            onclick="laser(); $.post('sheepDB.php', { vic: victim, num: numVics });">
    Activate Her Powers!
    </button>

    <div id="lasertext"></div>

    <p>Want to see how many things Queen Penelope <a href="http://www.queenofsheep.com/Sheep/victimlist.php"&gt;has decimated?</a></p>

</body>
</html>

Here's the .js script containing my the series of functions called first by onclick():

/*
 * Initialize laserState to 0
 * i.e. the laser is off.
 */
var laserState = 0;
var numVics;

/*
 * Function: laser
 * Called from button on jSheep.php
 *
 * If the laser is on, i.e. laserState = 0,
 * it calls laserOn(). Otherwise, it calls laserOff().
 *
 * @call laserOff() if laserState == 1
 * @call laserOn() if laserState == 0
 */
function laser()
{
    laserState ? laserOff() : laserOn();
}

/*
 * Function: laserOff
 * Called from function laser()
 *
 * Turns off the laser.
 * Sets laserState to 0,
 * prints a message about the laser being off,
 * and switches the image to the sheep minus the laser.
 */
function laserOff()
{
    laserState = 0;

    if ( document.getElementById("vartext") )
    {
        var textdiv = document.getElementById("lasertext");
        var para = document.getElementById("vartext");

        textdiv.removeChild(para);
    }

    if ( document.getElementById("nightlaser") )
    {
        var body = document.getElementById("nightlaser");

        body.setAttribute('id', 'night');
    }

    if ( document.getElementById("daylaser") )
    {
        body = document.getElementById("daylaser");

        body.setAttribute('id', 'day');
    }

    textdiv = document.getElementById("lasertext");
    para = document.createElement("p");
    var text = document.createTextNode("Queen Penelope has deactivated her lasers.");

    para.setAttribute("id", "vartext");
    para.appendChild(text);
    textdiv.appendChild(para);
}

/*
 * Function: laserOn
 * Called from function laser()
 *
 * Turns on the laser
 * Sets laserState to 1,
 * removes the text about the laser being off,
 * calls function selectVictim
 * and uses the returned value to call function zapVictim.
 *
 * @call selectVictim()
 * @call zapVictims()
 */
function laserOn()
{
    laserState = 1;

    if ( document.getElementById("vartext") )
    {
        var textdiv = document.getElementById("lasertext");
        var para = document.getElementById("vartext");

        textdiv.removeChild(para);
    }

    if ( document.getElementById("night") )
    {
        var body = document.getElementById("night");

        body.setAttribute('id', 'nightlaser');
    }

    if ( document.getElementById("day") )
    {
        body = document.getElementById("day");

        body.setAttribute('id', 'daylaser');
    }

    return selectVictim( function( victim ) {zapVictims(victim);} );
}

/*
 * Function: selectVictim
 * Called from function laserOn()
 *
 * Selects a random victim from a list of victims
 *
 * @return String: victim
 */
function selectVictim(callback)
{
    var vicString;
    var vicArray;
    var vicID;

    var params = "url=queenofsheep.com/Sheep/victims.php";
    var request = new ajaxRequest();

    request.open("POST", "victims.php", true);
    request.setRequestHeader("Content-Type",
                             "application/x-www-form-urlencoded");
    request.setRequestHeader("Content-Length", params.length);
    request.setRequestHeader("Connection", "close");

    request.send(params);

    request.onreadystatechange = function ()
    {
        if (this.readyState == 4)
        {
            if (this.status == 200)
            {
                if (this.responseText != null )
                {
                    vicString = this.responseText;
                    vicArray = JSON.parse(vicString);
                    vicID = Math.floor(Math.random() * (vicArray.length - 1));

                    if(callback)
                    {
                        callback(vicArray[vicID]);
                    }
                }
                else alert("Ajax error: No data received");
            }
            else alert("Ajax Error: " + this.statusText);
        }
    }
}

/*
 * Function: zapVictims
 * Called from function laserOn()
 *
 * @Arg String: victim
 *
 * Given the identifier of a victim,
 * generates a pseudorandom number of victims
 * to be zapped with the laser.
 * Then, it passes this number and the victim string
 * to a PHP script that updates the database values.
 */
function zapVictims( victim )
{
    numVics = Math.floor(Math.random() * 100) + 1;

    var textdiv = document.getElementById("lasertext");
    var para = document.createElement("p");
    var text = document.createTextNode("Queen Penelope has dissolved " + numVics + " " + victim + "!");

    para.setAttribute("id", "vartext");
    para.appendChild(text);
    textdiv.appendChild(para);
}

/*
 * Function: ajaxRequest
 * Called whenever external data is needed
 *
 * Tried to create a new XMLHttpRequest object
 * If it can't, attempts to correct for IE.
 * Finally, if it still can't, returns false.
 * Otherwise, it returns the created object.
 *
 * @return Boolean false
 * @return Object XMLHttpRequest
 * @return Object ActiveXObject
 */
function ajaxRequest()
    {
        try
        {
            var request = new XMLHttpRequest();
        }
        catch(e1)
        {
            try
            {
                request = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e2)
            {
                try
                {
                    request = new ActiveXObject("Microsoft.XMLHTTP");
                }
                catch(e3)
                {
                    return false;
                }
            }
        }
        return request;
    }

And finally, the script that should be receiving the POST data:

<?php

require_once 'mysqlSheep.php';

$numVics = mysql_real_escape_string($_POST["numVics"]);
$vic = mysql_real_escape_string($_POST["vic"]);

mysql_query("
            UPDATE victims
            SET amount=amount+".$numVIcs."
            WHERE victim='".$vic."'"
           );

?>

Where am I going wrong? Are the variables from the Javascript file (which is included in the page) not available to onclick? Everything works as it should except for the MySQL update in the third file.

A: 

A handful of things:

  • Where is the variable "victim" being defined (in your first file, when you make the call to $.post() )?

  • Why are you defining your own method of making an AJAX call in the second file? You're recreating the functionality of $.post().

  • If you want to do a lot of ajax programming, I highly encourage that you learn:
    • How to use Fiddler
    • The HTTP protocol (so that you can understand what Fiddler is showing you).
Stargazer712
In the second file, how do I use jQuery? I can't include the library in a JS file, can I?
Andrew
@Andrew, include the jQuery library first, and it should work
Stargazer712