Passing a javascript variable to a php switch case statement

The javascript parameter "Step" should trigger a switch-case function in php. If Step is one than trigger this piece of code in php and return the output by JSON.

If I take a look in firebug the post string is: Step=one&inputFname=rick&inputLname=bovenkamp I think this is correct. So the problem must be in the php file and I think it's in the $_POST part...

What am I doing wrong? Any help would be very great!

javascript code:

$(document).ready(function() {
    $("form#userForm").submit(function() {
        var inputFname = $('#inputFname').attr('value');
        var inputLname = $('#inputLname').attr('value');
            var Step = "one";
        $.ajax({
            type: "POST",
            url: "main.php",
            data: {Step: Step,inputFname: inputFname,inputLname: inputLname},
            dataType: "json",
            contentType:"application/json; charset=utf-8",
                success: function(data) {
                $("p.succesText").html(data.jsCode);
                    $("form#userForm").hide();
                $("div.success").fadeIn();
            },
            error: function(xhr, status, error) {
                $("form#userForm").hide();
                $("p.errorHead").html("Something went wrong.");
                $("p.errorText").text("ResponseText: " + xhr.responseText
                                        + "Statuscode: " + xhr.status
                                        + "ReadyState: " + xhr.readyState);
                $("div.error").fadeIn();
            }
        });
            return false;
    });
});     

PHP file:

<?php header('content-type: application/json; charset=utf-8');

    $log = array();

    $varStep = htmlspecialchars(trim($_POST["Step"]));  

    switch($varStep) {

        case "one":

        $varFname = htmlspecialchars($_POST["inputFname"]);
        $varLname = htmlspecialchars($_POST["inputLname"]);

        //Make Database connection
        $db = mysql_connect("192.168.178.254","root","852456");
        if(!$db) die("Error connecting to MySQL database.");
        mysql_select_db("Ajax" ,$db);

        //Generate code and check if code already exists in the database
        do
        {
            $varCode = rand(10000, 99999);
            $dbCheckCode = "";
            $dbCheckCode = mysql_query("SELECT * FROM TableAjax WHERE code='$varCode'");
        }
        while (mysql_fetch_array($dbCheckCode) !== false);

        //Save the Form data in the database
        $sql = "INSERT INTO TableAjax (fname, lname, code) VALUES (".PrepSQL($varFname) . ", " .PrepSQL($varLname) . ", " .PrepSQL($varCode) . ")";
        mysql_query($sql);  

        //Return code to frontend
        $log['jsCode'] = $varCode;

        break;
    }

    echo json_encode($log);


    //Clean SQL statement
    function PrepSQL($value)
    {
        if(get_magic_quotes_gpc()) 
        {
            $value = stripslashes($value);
        }
        $value = "'" . mysql_real_escape_string($value) . "'";
        return($value);
    }   

?>

Upvotes: 0

Views: 1917

Answers (1)

marteljn
marteljn

Reputation: 6526

Put Step in quotes data : {"Step" : Step,....

You are passing the value of the variable as the key in that case, that is to say you are actually passing data : {"one" : "one",.... You should do the same with inputLname and inputFname.

Edit - Explanation

If you look at what the contentType options does here at http://api.jquery.com/jQuery.ajax/, you will see that the default is application/x-www-form-urlencoded which is what you want. Essentially what your PHP error was indicating is that the $_POST array was empty because it did not know how to read your data due to the format. You want your return data to be json, the dataType option was all you needed.

You still would have needed to do what I indicated in the first part of the post, but essentially you had two errors that were tripping you up.

I hope this makes sense!

Upvotes: 1

Related Questions