简体   繁体   中英

Ajax success and error

I am using Ajax to post the results from a php form to a database using an API. However when the script runs, I am not getting anything in return stating that it was a success or an error. I can log into the database and see that it has added the entry but I am not getting an alert when it saves to the database.

What I would like the script to do is:

-First save to the database (Done)

-Second: Alert the user that the operation was completed successfully or error

-Third: reset the values in the form if success, keep values if error

Here is what I have tried and have so far:

$(document).ready(function () {
function showSuccess(message) {
    $('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
}
function showError(message) {
        $('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
    }
$('form#directory-create').on('submit', function (e) {
    //stops the submit action
    e.preventDefault();
    //format the data into javascript object
    var data = $(this).serializeArray();
    //calls function to create record, passing participant information as arguments
    createRecord(data);
});
function resetStudyInfo() {
    //resets all form values to default
    $('form#directory-create').find('input:text, input:radio, input:email, input:phone').val('');
    return true;
}
function createRecord(data) {
    //converts into json data format
    var myData = JSON.stringify(data);
    console.log(myData);

    $.ajax({
        //setup option for .ajax func
        type: "POST",
        url: "directory-create-record.php",
        data: {
            //user_data : contains all the fields and their data
            user_data: myData
        },
        //shows output message on error or success
        success: function () {
            showSuccess('Study created successfully, you may now add participants to this study.');
            var reset = resetStudyInfo();
            return true;
        },
        error: function () {
            showError('Unable to create the study, did you fill out everything?');
            return false;
        }

    });
}
});

PHP side:

 require "RestCallRequest.php";
function insertData($data_from_user){
    $status = 2;
    $url = "xxxx";
    $token = "mytokenishere";
    $fname = $data_from_user[0]->value;
    $lname = $data_from_user[1]->value;
    $title = $data_from_user[2]->value;
    $school = $data_from_user[3]->value;
    $facultystafftrainee = $data_from_user[4]->value;
    $email = $data_from_user[5]->value;
    $phone = $data_from_user[6]->value;
    $record_id = $lname .'_'. $fname;
    # an array containing all the elements that must be submitted to the API
    $data = "record_id,f_name,l_name,title,school,facultystafftrainee,email,phone,directory_complete\r\n";
    $data .= "$record_id,$fname,$lname,$title,$school,$facultystafftrainee,$email,$phone,$status";
    $args = array(
        'content'   => 'record', 
        'type'      => 'flat', 
        'format'    => 'csv', 
        'token'     => $token,
        'data'      => $data
    );
    # create a new API request object
    $request = new RestCallRequest($url, 'POST', $args);
    # initiate the API request
    $request->execute();
    $result = $request->getResponseBody();
    if($result == '1'){
        return 1;      
    }
    }

Any help is greatly appreciated. Thank you

When resetting the form values, you have input:email and input:phone, javascript throws a syntax error as you do not need these values, When you remove them your code should work.... Here is the complete working code

$(document).ready(function () {
    function showSuccess(message) {
        $('#success.success').append('<h3 class="alert alert-success">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
    }
    function showError(message) {
        $('#success.success').append('<h3 class="alert alert-danger">' + message + '</h3>').fadeIn(1000).fadeOut(5000);
    }
    function resetStudyInfo() {
        $('form#directory-create').find('input:text, input:radio').val('');
        return true;
    }

    $('form#directory-create').on('submit', function (e) {
        e.preventDefault();
        var data = $(this).serializeArray();
        createRecord(data);
});
function createRecord(data) {
    var myData = JSON.stringify(data);

    $.ajax({
        type: "POST",
        url: "directory-create-record.php",
        data: {
            user_data: myData
        },
        success: function () {
            showSuccess('Study created successfully, you may now add more participants to this study.');
            var reset = resetStudyInfo();
            return true;
        },
        error: function () {
            showError('Unable to create the study, did you fill out everything?');
            return false;
        }
    });
}
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM