mercredi 29 juin 2016

Too much recursion on ajax request

Here is the code of my register.js page:

$(document).on('pagecreate', '#register', function() {
    $('#submit').click(function() {
        $('.frmFields').removeClass('error');
        var errors = 0;

        var fields = {
            username: $('#username'),
            name: $('#name'),
            email: $('#email'),
            password: $('#password'),
            vPassword: $('#password_verify'),
            dob: $('#dob')
        };

        $.each(fields, function(key, value) {
            if (value.val() == '') {
                value.addClass('error');
                errors++;

                alert('שדה ' + key + ' הינו שדה חובה');
            }

            if (key == 'name') {
                if (!isText(value.val())) {
                    value.addClass('error');
                    errors++;

                    alert('שדה שם חייב להכיל טקסט בלבד');
                }
            }

            if (key == 'email') {
                if (!isEmailAddress(value.val())) {
                    value.addClass('error');
                    errors++;

                    alert('שדה דואר אלקטרוני חייב להכיל כתובת תקנית');
                }
            }
        });

        if (fields.password.val() != fields.vPassword.val()) {
            vPassword.addClass('error');
            errors++;

            alert('הסיסמאות שהקלדת אינן זהות');
        }

        function checkUsername(uname) {
            var valid = false;

            $.ajax({
                url: './actions/checkUsername.php',
                type: 'GET',
                async: false,
                data: {
                    username: fields.username.val()
                },
                success: function(resp) {
                    if (resp == "success")
                        $('#valid').val('true');
                    else
                        $('#valid').val('false');
                }
            });
        }

        checkUsername(fields.username.val());

        if ($('#valid').val() == 'true') {
            $.ajax({
                url: './actions/register.php',
                type: 'POST',
                data: fields,
                success: function(resp) {
                    if (resp == "success") {
                        alert('yay!');
                    } else
                        alert(resp);
                }
            });
        } else
            alert('שם המשתמש שבחרת תפוס');
    });
});

Everything is working fine, the data is being sent correctly, only that I get an error:

too much reccursion

It happens because of the last $.ajax call. I tried it with $.post and it does the same.

How can I do this correctly so I won't get this error?

Aucun commentaire:

Enregistrer un commentaire