Jake Jake - 10 months ago 145
Ajax Question

PHP GET variable not being set

I have a

registraion
php class that displays a form and when the registration button is clicked, calls a function in a login javascript file. This file uses
ajax
to post data to a index.php file. My
index.php
file cannot access this data, despite the post being a success (ajax success is true as the alert is being called).

Login.js

var loginData, urlPath;

// Allow users to log in or register
function Login() {

loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val();
urlPath = "../index.php?action=register";

// Send the login/registration data to database
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert("success");
}
})
})
}


index.php

<?php

require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");

$model = new Model();
$view = new View();
$controller = new Controller($model, $view);

$controller->Begin();

// Client wants to register
if(isset($_GET['action'])) {
if($_GET['action'] == "register") {
echo '<script type="text/javascript">alert("hello")</script>';
}
}
?>

Answer Source

You used POST method of ajax. So send data also in POST manner like below:-

// Send the login/registration data to database
$(document).ready(function() {
    var username = $("#usernameField").val();
    var email = $("#emailField").val();
    var password = $("#passwordField").val();
    $.ajax({
        type: "POST",
        url: "../index.php",
        data: {"username":username,"email":email,"password":password,"action":"register"},
        success: function (result) { 
            alert(result);//check the change 
        }
    });
});

And then change GET to POST at php end:-

<?php 

    require_once("Model/model.php");
    require_once("Controller/controller.php");
    require_once("View/view.php");

    $model = new Model();
    $view = new View();
    $controller = new Controller($model, $view);

    $controller->Begin();

    // Client wants to register
    //single condition can do the job and use POST instead of GET
    if(isset($_POST['action']) && $_POST['action'] == "register" ) { 
      echo "hello"; //check the change
    }
?>

Note:- Please take care of comments too.(added in the code)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download