Matt
Matt

Reputation: 1590

Trying to work with AJAX & PHP

I haven't worked with AJAX much but what I've been attempting to do is have a form where a user enters data, click submit and instead of refreshing the page for the result, a modal window opens with the result. My understanding is that I need to use AJAX for this to work.

The following is my code thus far. Please note that I am only trying to get the AJAX call to work first, I will worry about a modal window later.

At the moment, all that is achieved when hitting the submit button is the page performs the form action and goes to testauthcall.php where my result is echo'd on a blank page (I thought return false; was supposed to kill the page load?).

HTML File: testauth.php

<form id="myForm" action="testauthcall.php" method="post"> 
    Username: <input type="text" name="user" /> 
    Password: <input type="text" name="pass" />
    <input type="submit" value="Test Authentication" /> 
</form>

Javascript File: testauth.php

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 

<script type="text/javascript"> 

var frm = $('#myForm');
frm.submit(function () {
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function (data) {
            alert('ok');
        }
    });
    return false;
});

<script>

PHP File: testauthcall.php

require_once('variables/radius.class.php');

    if ((isset($_POST['user'])) && ('' != trim($_POST['user'])))
    {
        $radius = new Radius('xxx.xxx.xxx.xx', 'xxxxxxxxxx');

        if ($radius->AccessRequest($_POST['user'], $_POST['pass']))
        {
            $authresult = "<strong>Authentication accepted.</strong>";
            echo $authresult;
        }
        else
        {
            $authresult = "<strong>Authentication rejected.</strong>";
            echo $authresult;
        }
    }

Upvotes: 0

Views: 81

Answers (1)

joerx
joerx

Reputation: 2088

So your problem is that the page is reloading even though it should not? I assume you are using jQuery? Try to write your form submit handler like this:

frm.submit(function (e) {
    if (e) {e.preventDefault()};
    //...
});

As far as I remember, returning false only works if you attach handlers the old-fashioned way, in jQuery you have to explicitly suppress the default action of the event triggered by the form submit.

Upvotes: 2

Related Questions