Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Esmobrander Ozpedelamo
Esmobrander Ozpedelamo
9,136 Points

PHP With AJAX Trouble.

Im having problems when submitting a form using PHP with Ajax... when i click the submit button the echo that i have inside:

if($_POST){
}

Wont show... if i remove the e.preventDefault from my script it will work... but i dont want my page to reload every single time somebody sends some form...

Heres all my code:

<div class="mainContainer">

        <img src="images/logo.svg" class="logo">

        <!--  Sign In -->

        <div class="signIn box absoluteCenter">

            <h3 class="medium">Sigin</h3>

            <h2 class="medium">Into your account.</h2>

            <form action="create.php" method="POST" accept-charset="UTF-8" id="create">
                <input type="text" name="name" id="name" placeholder="Full name" value="testing"></input>

                <input type="email" name="email" id="email" placeholder="Email"></input>

                <input type="password" name="password" id="password" placeholder="Password"></input>

                <select name="role" id="role">
                    <option value="Select" disabled selected> Select Position </option>
                    <option value="Teacher"> Teacher </option>
                    <option value="Designer"> Designer </option>
                    <option value="Illustrator"> Illustrator </option>
                    <option value="Developer"> Developer </option>
                </select>

                <input type="submit" name="submit" value="Sign Up"></input>
$user_name=$_POST['name'];

                        $email=$_POST['email'];

                        $password=md5($_POST['password']);

                        $role=$_POST['role'];


                    if($_POST){

                        echo "hello";

                        try {

                                $result = $db->query("INSERT INTO users (name, email, password, role) VALUES ('$user_name','$email','$password','$role') ");

                            } catch (Exception $e) {

                            echo "Data could not be submitted";

                            print_r($e);

                            exit;
                        }

                    }
$(document).on('submit', '#create', function(e) {
            e.preventDefault();
            $.ajax({
                url: $(this).attr('action'),
                type: $(this).attr('method'),
                data: $(this).serialize(),
                success: function(html) {
                    $("<h2 class='success'>Account created successfully.</h2>").insertAfter( " h2.medium " );
                }
            }); 
        });

2 Answers

Benjamin Payne
Benjamin Payne
8,142 Points

Hey Pedro, A couple of things. Try changing type to method in your ajax call, And in the callback function on success change that to response if you want to add to the document a response from your php script, in your case 'Hello`.

Also your jquery selector is not selecting anything. You need a dom element e.g. $('#somediv') and your form / html is not complete. Not sure if you just didn't include everything.

Also, one last thing, you should always have a error callback as well in case the PHP script fails. This essentially tells you that something went wrong. I usually put the response in the console while developing. I included that as well.

Try adding a div with a class of response, and then try the code below and let me know.

$(document).on('submit', '#create', function(e) {
            e.preventDefault();
            $.ajax({
                url: $(this).attr('action'),
                method: $(this).attr('method'),
                data: $(this).serialize(),
                success: function(response) {
                    $(".response").html(response);
                },
                 error: function(response) {
                     console.log(response);
                     $(".response").html(response.responseText);
                 }
            }); 
        });
Esmobrander Ozpedelamo
Esmobrander Ozpedelamo
9,136 Points

Seems legit, thanks, i'll try that as soon as i reach the office tomorrow morning.

Esmobrander Ozpedelamo
Esmobrander Ozpedelamo
9,136 Points

You were right, now it's working just fine. Thanks a lot Best Answer :D

Benjamin Payne
Benjamin Payne
8,142 Points

Glad you got it working man.

Greg Kaleka
Greg Kaleka
39,021 Points

I don't know anything about AJAX, but peeking at the docs, it looks like you might need to add method: "POST", to your AJAX closure.