Jump to content

how to save data to mysql from javascript


suryakant2901

Recommended Posts

i have a a script for typing speed test. after 10 sex. script shows some result like

 

Raw CPM: 35  Corrected CPM:  20 WPM:  4Time left: 0

 

Your score: 20 CPM (that is 4 WPM)

In reality, you typed 35 CPM, but you made 3 mistakes (out of 7 words), which were not counted in the corrected CPM score.

Your mistakes were:

 

    * Instead of "language", you typed "dkfre".

    * Instead of "start", you typed "regre".

    * Instead of "been", you typed "rege".

 

i want to store these value to mysql database through php

pease help me how can i do this????

 

here is my html code

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<head>

<title>Typing Speed Test - Online Typing Test - CPM, WPM and percentile</title>

<meta property="fb:admins" content="100000423950474">

<xmeta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">

 

 

 

<script type="text/javascript">

var $iphone = 0;

var $sourcewords =

'the name of very to through and just form in much is great it think you say ' +

'that help he low was line for before on turn are cause with same as mean ' +

'differ his move they right be boy at old one too have does this tell from ' +

'sentence or set had three by want hot air but well some also what play there ' +

'small we end can put out home other read were hand all port your large when ' +

'spell up add use even word land how here said must an big each high she such ' +

'which follow do act their why time ask if men will change way went about light ' +

'many kind then off them need would house write picture like try so us these ' +

'again her animal long point make mother thing world see near him build two self ' +

'has earth look father more head day stand could own go page come should did ' +

'country my found sound answer no school most grow number study who still over ' +

'learn know plant water cover than food call sun first four people thought may ' +

'let down keep side eye been never now last find door any between new city work ' +

'tree part cross take since get hard place start made might live story where saw ' +

'after far back sea little draw only left round late man run year don\'t came ' +

'while show press every close good night me real give life our few under stop ' +

'open ten seem simple together several next vowel white toward children war ' +

'begin lay got against walk pattern example slow ease center paper love often ' +

'person always money music serve those appear both road mark map book science ' +

'letter rule until govern mile pull river cold car notice feet voice care fall ' +

'second power group town carry fine took certain rain fly eat unit room lead ' +

'friend cry began dark idea machine fish note mountain wait north plan once ' +

'figure base star hear box horse noun cut field sure rest watch correct color ' +

'able face pound wood done main beauty enough drive plain stood girl contain ' +

'usual front young teach ready week above final ever gave red green list oh ' +

'though quick feel develop talk sleep bird warm soon free body minute dog strong ' +

'family special direct mind pose behind leave clear song tail measure produce ' +

'state fact product street black inch short lot numeral nothing class course ' +

'wind stay question wheel happen full complete force ship blue area object half ' +

'decide rock surface order deep fire moon south island problem foot piece yet ' +

'told busy knew test pass record farm boat top common whole gold king possible ' +

'size plane heard age best dry hour wonder better laugh true thousand during ago ' +

'hundred ran am check remember game step shape early yes hold hot west miss ' +

'ground brought interest heat reach snow fast bed five bring sing sit listen ' +

'perhaps six fill table east travel weight less language morning among'

;

$sourcewords = $sourcewords.split(' ');

 

 

// The following is public domain. Feel free to use it for your own project.

// I'd like to see what you used it for :)

function i($s) {

    // String interpolation. Just eval the result.

    var $r = "'"

    + $s.replace(/'/g, "\\'").replace(

        /(\$[.\w]+\[\$[.\w]+\]|(\$[.\w]+))/g, "'+$1+'"

        // Default is non-greedy, so "?" won't work.

    ).replace(

        /\$\.(\w)/g, 'this.$1'

        // Perl 6-ish $.foo for object attributes

    ).replace(

        /<\/\./g, "</"

        // Can't have "</" followed by a letter in <script>, so I use "</.foo".

    ) + "'";

    //alert($r);

    return $r;

}

 

function time() {

    // Return the current time as a timestamp in seconds

    return (new Date()).valueOf() / 1000;

}

 

function el($id) {

    return document.getElementById($id);

}

 

// Provide the XMLHttpRequest class for IE 5.x-6.x:

if (typeof XMLHttpRequest == "undefined") XMLHttpRequest = function() {

    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}

    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}

    try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}

    try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}

//    throw new Error( "This browser does not support XMLHttpRequest." )

    return null;

};

 

function thingWithWords($arg) {

 

    // http://www.thefutureoftheweb.com/blog/detect-ie6-in-javascript

    this.exploder  = /*@cc_on!@*/false;

    this.opera    = navigator.userAgent.indexOf("Opera") > -1;

 

    if (this.exploder && navigator.appVersion.match(/MSIE [89]/))

        this.exploder = false;

 

    for ($_ in $arg) this[$_] = $arg[$_];

 

    if (!$arg.words) this.words = new Array('foo', 'bar', 'baz', 'xyzzy');

    if (!$arg.interval) this.interval = 500;

 

    this.current    = 0;            // Index of the current word

    this.iscorrect  = new Array();  // Status of all previous words

    this.starttime  = 0;            // Timestamp of first keypress (ms)

    this.chars      = 0;            // Number of characters typed

    this.goodchars  = 0;            // Number of characters typed and accepted

    this.keypresses = 0;            // Number of keys pressed (released, really)

    this.lastword  = false;        // Stop after_this word

    this.wrongwords = new Array();  // For description of negative $delta

    this.interval_id;              // ID to stop the interval

    this.rawcpm;                    // $chars / $time

    this.cpm;                      // $goodchars / $time

    this.wpm;                      // $cpm / 5

    this.enterused  = false;

 

    this.do_hook = function($hook, $arg1, $arg2, $arg3, $arg4) {

        if (!this[$hook]) return;

        this[$hook].apply(this, new Array($arg1, $arg2, $arg3, $arg4));

    }

 

    this.render = function() {

        this.do_hook('before_render');

 

        var $newhtml = '';

        if (this.current)

            for (var $i = 0; $i < this.current; $i++) {

                var $class = this.iscorrect[$i] ? 'correct' : 'incorrect';

                $newhtml += eval(i(

                    "<span class=$class>$.words[$i]</.span> "

                ));

            }

        $newhtml += eval(i(

            "<span id=currentword>$.words[$.current]</.span> "

        ));

        $newhtml += '<span id=nextwords>'

            + this.words.slice(

                this.current + 1,

                this.words.length

            ).join(' ')

            + '</'+'span>'

 

        var $words_el = el('words');

        $words_el.innerHTML = $newhtml;

 

        if (this.opera) $words_el.scrollTop = 0;

 

        var $scrollbase_el  = el(this.exploder ? 'nextwords' : 'currentword');

        var $scroll = (

            $scrollbase_el.offsetTop - el('currentword').offsetHeight*1.3

        );

 

        if (!this.exploder) $scroll -= $words_el.offsetTop;

 

        if ($scroll < 0) $scroll = 0;

        $words_el.scrollTop = $scroll;

 

        this.do_hook('after_render');

    };

 

    this.calcspeed = function() {

        var $seconds = time() - this.starttime;

        if (!$seconds) return;  // div by zero when timer's bad

        if (!this.current) return;  // div by zero

 

        this.do_hook('before_calcspeed', $seconds);

 

        this.rawcpm = Math.floor(this.chars / $seconds * 10);

        this.cpm    = Math.floor(this.goodchars  / $seconds * 10);

        this.wpm    = Math.round(this.cpm / 5);

 

        this.do_hook('after_calcspeed', $seconds);

    }

 

    this.advance = function() {

        this.do_hook('before_advance');

 

        this.current++;

 

        // this.lastword can be set by another function, but if we're actually

        // at *the last word*, then force it to true.

        if (this.current >= this.words.length) this.lastword = true;

 

        this.calcspeed();

 

        if (this.lastword) {

            clearInterval(this.interval_id);

            el('input').disabled = 1;

            el('wordsbox').innerHTML = this.report ? this.report() : "Done!";

            this.do_hook('after_report');

        } else {

            this.render();

        }

 

        this.do_hook('after_advance');

    }

 

    this.beforgiving = function ($given) {

    }

 

    this.keypress = function ($input_el, $event) {

        var $value = $input_el.value;

        var $length = $value.length;

        this.do_hook('before_keypress', $value);

        if (!$length) return;

 

        this.keypresses++;

 

        var $keycode = $event.which ? $event.which : $event.keyCode;

        if ($keycode == 13) {

            this.enterused = true;

            // Enter pressed. Pretend that spacebar was pressed.

            $input_el.value = $value += " ";

        }

 

        if (!$value.match(/[^ ]/)) {

            // Only whitespace. Remove and ignore.

            $input_el.value = $value.replace(/^ +/, '');

            return;

        }

 

        if (!this.starttime) {

            this.starttime = time();

            var $this = this;  // for closure

            this.interval_id = setInterval(

                this.ticktock // premature optimization? :)

                    ? function () { $this.ticktock(); }

                    : function () { null; },

                this.interval

            );

        }

 

        var $wordandspace = $value.match(/^.+? /);

        if (!$wordandspace) {

            this.do_hook('after_keypress', $value);

            return;

        }

        $wordsandspace = new String($wordandspace);  // coerce

 

        $input_el.value = $value.replace(/^.+? +/, "");

        this.chars += $wordsandspace.length;

 

        var $given    = $wordsandspace.match(/^[^ ]+/);

        var $expected = this.words[this.current];

 

        if ($given == $expected) {

            this.do_hook('on_correct_word', $given);

            this.goodchars += $wordsandspace.length;

            this.iscorrect[this.current] = true;

            this.advance();

        } else if (this.allowwrong) {

            this.do_hook('on_wrong_word', $given, $expected);

            if (!this.strictwrong) {

                // Mitigate damage when someone forgets the spacebar or presses

                // it before_finishing a word

                for (var $delta = -2; $delta <= 3; $delta++) {

                    if ($delta == 0) continue;

                    if ($given != this.words[this.current + $delta]) continue;

 

                    if ($delta > 0) {

                        // a-ha! user skipped $delta words

                        for (var $i = 0; $i < $delta; $i++) {

                            this.do_hook(

                                'on_skipped_word', this.words[this.current]

                            );

                            this.iscorrect[this.current] = false;

                            this.current++;

                        }

                    } else {

                        // extra space in a word: user "skipped -1 or -2 words"

                        if (this.iscorrect[this.current + $delta]) break;

                        var $extra = new Array();

                        for (; $delta < 0; $delta++) {

                            this.current--;

                            $extra.unshift(this.wrongwords[this.current]);

                        }

                        this.do_hook('on_extra_words', $extra);

                    }

                    this.goodchars += $wordsandspace.length;

                    this.iscorrect[this.current] = true;

                }

            }

            this.advance();

        } else {

            // do nothing

        }

        this.do_hook('after_keypress', $value);

    };

 

    this.init = function() {

        this.do_hook('before_init');

        this.render();

        this.do_hook('after_init');

    };

}

 

// Public domain part ends here. Please don't copy the following.

 

var $words = new Array();

 

 

 

for (var $i = 1; $i < 300; $i++)

    $words.push($sourcewords[

        Math.floor(Math.random() * $sourcewords.length)

    ]);

 

var $speedtest = new thingWithWords({  // I have a thing with words ;)

    words: $words,

    allowwrong: true,

    interval: 200

});

 

$speedtest.mistakes  = new Array();  // Descriptions of mistakes

$speedtest.cheater    = false;        // Basic copy/paste detection

 

$speedtest.on_wrong_word = function($given, $expected) {

    this.mistakes.push(eval(i(

        "Instead of \"$expected\", you typed \"$given\"."

    )));

    this.wrongwords[this.current] = $given;

};

 

$speedtest.on_skipped_word = function($word) {

    this.mistakes.pop();

    this.mistakes.push(eval(i("You skipped the word \"$word\".")));

};

 

$speedtest.on_extra_words = function($words) {

    this.mistakes.splice(

        this.mistakes.length - $words.length - 1,

        $words.length + 1

    );

    for ($i in $words) this.mistakes.push(eval(i(

        "You typed an extra word: \"$words[$i]\"."

    )));

};

 

$speedtest.before_advance = function() {

    if (this.lastword) el('timer').innerHTML = '0';

}

 

$speedtest.after_keypress = function($value) {

    if (this.current >= this.words.length) return;

    if ($value.length > 5*this.words[this.current].length ) {

        this.cheater = true;

        alert(eval(i(

            "Er... the word \"$.words[$.current]\" is not $value.length "

            + "characters long ... :). Don't forget to press the space bar "

            + "after each word! (You have to start over now...)"

        )));

        return;

    }

}

 

$speedtest.ticktock = function() {

    var $remaining = Math.ceil(10 - (time() - this.starttime));

    if ($remaining <= 0) {

        clearInterval(this.interval_id);

        $remaining = 'finish word';

        this.lastword  = true;

    }

    el('timer').innerHTML = $remaining;

};

 

$speedtest.after_calcspeed = function ($seconds) {

    if (this.current == 0) return;

    if ($seconds < 3 && !this.lastword) return;

    el('rawcpm').innerHTML = this.rawcpm;

    el('cpm'  ).innerHTML = this.cpm;

    el('wpm'  ).innerHTML = this.wpm;

}

 

$speedtest.report = function () {

    var $report = eval(i(

        "<p id=result>Your score: <big>$.cpm</.big> CPM "

        + "(that is <big>$.wpm</.big> WPM)<div id=pct></div>"

    ));

 

    var $missers    = this.cpm == this.rawcpm ? 0 : 0 + this.mistakes.length;

    var $mistake_s  = ($missers == 1 ? 'mistake' : 'mistakes');

    var $excl        = ($missers == 0 ? '!' : '');

    if (this.cheater) $excl = "*";

 

 

    $tweet = eval(i("I did a typing speed test and scored $.cpm CPM = $.wpm WPM (with $missers $mistake_s$excl) at http://speedtest.aoeu.nl/"));

    $tweet = $tweet.replace(/ /g, "+");  // Unfortunately, they don't appear to understand real URI encoding.

 

    $report += eval(i(

        "<p><a href='#'>" +

        "<img border=0 alt='' width=138 height=55 ></a>"

    ));

 

    if ($missers) {

        var $waswere    = ($missers == 1 ? 'was'    : 'were');

 

        $report += eval(i(

            "<p>In reality, you typed $.rawcpm CPM, but you made $missers "

            + "$mistake_s (out of $.current words), which $waswere not counted "

            + "in the corrected CPM score. <p>Your $mistake_s $waswere:"

        ));

 

        $report += '<ul>';

        for (var $i in this.mistakes)

            $report += '<li>' + this.mistakes[$i];

        $report += '</ul>';

    }

    else

        $report += eval(i(

            "<p>Congratulations! You typed all $.current words correctly!"

        ));

 

    if (this.rawcpm > 300)

        $report += '<p>I advise you to take a 2 minute break now.';

 

    if (this.enterused) {

        $report += '<p>By the way, you used <b>enter</b> instead of the ' +

            '<b>space bar</b>. Try using space next time; this will probably ' +

            'result in a greater overall typing speed.'

    }

 

 

    var $foo = new Image();

    $foo.src = eval(i(

        "/grab.plp?cpm=$.cpm;rawcpm=$.rawcpm;wrong=$missers;words=$.current;"

        + "ip=117.198.3.85;keys=$.keypresses;chars=$.chars;cheater="

        + (this.cheater?"1":"0") + ";iphone=$iphone;enterused="

        + (this.enterused?"1":"0")

    ));

 

 

    return $report;

};

 

$speedtest.after_report = function () {

    if ($http = new XMLHttpRequest()) {

      // $http.open("GET", "pct1.html?cpm=" + this.cpm);

        $http.onreadystatechange = function() {

            if ($http.readyState != 4) return;

            document.getElementById("pct").innerHTML = $http.responseText;

        };

        $http.send(null);

    }

}

 

 

function oninit() {

    $input_el = el('input');

    $input_el.value = "";

    $input_el.focus();

    $speedtest.init();

}

 

</script>

</head>

<body onload="oninit()">

 

<div id=container>

 

<div id=testui>

<div id="header">

<div class="logo"></div>

<div class="title-box">

<h1>Certify Yourself For Typing Skills With Online Examination.</h1>

<p>Find out how fast your fingers are! Saperate Each Word With a Space after Typing. The timer starts automatically when you begin to type, and after one minute you get your score. Good luck!</p>

</div>

</div>

 

 

 

 

<div id=score>

<div class="raw-box">Raw CPM: </div> <div id=rawcpm>?</div>

 

<div class="raw-box">Corrected CPM: </div> <div id=cpm>?</div>

<div class="raw-box">WPM: </div> <div id=wpm>?</div>

 

<div class="raw-box">Time left: </div> <div id=timer>10</div>

 

<div> 

 

</div>

</div>

<div id=wordsbox>

<div id=words onclick="el('input').focus();"></div>

 

<input id=input onkeyup="$speedtest.keypress(this, event);" autocomplete=off>

</div>

</div>

 

</div>

</div>

 

 

</div>

 

</body>

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.