views:

60

answers:

3

Hi, 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!" />
<input 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

A: 

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.

Chacha102
ok, found some, but what I don't get is how to I check against the script. e.g., if "1" is returned do this, if "2" is returned do this?
WillyG
i disagree. Play with javascript itself a bit. YOu don't need to be an expert, but at least master the basics before you start masking everything up with a framework like jQuery. AFTER THAT, however, do get jQuery and save yourself a lot of time.
darren
the thing is, I need to use some jQuery to display some fancy error messages (not really fancy, just some slides). Is there a way to use jQuery and plain ole' javascript? I tried and it didn't work out, although I very easily could have done things wrong.
WillyG
In the function I provided, you can do anything in that `function(){}` space. You can call another function, or you can check the content returns (Held in `data`) against various values.
Chacha102
still one little problem, how to I tell jQuery which data to send, where does that come from? I don't think I can do it the same way (inline) because last time it was in a function. It is still just going to the normal "action" page. I've tried many things (I was up till 2:30 last night) and still can't get them to work. Thanks for all previous and any future help!
WillyG
+2  A: 

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 ()

K Prime
Awesome! Thanks so much!!!
WillyG
A: 

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);

    }

}
Jabes88
hmm, I'll look at that. I'm also going to try to rewrite it in jQuery, as that's what my site uses for everything else. Thanks! Although, this code is only for collecting email addresses on a coming soon page, nothing permanent.
WillyG