0

I have build a simple but working AJAX form using jQuery. The form is validated with jQuery before submit and then after successful submit again with PHP.

The only problem is the error handling. When the PHP-check returned that all fields are ok, I display a success message. If there was an error, I simply display "there was an error".
How can I send back data from PHP to jQuery so invalid fields can be marked as invalid?

Or is such form of error handling unnecessary as the dynamic highlighting needs JavaScript turned on and if JavaScript is turned on, the form can't be submitted wrong?

Basically, my valid checks look like this (simplified of course):

function checkSomething( $something ) {

        $valid = true;

        if ( strlen( $something ) === 0 ) {
            $valid = false;
        }


        return $valid;
} 

At the end of the script, I do it like this:

if ( checkSomething( $something ) && checkThis( $this ) && checkThat( $that ) ) {
    echo "success"; 
} else {
    echo "error";
}

And in my JavaScript/jQuery code it looks like this:

$.ajax({
    url: "form.php",
    type: "POST",
    data: string,
        success: function ( result ) {
            if ( result == "success" ) {
                alert( "success" );                     
            } else {
                alert( "error" );
            }
        }
});
3
  • You need to echo something more back from PHP which tells you what failed, and then handle that response with JS to show whatever message is appropriate. Post some code and show us how you have it's set up now, and it will be easier to help. Commented Feb 15, 2013 at 20:24
  • If you have jQuery validation and JS is enabled, your PHP validation will likely never come into play (it's only there for a precaution). In other words, if your client-side validation is working, then your server-side validation would not have any messages to send back. If your client-side validation is disabled or bypassed, then your server-side validation would take over. If the client's JS is disabled, then you cannot send any message back via jQuery anyway. Show the code too. Commented Feb 15, 2013 at 20:28
  • He should still return a JSON response. In the event it is bypassed, that doesn't mean that Javascript is disabled. Even if it were, it should return JSON response, which will simply display as text in the browser if Javascript is disabled. Commented Feb 15, 2013 at 20:36

3 Answers 3

1

Your form submission has 3 steps: JavaScript Validation & Submission, PHP validation/Processing, and JavaScript on complete ( 'so invalid fields can be marked as invalid')

It sounds like you have step 1 completed and most of step 2.

In your PHP code you should have some data structure, preferably an array, which holds which values are invalid. You can return this data to the browser by echo`ng it to the browser

<?php
...
...
if( count( $invalidFieldArray ) ){
    echo json_encode( array( 'status' => 'Fail',
                             'data' => $invalidFieldArray ) );
}else{
    echo json_encode( 'status' => 'Success' );
}

The code above will return the success/fail to your JavaScript form.

I personal use a jQuery form plugin to handle form submissions, and I recommend you give it a try. It has many nice out of the box features.

$.ajax({
    url: "form.php",
    type: "POST",
    data: string,
    dataType: json,
        success: function ( result ) {
            if ( result.status === "Success" ) {
                alert( "success" );                     
            } elseif (result.status === 'Fail'){
                for (field in result.data) {
                         /* Invalid field handling */
                         ...
                } 
            }
        }
});

Tip : Slightly off-topic, but when using comparisons in JavaScript always use triple equal ( === ), double equal ( == ) is not the same in JavaScript as in other languages; JavaScript does type coercion with double equals, which provides for inconsistent results.

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

1 Comment

Cool, thank you! I believe I finally understood how this works. But still, I get an PHP error Parse error: syntax error, unexpected T_DOUBLE_ARROW - I also tried a : instead of the => without any luck. $invalidFieldArray looks like this: Array ( [name] => Please enter a name. [email] => You need to enter an email address. [message] => Please enter a message. ) Do you have any idea what is happening or is this too complicated now?
1

I think you should have only one service in PHP. You send the data from the form, if there is any invalid data, you might want to return a JSON indicating which fields are wrong, so you can parse and show it. If it went ok, you just simply display that success message.

I'm not sure I get your problem, though.

1 Comment

This is the better of the two suggestions. Return JSON with fields, and the error message for each field you wish to display.
0

You could send the data from PHP and store it in URLs, like this url.com/#value=1

Comments

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.