开发者

Simple AJAX code not being recognized

I'm trying to begin learning AJAX, and I've already hit a little stump. So I'm starting simple and just trying to get an alert to pop up showing the length of the string the user types into a text field.

The HTML:

<form action="/scripts/addemail_fb.php" method="post">
<input type="text" name="email" value="Enter your email here!" />
<in开发者_JAVA技巧put id="submit" type="submit" name="submit" value="Go!"     onClick="check(this.form.email.value);"/>
</form>

The JS:

function check(email) {


    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
    }


    else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }

    email=encodeURIComponent(email);

    req.open("POST","/scripts/addemail.php");

    req.setRequestHeader(
        'Content-Type',
        'application/x-www-form-urlencoded; charset=UTF-8');

    req.send(email);

    req.onreadystatechange=function() {

        if(req.readyState==4) {

            result = req.responseText;

            alert("The length of the email is:" + result);

        }

    }

    return false;

}

The PHP (addemail.php):

<?php
function check_email($input) {
     return strlen($input);
}
$email = urldecode(implode(file('php://input')));
$result = check_email($email);
echo $result;
?>

And yes, I've included the JS in the section. I got this almost directly from a tutorial so I'm not sure what's going on. My testing browser is Safari, but I've also tried FF. Sorry is this is obvious, as this is my very first AJAX attempt. Thanks!

EDIT: Sorry, the problem is that its just going to the file described in action="addemail_fb" instead of the JS.

-iMaster


Change the onclick handler to onsubmit (on the form), like so:

<form onsubmit="return check(this.email.value);"> ... </form>

Also, set your req.onreadystatechange before calling req.send ()


inline javascript is bad practice. this solution may seem a bit more convoluted but if you implement it into the rest of your scripts then you will find this much more elegant. JS libraries use similar methods, but if you cant use one then do this instead:

onDomReady(function(){

    var oForm = document.getElementById("myform");

    addListener(oForm,"submit",function(){

        removeListener(oForm,"submit",arguments.callee);
        // do stuff here

    });

});

// Cross-browser implementation of element.addEventListener()
function addListener(element, type, expression, bubbling)
{
    bubbling = bubbling || false;

    if(window.addEventListener) { // Standard
        element.addEventListener(type, expression, bubbling);
        return true;
    } else if(window.attachEvent) { // IE
        element.attachEvent('on' + type, expression);
        return true;
    } else return false;
}

// Cross-browser implementation of element.removeEventListener()
function removeListener(element, type, expression, bubbling)
{
    bubbling = bubbling || false;

    if(window.removeEventListener)  { // Standard
        element.removeEventListener(type, expression, bubbling);
        return true;
    } else if(window.detachEvent) { // IE
        element.detachEvent('on' + type, expression);
        return true;
    } else return false;
}

function onDomReady(fn) {

    // Mozilla, Opera and webkit nightlies currently support this event
    if ( document.addEventListener ) {

        // Use the handy event callback
        document.addEventListener( "DOMContentLoaded", function(){

            document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
            fn();


        }, false );

    // If IE event model is used
    } else if ( document.attachEvent ) {

        // ensure firing before onload,
        // maybe late but safe also for iframes
        document.attachEvent("onreadystatechange", function(){
            if ( document.readyState === "complete" ) {
                document.detachEvent( "onreadystatechange", arguments.callee );
                fn();
            } else {    
                setTimeout( arguments.callee, 0 );
                return;
            }
        });

    } else {

        // A fallback to window.onload, that will always work
        addListener(window,"load",fn);

    }

}


Here is the problem:

You are doing it wrong.

And jQuery is the Answer.


But seriously. Try using jQuery, as it will make you Javascript life easier than cutting into a piece of pumpkin pie.

AJAX is one of the most annoying subjects in Javascript, and jQuery, along with other libraries have gone and made the problem much easier to deal with. Plus, there are many many other great features of jQuery that just make it so much more wonderful to work with Javascript.

In jQuery, the entire code would look like:

 $.post("/scripts/addemail.php", {email_address:email}, function(data){
    alert("The length of the email is:"+data);
 });

Speaking of pumpkin pie.....


Now that I've finished my public server announcement for jQuery, you will want to check the Javascript console (Ctrl + Shift + J in Firefox), and run the page. It will give you any errors that you are bound to have such as syntax errors or various other things that go wrong.

If you can go there and then give us any error messages that pop-up, we will be more likely to be able to solve your problem.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜