2

So, I followed a tutorial here to be able to submit a form with ajax. I followed the tutorial exactly (atleast I thought I did) and when I try to submit the form the page just refreshes and it never gets to the php script to send it to the database.

The script that I am using is below:

$(function () {
$(".button").click(function () {
    $(function () {
        $('.error').hide();
        $("#submit_btn").click(function () {
            //validate and process form here

            $('.error').hide();
            var firstname = $("input#firstname").val();
            if (firstname == "") {
                $("label#firstname_error").show();
                $("input#firstname").focus();
                return false;
            }

            var lastname = $("input#lastname").val();
            if (lastname == "") {
                $("label#lastname_error").show();
                $("input#lastname").focus();
                return false;
            }

            var email = $("input#email").val();
            if (email == "") {
                $("label#email_error").show();
                $("input#email").focus();
                return false;
            }

            var pin = $("input#parent_pin").val();
            if (pin == "") {
                $("label#parent_pin_error").show();
                $("input#parent_pin").focus();
                return false;
            }

            var login = $("input#login").val();
            if (login == "") {
                $("label#login_error").show();
                $("input#login").focus();
                return false;
            }

            var passwd = $("input#passwd").val();
            if (passwd == "") {
                $("label#passwd_error").show();
                $("input#passwd").focus();
                return false;
            }

            var cpasswd = $("input#cpasswd").val();
            if (cpasswd == "") {
                $("label#cpasswd_error").show();
                $("input#cpasswd").focus();
                return false;
            }

            var user_type = $("input#user_type").val();
            if (user_type == "") {
                $("label#user_type_error").show();
                $("input#user_type").focus();
                return false;
            }

            var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login='
            login + '&passwd='
            passwd + 'user_type' = user_type;
            //alert (dataString);return false;
            $.ajax({
                type: "POST",
                url: "studentAccess/files/AddNewUser.php",
                data: dataString,
                success: function () {
                    $('#form-body').html("<div id='message'></div>");
                    $('#message').html("<h2>New User Added Successfully!</h2>");

                }
            });
        });
    });
  });
});

The error that I am receiving in Google Chrome's console is:

Uncaught SyntaxError: Unexpected identifier AddNewUser.js:65

Line 65 would be:

var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login=' login + '&passwd=' passwd + 'user_type' = user_type;

I'm not sure how to fix this problem because I don't know what the error means. Any help would be great!

UPDATE

<?php
$con = mysqli_connect("");
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = "INSERT INTO members (firstname, lastname, email, login, psswd, user_type)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[email]', '$_POST[login]', '$_POST[psswd]', '$_POST[user_type]')";

if (!mysqli_query($con, $sql)) {
    die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>
5
  • '&passwd=' passwd + 'user_ missing + Commented Aug 27, 2013 at 17:08
  • Different problem: you're not properly URL-encoding those components. What if enduser enters spaces/quotes/ampersands/etc in the input values? Plus, this approach is clumsy. Checkout api.jquery.com/serialize and eventually malsup.com/jquery/form + jqueryvalidation.org Commented Aug 27, 2013 at 17:08
  • To stop the page from refreshing (to stop the default button click behavior, you could try modifying your submit button click handler to this: $("#submit_btn").click(function (event) { event.preventDefault(); .... Commented Aug 27, 2013 at 17:13
  • @Jrop -- The script should work just like what it came like from the tutorial... It did in the demo. Commented Aug 27, 2013 at 17:15
  • @user2673735: In the tutorial, at the end of the AJAX there is a return false; statement which is missing in your code. This causes the refresh. You can solve this by either adding the missing line (or) adding event.preventDefault() as mentioned by Jrop and also in my answer. Hope this clarifies. Commented Aug 27, 2013 at 17:19

3 Answers 3

1

You have missed + symbols in the #65 line

Should be

var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login=' + login + '&passwd=' + passwd + '&user_type=' + user_type;

Please read http://en.wikipedia.org/wiki/JavaScript_syntax

Remove $(function () { in .button click handler. Now it just registers a handle on button click but not executes it

Sign up to request clarification or add additional context in comments.

2 Comments

Ok so I fixed that but it still doesn't submit the form without refreshing the page. And it still isn't sending the information to the php script.
So it needs to be just .button.click I don't think so.
1

At the very end of that line you have:

'user_type' = user_type;

It needs to be:

'&user_type=' + user_type;

You may also need to add return false; after your ajax to prevent the page from refreshing (and clearing out your form).

$.ajax({
    type: "POST",
    url: "studentAccess/files/AddNewUser.php",
    data: dataString,
    success: function () {
        $('#form-body').html("<div id='message'></div>");
        $('#message').html("<h2>New User Added Successfully!</h2>");
    }
});
return false; //Keep page from refreshing

Further EDIT:

You also have a .click() embedded in a .click(). You cannot click two buttons at one time. You need to change this:

$(function () {
$(".button").click(function () {
    $(function () {
        $('.error').hide();
        $("#submit_btn").click(function () {

to this...

$(function () {
    $('.error').hide();
    $("#submit_btn").click(function (e) {
        e.preventDefault();
        ...

4 Comments

OK, so I fixed that but the page still just refreshes and the form isn't actually submitted.
Try adding return false; after your ajax and see if that does the trick.
No. Still just refreshes the page after I click submit.
Made another change. You cannot embed .click() functions inside other .click() functions. You can't click two buttons at once.
0

In the below line, it should be '&user_type=' + user_type; instead of 'user_type' = user_type;

var dataString = 'firstname=' + firstname + '&lastname=' + lastname + '&email=' + email + '&parent_pin=' + pin + '&login=' login + '&passwd=' passwd + 'user_type' = user_type;

Also, if the button is a submit button, you should prevent the default form submit action using event.preventDefault(); within the button's click event.

In addition, the first two lines of code is not required. I have commented them out.

/*$(function () {
$(".button").click(function () {*/

    $(function () {
        $('.error').hide();
        $("#submit_btn").click(function (event) { 
            event.preventDefault();
            //rest of your current validation code should be put here.
        });
     });

20 Comments

Will you provide exactly how the event.preventDefault(); should look like in my script.
Ok I am not getting the form to "submit" without page refreshing. But now nothing is showing up in the database. The php script is just fine. So it has to be something within the ajax.
You need to show your php code. How you are connecting to and inserting into the database could be incorrect.
There is your problem: you are not connecting to any database with your $con. You need $con = mysqli_connect("localhost","username","password","my_db"); localhost is your host/IP, username and password are how you login to your database, and my_db is your database name.
First thing I noted, the variable in datastring is passwd whereas the one in the insert statement is psswd. Next, can you add some echo statements to see if (a) the PHP page is called and (b) if it is getting the parameter values correctly. (I have limited experience with PHP/mySQL)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.