somdow
somdow

Reputation: 6318

Ajax not submitting to PHP

I'm having an issue where Ajax is not submitting to my PHP processing form. When I submit directly from form to PHP file, it does what it's supposed to and works great but when I try to submit via ajax(i don't want any loading while processing), it always says "Undefined index:" for all my variables etc.

It's a basic form so not sure what I'm doing wrong. Need a different pair of eyes on this. I've tried different posting methods, I've tried adding/removing data type and data etc on the JS. and interestingly enough, I do get the error messages on the PHP fed back to "#formStatusMessage", so it is communicating from back to front, but it's not sending the data from front to back.

I stripped out all inconsequential code for easy reading. Any assistance is greatly appreciated.

Below is my code:

HTML:

<form id="mainUserRegFormActual" method="post" >
            <input type="text" id="uFname" name="uFname" placeholder="first name" value="ozarks">
            <input type="text" id="uLname" name="uLname" placeholder="last name" value="sucks Balls">
            <input type="text" id="uEmail" name="uEmail" placeholder="email" value="[email protected]">
            <input type="submit">
        </form>
    </div>

JS:

$("#mainUserRegFormActual").on("submit", function(evt){
    evt.preventDefault();

    var formProcURL = "proc.php";
    var dataStringForStream = $("#mainUserRegFormActual").serialize();

    $.ajax({
        url : formProcURL,
        type: "POST",
        contentType: "application/json",
        dataType: 'json',
        data: dataStringForStream,
    }).done(function(dataPassResponse){
        $("#formStatusMssgs").text("passed data send --> " + dataPassResponse);
    }).fail(function(dataFailResponse){
        $("#formStatusMssgs").text("failed data send --> " + dataFailResponse.responseText);
    });
});

PHP:

define('DB_NAME', 'testDB');

/** MySQL database username */
define('DB_USER', 'unameHere');

/** MySQL database password */
define('DB_PASSWORD', 'passHere');

/** MySQL hostname */
define('DB_HOST', 'localhost');
$c2d = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die("Failed to connect to database" . mysqli_error($c2d));

// =============================================== ][ user info from form ]
$uFnameClean=mysqli_real_escape_string($c2d, $_POST["uFname"]);
$uLnameClean=mysqli_real_escape_string($c2d, $_POST["uLname"]);
$uEmailClean=mysqli_real_escape_string($c2d, $_POST["uEmail"]);

// =============================================== ][ db query ]
$insertData = "INSERT INTO testDB (first_name, last_name, email_addy) VALUES ('$uFnameClean', '$uLnameClean', '$uEmailClean')";

// =============================================== ][ validation ]
if(empty($uFnameClean) || empty($uLnameClean) || empty($uEmailClean)){
    http_response_code(400);
    $userMessage = "Sorry, there was an error processing your form because you forgot to enter in either your First Name, Last Name, or your Email Address. " ;

    echo $userMessage;
    die();

} elseif(!filter_var($uEmailClean, FILTER_VALIDATE_EMAIL)){
    http_response_code(400);
    $userMessage = "Sorry, there was an error processing your form because the email you entered is incorrect. " ;

    echo $userMessage;
    die();

} elseif(preg_match('#[0-9]#',$uFnameClean) || preg_match('#[0-9]#',$uLnameClean)) {
    echo "Unfortunately there was a problem saving your data. Your name has numbers";
    die();

} else {

    if($c2d){
        if(mysqli_query($c2d, $insertData)){
            http_response_code(200);
            setcookie("userRegistered", true);
            echo "Your data has been saved!";
        }else{
            http_response_code(400);
            echo "Unfortunately there was a problem saving your data. Please try again later";
        }

    }else{
        http_response_code(400);
        echo "no connection";
    }

}

Upvotes: 0

Views: 76

Answers (2)

Justin T.
Justin T.

Reputation: 846

I believe the issue may be with the contentType you are using to send the data. When I use serialize() on the form data you provided, I get the following output:

uFname=ozarks&uLname=sucks%20Balls&uEmail=neverWatchingAgain%40ever.com

This data is not formatted as JSON. If you remove the contentType parameter, your data should send properly.

Upvotes: 2

Musa
Musa

Reputation: 97672

Your content type in your ajax request is wrong, you have it as application/json when it is not.
Remove the content type parameter from the ajax request

$.ajax({
    url : formProcURL,
    type: "POST",
    //dataType: 'json',
    data: dataStringForStream,
}).done(function(dataPassResponse){
    $("#formStatusMssgs").text("passed data send --> " + dataPassResponse);
}).fail(function(dataFailResponse){
    $("#formStatusMssgs").text("failed data send --> " + dataFailResponse.responseText);
});

The default content type for $.ajax is application/x-www-form-urlencoded which is what you get from .serialize() and what is used to populate the $_POST super global


Since you're responding with plain text and not json the dataType: 'json', should be removed as well.

Upvotes: 3

Related Questions