Jump to content

Newbie Help - Form Validation


spacebiscuit

Recommended Posts

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
Link to comment
Share on other sites

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
Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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!

Link to comment
Share on other sites

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
Link to comment
Share on other sites

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?

Link to comment
Share on other sites

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
Link to comment
Share on other sites

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>

Link to comment
Share on other sites

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
Link to comment
Share on other sites

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. ;)

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

  • 4 weeks later...
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.