0

I have successfully implemented the Jquery Validation Plugin http://posabsolute.github.com/jQuery-Validation-Engine/ but i am now trying to get an ajax database email check to work (email exists / email available) and i have written some php script to get this done. Its kinda working but i am getting the most unexpected heretically odd behavior from my IF ELSE statement (seems really crazy to me). observe ### marked comments

PHP code: LOOK AT THE IF ELSE STATEMENT

/* RECEIVE VALUE */
$validateValue = $_REQUEST['fieldValue'];
$validateId = $_REQUEST['fieldId'];


$validateError = "This username is already taken";
$validateSuccess = "This username is available";


/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;

$req = "SELECT Email
  FROM business
  WHERE Email = '$validateValue'";

$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
  $results = array($row['Email']);
}



if (in_array($validateValue, $results)) {

   $arrayToJs[1] = false;
   echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR ### popup shows "validating, please wait" then "This username is already taken" when email typed is in database - i.e. Working
   file_put_contents('output.txt', print_r("1 in array - Email is Taken  " . $validateValue, true)); ### this runs!!

}else{

  $arrayToJs[1] = true; // RETURN TRUE
  echo json_encode($arrayToJs); // RETURN ARRAY WITH success ### popup shows "validating, please wait" when email typed is NOT in the database - i.e. not Working
  file_put_contents('output.txt', print_r("2 else - Email is available  " .   $validateValue, true)); 
  //### THIS RUNS TOO !!!!!!!!!!!!! i.e. echo json_encode($arrayToJs) wont work for both.. If I change (in_array()) to (!in_array()) i get the reverse when email is in database. 
  //i.e. only the else statements echo json_encode($arrayToJs) runs and the popup msg shows up green "This username is available" crazy right??? 
  //so basically IF ELSE statements run as expected (confirmed by output.txt) but only one echo json_encode($arrayToJs) will work.!!!! 
  //If i remove the json_encode($arrayToJs) statements and place it once after the IF ELSE statement i get the same problem.
  //both $arrayToJs[1] = false; and $arrayToJs[1] = true; can work separately depending on which is first run IF or ELSE but they will not work in the one after another;
  }

HERE IS THE REST OF THE CODE-->

1-HTML FORM INPUT CODE:

    <tr>
        <td> <Label>Business Email</Label>
            <br>
            <input type="text" name="Email" id="Email" class="validate[required,custom[email],ajax[ajaxUserCallPhp]] text-input">
        </td>
    </tr>

2-Relevant JQUERY code in jquery.validationEngine.js:

$.ajax({
            type: type,
            url: url,
            cache: false,
            dataType: dataType,
            data: data,
            form: form,
            methods: methods,
            options: options,
            beforeSend: function() {
                return options.onBeforeAjaxFormValidation(form, options);
            },
            error: function(data, transport) {
                methods._ajaxError(data, transport);
            },
            success: function(json) {
                if ((dataType == "json") && (json !== true)) {
                    // getting to this case doesn't necessary means that the form is invalid
                    // the server may return green or closing prompt actions
                    // this flag helps figuring it out
                    var errorInForm=false;
                    for (var i = 0; i < json.length; i++) {
                        var value = json[i];

                        var errorFieldId = value[0];
                        var errorField = $($("#" + errorFieldId)[0]);

                        // make sure we found the element
                        if (errorField.length == 1) {

                            // promptText or selector
                            var msg = value[2];
                            // if the field is valid
                            if (value[1] == true) {

                                if (msg == ""  || !msg){
                                    // if for some reason, status==true and error="", just close the prompt
                                    methods._closePrompt(errorField);
                                } else {
                                    // the field is valid, but we are displaying a green prompt
                                    if (options.allrules[msg]) {
                                        var txt = options.allrules[msg].alertTextOk;
                                        if (txt)
                                            msg = txt;
                                    }
                                    if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true);
                                }
                            } else {
                                // the field is invalid, show the red error prompt
                                errorInForm|=true;
                                if (options.allrules[msg]) {
                                    var txt = options.allrules[msg].alertText;
                                    if (txt)
                                        msg = txt;
                                }
                                if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true);
                            }
                        }
                    }
                    options.onAjaxFormComplete(!errorInForm, form, json, options);
                } else
                    options.onAjaxFormComplete(true, form, json, options);

            }
        });

3-Relevent code for ajaxUserCallPhp in jquery.validationEngine-en.js:

"ajaxUserCallPhp": {
                "url": "validation/php/ajaxValidateFieldUser.php",
                // you may want to pass extra data on the ajax call
                "extraData": "name=eric",
                // if you provide an "alertTextOk", it will show as a green prompt when the field validates
                "alertTextOk": "* This username is available",
                "alertText": "* This user is already taken",
                "alertTextLoad": "*Validating, please wait"
            },

Im sure the problem lies with this echo.

echo json_encode($arrayToJs)

Please help i've spent to long on this and its almost working fully.

To clarify - I basically am trying to code it so that if i type an email in the db it shows red "This username is taken" then if i edit the input box to an email not in the database it changes to green "username is available" at the moment only one json_encode will run in any scenario no matter how i change the if else statement –

Thank you very much in advance.

monoflux
  • 3
  • 1
  • 4
  • Exactly which validation plugin are you using? You've linked to jQuery Validate by Bassistance, and then twice later you refer to the `jquery.validationEngine.js` script. Those are two totally different plugins. – Sparky Mar 13 '13 at 01:32
  • And please use your ["edit" link](http://stackoverflow.com/posts/15374755/edit) to add information to your question; do not use comments for that. – Sparky Mar 13 '13 at 05:11
  • I have made the necessary changes. good spot, The Correct plugin is now shown on the first few lines. – monoflux Mar 13 '13 at 06:25
  • STAHP SHOUTING! WE CAN HEAR YOU! – bjb568 May 10 '14 at 15:56

2 Answers2

0

Ok got it finally after a fiddle. I found that json_encode() returns false when any error or warning is posted. using the php error log file in xampp/php/logs/error_logs file i realised that i was getting an error only when the query result was null making $results = null. this caused an output error preventing json_encode() from echoing true, which is why i only got one response.

To fix it i made sure that the $result array was not empty by using the following code after the query to array part.

if(empty($results)){
   $results [0]= ("obujasdcb8374db");
}

The whole code is now

$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";

$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = $row['Email'];
}

if(empty($results)){
  $results [0]= ("obujasdcb8374db");
}

if (in_array($validateValue, $results)) {
  $arrayToJs[1] = 0;
  echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR


} else {

  $arrayToJs[1] = 1; // RETURN TRUE
  echo json_encode($arrayToJs); // RETURN ARRAY WITH success
  }
monoflux
  • 3
  • 1
  • 4
0

I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js

Find : _ajax:function(field,rules,I,options)

Then scroll down to the ajax request .ie $.ajax

And change url:rule.url to options.ajaxCallPhpUrl

Then all you have to do is include the url as an option like this:

JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){ }) I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js

Find : _ajax:function(field,rules,I,options)

Then scroll down to the ajax request .ie $.ajax

And change url:rule.url to options.ajaxCallPhpUrl

Then all you have to do is include the url as an option like this:

JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){ })

Emeka Mbah
  • 16,745
  • 10
  • 77
  • 96