开发者

JSON if value is not undefined, do something

Easy points for someone willing to help a beginner. Using JQuery Form and Validation Plugins to submit a form with PHP and create a MySQL record if certain criteria are met. I'm returning the response as JSON and I want the form to slideUp if server-side validation shows OK, or prepend an error message to the div containing the form and leave the form in place if there are errors. I've gotten valid JSON responses to echo back using:

<?php

$errors = array();
$reqs = array('userName', 'Pwd', 'firstName', 'lastName', 'email', 'cellPhone', 'homePhone', 'role');
foreach($reqs as $req) {
    if((!isset($_POST[$req])) || (empty($_POST[$req]))) {
            $newerr = array('response' => "The field " . $req . " is required.");
            array_merge(array($errors), array($newerr));
            echo json_encode($newerr);
    }
}

if(is_null($errors)) {
    $auser = new User();
    $hshd = sha1($_POST['Pwd']);
    $auser->userName = $_POST['userName'];
    $auser->hshdPwd = $hshd;
    $auser->firstName = $_POST['firstName'];
    $auser->lastName = $_POST['lastName'];
    $auser->email = $_POST['email'];
    $auser->cellPhone = $_POST['cellPhone'];
    $auser->homePhone = $_POST['homePhone'];
    if(!is_null($_POST['school'])) {
    $auser->school开发者_JAVA技巧 = $_POST['school'];
    } else {
        $auser->school = "0";   
    }
    $auser->prelim_role = $_POST['role'];
    $auser->approved = $_POST['approved'];
    if($auser->create()) {
        $abc = array('response'=>"Request successfully submitted. Your account must be configured before you can access the user panel. Please watch for an email confirming your registration and configuration.");
    } else { 
        $abc = array('response'=>"An unknown error occurred. Please send an email to info@aSite.com describing the error event.");
    }
    echo json_encode($abc);
}

?>

And the pertinent portion of the JS:

submitHandler: function(form) {

$("#frmPrntRgstr").ajaxSubmit({
                                                        dataType: 'json',
                                                        success:    processJson,
                                                        })
                            }
});
function processJson(data) { 
        $("#frmPrntRgstr").slideUp("normal", function() {
            $("#frmPrntRgstrRspns").append(data.response).slideDown("normal");
        })
        }
});

But with this setup, both the errors and success messages have a key of 'response' in the JSON Object. The form will slide up whether or not there are errors. I'm thinking of something analogous to if(array_key_exists) in PHP. So if(array_key_exists('errors', $response)) then just prepend, but if(array_key_exists('success', $response)) append and slide up. Only in JSON.

EDIT:

This seems to be working for now. Thanks to Marc B and citizen conn. Please let me know if there are obvious issues or limitations with this structure.

<?php  header("Content-type: application/json"); ?>

<?php

$errors = array();

$reqs = array('userName', 'Pwd', 'firstName', 'lastName', 'email', 'cellPhone', 'homePhone', 'role');
foreach($reqs as $req) {
    if((!isset($_POST[$req])) || (empty($_POST[$req]))) {
            $newerr = array("error" => "The field " . $req . " is required.");
            $errors[] = $newerr;
    }
}

if(!empty($errors)) {
echo json_encode($errors, JSON_FORCE_OBJECT);
} else {
    $auser = new User();
    $hshd = sha1($_POST['Pwd']);
    $auser->userName = $_POST['userName'];
    $auser->hshdPwd = $hshd;
    $auser->firstName = $_POST['firstName'];
    $auser->lastName = $_POST['lastName'];
    $auser->email = $_POST['email'];
    $auser->cellPhone = $_POST['cellPhone'];
    $auser->homePhone = $_POST['homePhone'];
    if(!is_null($_POST['school'])) {
    $auser->school = $_POST['school'];
    } else {
        $auser->school = "0";   
    }
    $auser->prelim_role = $_POST['role'];
    $auser->approved = $_POST['approved'];
    if($auser->create()) {
        $success = array('response'=>"Request successfully submitted. Your account must be configured before you can access the user panel. Please watch for an email confirming your registration and configuration.");
        echo json_encode($success);
    } else { 
        $failure = array('error'=>"An unknown error occurred. Please send an email to info@aSite.com describing the error event.");
        echo json_encode($failure);
    }

}

?>

With the JS callback:

function processJson(data) {
    if(data.response) {
        $("#frmPrntRgstr").slideUp("normal", function() {
            $("#frmPrntRgstrRspns").append(data.response).slideDown("normal");
        })
    } else {
        $("#frmPrntRgstr").prepend(data[0].error);
    }
}
});


If you're expecting JSON you should use $.getJSON

function processJson(data) { 
    if(!data.response.errors){
        $("#frmPrntRgstr").slideUp("normal", function() {
          $("#frmPrntRgstrRspns").append(data.response).slideDown("normal");
        })
    }
});


You might use something like this:

(typeof data.response == "undefined")

If you wish catch the error, use this:

    ("#frmPrntRgstr").ajaxSubmit({
                                                        dataType: 'json',
                                                        success:    processJson,
                                                        error: catchError
                                                        })
                            }
})

function catchError(jqXHR, textStatus, errorThrown){
}
function processJson(data) { 
        $("#frmPrntRgstr").slideUp("normal", function() {
            $("#frmPrntRgstrRspns").append(data.response).slideDown("normal");
        })
        }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜