Jump to content


Photo

Newbie Help - Form Validation


  • Please log in to reply
16 replies to this topic

#1 spacebiscuit

spacebiscuit

    Newbie

  • New Members
  • Pip
  • 8 posts

Posted 29 October 2012 - 04:26 PM

Hi,

I'm new to ajax and I'm having some issues, I've been hacking away for about 5 hours now and I've hit a deadend so hopefully someone here can help?

What I want to do is perform html form validation (which requires a php script to be called) when a form is submitted, if it evaluates to 'true' print an alert and stop the form from being submitted, if false the form submission can continue.

Here is what I am doing:

<script src="prototype.js"></script>

<script>
function dosubmit() {

$.ajax({ type: 'POST',
url: 'check.php',
success: function(data){
alert("Hello");
}
});

}
</script>


<form method="POST">
<p>
<input type="text" name="name"></p>
<p>
<input type="button" value="Submit" onsubmit="dosubmit()"/></p>
</form>


When I submit my form nothing happens, I get no response. Should I at least not get an alert?

Thank you in advance,

David.

Edited by spacebiscuit, 29 October 2012 - 04:31 PM.


#2 jazzman1

jazzman1

    Advanced Member

  • Gurus
  • 2,450 posts
  • LocationMississauga, Canada

Posted 29 October 2012 - 06:24 PM

The onsubmit event occurs when the submit button in a form is clicked.
It should be here,
<form method="POST" onsubmit="dosubmit()">


#3 spacebiscuit

spacebiscuit

    Newbie

  • New Members
  • Pip
  • 8 posts

Posted 29 October 2012 - 09:19 PM

Ok I have things almost working but have hit another dead end:

<form id="myform" action="index.php" onsubmit="return dosubmit(this)" >
<p><input type="text" name="
captcha_code"></p>
<p><input type="Submit" value="Submit" name="submit"/></p>
</form>

function dosubmit(form) {

var captcha_code=form.captcha_code.value;

$.ajax({
type:'POST',
url:'/includes/check.php',
dataType:'json',
data: 'captcha_code=' + captcha_code,
success:function(result){

if(result==1){
alert("Wrong code input");
return false;
}


else{
return true;

}

}

});


}


So when the form is submitted check.php is executed and the result of the check is returned to 'result', which I then evaluate and the return value should then determine whether the form submission continues or not.

The input is passed successfully to the PHP page and result is successfully passed back to the ajax but the return value doesn't work - no matter what I try. I read something about async but I'm not sure what this is or if it will help.

It's taken me 12 hours to get to this stage and now with the finishing line seemingly in view it looks like I can't achieve what I set out to do?

Any help would be apprecaited.

Thanks!

Edited by spacebiscuit, 29 October 2012 - 09:20 PM.


#4 sumpygump

sumpygump

    Member

  • Members
  • PipPip
  • 14 posts

Posted 29 October 2012 - 09:38 PM

The problem is that dosubmit is making an ajax call and then ending, that is causing the form to be sent (posted) right away. The success function is called later after the ajax request finishes. I think by having the dosubmit function return false (it'll not submit the form), and then have the value of the result from the success function either display the error or else submit the form. You'd probably want to disable the submit button while the ajax call is waiting for a response.

#5 spacebiscuit

spacebiscuit

    Newbie

  • New Members
  • Pip
  • 8 posts

Posted 29 October 2012 - 09:56 PM

Yes that's right, if I set the return to false outside of the ajax request it prevents the form from submitting. So my code is now:

function dosubmit(form) {

var captcha_code=form.captcha_code.value;

$.ajax({
type:'POST',
url:'/includes/check.php',
dataType:'json',
data: 'captcha_code=' + captcha_code,
success:function(result){
if(result==1){
alert(result);
}
else{
{---SUBMIT THE FORM---}
}

}

});

return false;

}

How would I then submit the form based on the value of the the success.

Thanks!

#6 sumpygump

sumpygump

    Member

  • Members
  • PipPip
  • 14 posts

Posted 29 October 2012 - 10:00 PM

You can submit the form like this (using jQuery):
$('#myform').submit();

#7 spacebiscuit

spacebiscuit

    Newbie

  • New Members
  • Pip
  • 8 posts

Posted 29 October 2012 - 10:19 PM

Thanks, I tried that.

Whem I input my captcha it always returns as false. If I remove the call to submit the from though it correctly reports the captha as matched. eg:

if(result==1){
alert("Wrong code input");
}
else{
alert("Correct");
}

The above works correctly but below always evluates as true (wrong code input)

if(result==1){
alert("Wrong code input");
}
else{
$('#myform').submit();
}

Does the above call begin a new instance of the form, if so the captcha code will have changed since the previous check.

Thanks.

Edited by spacebiscuit, 29 October 2012 - 10:21 PM.


#8 sumpygump

sumpygump

    Member

  • Members
  • PipPip
  • 14 posts

Posted 29 October 2012 - 10:29 PM

As long as the page isn't refreshing (form is not submitting) prior to returning from the ajax request then it is the exact same form. I am not sure what check.php is returning. Can you verify the output of result for a correct and incorrect captcha response? Is there something else in the form that needs to be sent to check.php so it knows which captcha to validate?

#9 spacebiscuit

spacebiscuit

    Newbie

  • New Members
  • Pip
  • 8 posts

Posted 29 October 2012 - 10:41 PM

I have verified the output of 'result' - it works correctly for matched and mis-matched captcha inputs.

check.php simply returns a 1 or a 0.

Would this approach not send the code into an infinite loop? Take a look ay form code:

<form id="myform" enctype="multipart/form-data" action="<? echo $_SERVER['PHP_SELF']; ?>" method="POST" onsubmit="return dosubmit(this)" >

It looks to me as if dosubmit() will be called again, it should match the captcha and then call the form again, and so on?

Or am I mis-understanding something.

Another approach I thought might work was to have the user submit via onclick but have the jquery call the form by submit and thus have two different methods used to submit the form but I can't get the form action to work this way.

Edited by spacebiscuit, 29 October 2012 - 10:44 PM.


#10 spacebiscuit

spacebiscuit

    Newbie

  • New Members
  • Pip
  • 8 posts

Posted 29 October 2012 - 11:20 PM

Ok I got it working but had to use both the onsubmit and onclick event handlers. I've got to get some sleep now but I will report my findings tomorrow.

Thanks for your help!

David.

#11 sumpygump

sumpygump

    Member

  • Members
  • PipPip
  • 14 posts

Posted 29 October 2012 - 11:31 PM

You're right about the infinite loop problem. Sorry!

So here is a working example.
Note the following changes:
- submit button name renamed to 'submit_button'. This is because naming it 'submit' overrides the forms default submit function.
- I changed the code to not use the onsubmit html attribute and instead favor injecting the javascript with jQuery into the form.
- form is set to 'this' and that means that it becomes the form DOM element.
- When we submit the form after checking the ajax request we are using the browser native form submit() function which doesn't trigger it to use onsubmit which eliminates the infinite loop.

<form id="myform" action="index.php">
    <p><input type="text" name="captcha_code"></p>
    <p><input type="Submit" value="Submit" name="submit_button"/></p>
</form>
<script type="text/javascript">
$(function() {
    $('#myform').submit(function(event) {
        // Prevents form from doing it's default submission, so we can control 
        // when it happens.
        event.preventDefault();

        var form = this;
        var captcha_code = form.captcha_code.value;


        $.ajax({
            type:'POST',
            url:'/includes/check.php',
            dataType:'json',
            data: 'captcha_code=' + captcha_code,
            success:function(result){ 
                if (result==1) {
                   alert("Wrong code input");
                   return false;
                } else {
                    form.submit();
                    return true;
                }
            }
        }); 
    });
});
</script>


#12 Christian F.

Christian F.

    Advanced Member

  • Staff Alumni
  • 3,106 posts
  • LocationNorway

Posted 30 October 2012 - 04:39 AM

Spacebiscuit: Please use the [code][/code] tags around your code, as it helps make both your post and your code a lot easier to read. Thanks.
Keeping it simple.

#13 spacebiscuit

spacebiscuit

    Newbie

  • New Members
  • Pip
  • 8 posts

Posted 30 October 2012 - 09:06 AM

Thanks that works perfectly.

As I said. I did manage to get it working last night by changing the submit to a button and using a onclick event handler. The ajax request then called the form submit directly which had no form validation and so the captcha check was by-passed. It worked but I knew it wasn't very elegant and I wasn't 100% happy with it.

Your solution works perfectly though, however I think it is important that I understand exactly how it works and what is happening otherwise I've learned very little.

I can't quite see what is calling the function in the code provided. In my previous attempt I was using onclick or onsubmit to call the function. I can see that the code begins with:

$(function() {

What does this do?

$('#myform').submit(function(event) {

I guess that this is catching the form submit/click?

The rest makes sense.

Apologies for not using the code tags. I was looking for them yesterday but I was tired andmissed them.

Thanks!

Edited by spacebiscuit, 30 October 2012 - 09:08 AM.


#14 Christian F.

Christian F.

    Advanced Member

  • Staff Alumni
  • 3,106 posts
  • LocationNorway

Posted 30 October 2012 - 09:10 AM

You're right in your guess. That line of code traps the submit event of the element with the ID "myform", and then runs the anonymous function when the event happens.
It's basically the same as creating a named function, and then using it in the "onsubmit" handler of the form tag. Just a bit cleaner way of doing it, since you're keeping all of the JS functionality in JS. ;)
Keeping it simple.

#15 Jessica

Jessica

    This is not my name.

  • Gurus
  • 8,982 posts
  • LocationDallas, TX
  • Age:26

Posted 30 October 2012 - 09:11 AM

What does this do?

$('#myform').submit(function(event) {

When the element with the ID of myform triggers the submit event, capture the event and pass it to this anonymous function defined here.
My goal in replying to posts is to help you become a better programmer, including learning how to debug your own code and research problems. For that reason, rather than posting the solution, I reply with tips and hints on how to find the solution yourself. See below for useful links when you get stuck.

How to Get Good Help: How to Ask Questions | Don't be a help vampire
Debugging Your Code: Debugging your SQL | What does a php function do? | What does a term mean? | Don't see any errors?
Things You Should Do: Normalize Your Data | use print_r() or var_dump()
Lulz: "Functions should not have side effects." - trq

Please take a look at my new PHP/Web Dev blog: The Web Mason - Thanks!!

#16 spacebiscuit

spacebiscuit

    Newbie

  • New Members
  • Pip
  • 8 posts

Posted 31 October 2012 - 11:47 AM

So what about this line:
$(function() {

This is an anonamous function right? Would it be possible to name it.

Why does it open with

$(

The dollar sign would suggest to me that a variable name should follow.

I want to purchase a book to help me better get to grips with this, I was looking at one of the Dummies series. Should I be looking at JQuery or Ajax - what is the difference as I'm not clear on this. If anyone knows of any good books please let me know.

Thanks,

David.

#17 txmedic03

txmedic03

    Advanced Member

  • Members
  • PipPipPip
  • 313 posts
  • LocationCall, TX, USA

Posted 23 November 2012 - 04:36 PM

Someone who actually wants to learn and not just have the answers spoon fed and/or the code completely written for them. :o Seriously? They really do exist?!? I feel like I just found a leprechaun.

SEMPER FIDELIS!

I can't stop you from doing something silly, but at least I can help you do it right.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

Cheap Linux VPS from $5
SSD Storage, 30 day Guarantee
1 TB of BW, 100% Network Uptime

AlphaBit.com