2

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

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
  • Can you please post the relevant PHP code too? This is the actual code that should be generating the response to the AJAX request. – Lix Jul 29 '14 at 13:14
  • AJAX requests are asynchronous; the `createRecord` function will have completed *looong* before either of your `return` statements are hit. See the answer I linked to for more information. – Rory McCrossan Jul 29 '14 at 13:16
  • 1
    I have looked into the asynchronous and have gone through the steps However I was still unable to get it to work as I kept getting the same result. –  Jul 29 '14 at 13:20
  • 1
    @RoryMcCrossan OP isn't using the value returned by `createRecord`, so that wouldn't be an issue. The `success` or `error` callback should still get fired, which then in turn calls `showSuccess` or `showError`. However, I'm not seeing `showError` defined here. – Patrick Q Jul 29 '14 at 13:21
  • The success/failure works now after adding the showError.... Now just resetting the variables does not –  Jul 29 '14 at 13:27
  • `$('form#directory-create').find('...').val('')` should be `$('form#directory-create').find('...').each(function(){$(this).val('');});` – Patrick Q Jul 29 '14 at 13:40
  • Patrick, Same thing happens with your suggestion. The form will not reset the variables upon completion. Maybe just refreshing the page will be the best since the alert boxes don't keep stacking up upon theirself –  Jul 29 '14 at 13:45
  • 1
    Maybe post the related HTML? Also, check your browser's Javascript console to see if you're getting any errors. – Patrick Q Jul 29 '14 at 13:47

1 Answers1

0

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;
        }
    });
}
});
tgbrunet
  • 260
  • 3
  • 11