0

I am trying to test PHP post data using AJAX. From page test I want to post on to the same page and check if PHP receives post data, if data is posted just to see if redirection is successful, so that I can write authentication code and assign session before page redirects.

When I click on the login button, I just checking isset post data and if data exists then redirect. I am not sure why this is not working. Any help is appreciated.

<script>
    $(document).ready(function(){
        $('#login').click(function(){
            $.ajax({
                type: 'POST',
                url: 'http://domain.com/backend/test',
                data: { username: "John", password: "Boston" }
            });
            return false;
        });
    });
</script>

<?php
if(isset($_POST['username']) && isset($_POST['password'])) {
    redirectto("http://domain.com/backend/test2");
    // redirecto is a function equivalent to header location
}
?>

<form autocomplete="off" class="ui fluid form segment" method="post">
    <div class="ui fluid form segment">
        <div class="two fields">
            <div class="field">
                <label>Email/Username</label>
                <input placeholder="Email/Username" name="username" id="username" type="text">
            </div>
            <div class="field">
                <label>Password</label>
                <input placeholder="Password" name="password" id="password" type="password">
            </div>
        </div>
        <input type="submit" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />
    </div>
</form>
Karthik Malla
  • 5,570
  • 12
  • 46
  • 89

2 Answers2

0

Change

<input type="submit" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />

to

<input type="button" class="ui fluid submit button" name="dosubmit" value="Submit" id="login" />

Even if you triggered the click event of #login button, its a submit type and it will trigger the submit event first. Changing the button type should help.

Ariful Haque
  • 3,662
  • 5
  • 37
  • 59
  • No luck, `return false` will do pretty much the same job. – Karthik Malla Jun 11 '15 at 17:18
  • @lock It might not solve your problem but he's right. There's nothing in your code to [stop the propagation](http://stackoverflow.com/questions/10092580/stop-form-from-submitting-using-jquery) – Machavity Jun 11 '15 at 17:36
0

In the JS, instead of using a click event, use submit. I mean, instead of

$('#login').click(function(){

use

$('#login').submit(function(){

Also, you may add an action property to the form:

<form autocomplete="off" class="ui fluid form segment" method="post" action="#">
Nuno Pereira
  • 480
  • 4
  • 18