0

I need to change a form submit to an ajax post. I am working within codeigniter framework. The current JS code is:

$('#book-appointment-submit').click(function(event) {
    event.preventDefault();

    var formData = jQuery.parseJSON($('input[name="post_data"]').val());
    var postData = {
        'csrfToken': GlobalVariables.csrfToken,
        'id_users_provider': formData['appointment']['id_users_provider'],
        'id_services': formData['appointment']['id_services'],
        'start_datetime': formData['appointment']['start_datetime'],
    };
    if (GlobalVariables.manageMode) {
        postData.exclude_appointment_id = GlobalVariables.appointmentData.id;
    }
    var postUrl = GlobalVariables.baseUrl + '/index.php/appointments/ajax_check_datetime_availability';
    $.post(postUrl, postData, function(response) {
        console.log('Check Date/Time Availability Post Response :', response);
        if (response.exceptions) {
            response.exceptions = GeneralFunctions.parseExceptions(response.exceptions);
            GeneralFunctions.displayMessageBox('Unexpected Issues', 'Unfortunately '
                + 'the check appointment time availability could not be completed. '
                + 'The following issues occurred:');
            $('#message_box').append(GeneralFunctions.exceptionsToHtml(response.exceptions));
            return false;
        } 
        if (response === true) {
            $('#book-appointment-form').submit(); //on submit
        } else {
            GeneralFunctions.displayMessageBox('Appointment Hour Taken', 'Unfortunately '
                + 'the selected appointment hour is not available anymore. Please select '
                + 'another hour.');
            FrontendBook.getAvailableHours($('#select-date').val());
            alert('#select-date');
        }
    }, 'json');
});

THE CONTROLLER

if($this->input->post('submit2')) {       
    $post_waiting = json_decode($_POST['post_waiting'], true);
    $waitinglist = $post_waiting['appointment'];
    $this->load->model('appointments_model');
    $this->appointments_model->waitinglist_to_db($waitinglist);
    $this->load->view('appointments/waiting_success');//return to book view
} else {
    try {
        $post_data = json_decode($_POST['post_data'], true);
        $appointment = $post_data['appointment'];
        $customer = $post_data['customer'];
        if ($this->customers_model->exists($customer)) 
            $customer['id'] = $this->customers_model->find_record_id($customer);
        $customer_id = $this->customers_model->add($customer);
        $appointment['id_users_customer'] = $customer_id; 
        $appointment['id'] = $this->appointments_model->add($appointment);
        $appointment['hash'] = $this->appointments_model->get_value('hash', $appointment['id']);
        $provider = $this->providers_model->get_row($appointment['id_users_provider']);
        $service = $this->services_model->get_row($appointment['id_services']);
        $company_settings = array( 
            'company_name'  => $this->settings_model->get_setting('company_name'),
            'company_link'  => $this->settings_model->get_setting('company_link'),
            'company_email' => $this->settings_model->get_setting('company_email')
        );

The form submits fine with this code but when the form is used in frame the data is lost. To deal with this I need to change the line $('#book-appointment-form').submit(); to be an ajax call instead. I have tried replacing the line using a similar format to the other ajax call above in the JS:

...
if (response === true) {
    var dataUrl = GlobalVariables.baseUrl + '/index.php/appointments/';
    $.post(dataUrl, formData, function(response) {                  
        console.log('Customer Confirms Post Response:', response);
        if (response.exceptions) {
            response.exceptions = GeneralFunctions.parseExceptions(response.exceptions);
            GeneralFunctions.displayMessageBox('Unexpected Issues', 'Unfortunately '
                + 'the check appointment time availability could not be completed. '
                + 'The following issues occurred:');
            $('#message_box').append(GeneralFunctions.exceptionsToHtml(response.exceptions));
            return false;
        }
    }, 'json');
} else {
...

This did not work.

I got a 500 server error.

I do not think I am handling the ajax call correctly within the other ajax call. I assumed I needed to make a function in my controller to receive the call so I added "ajax_customer_confirms" to the url and made a ajax_customer_confirms() function in my controller and that did not work either.

QUESTIONS:

  1. How can I add an ajax call within the ajax call to replace my form submit?
  2. Do I need to handle the ajax call with a function in the controller or can I just replace the .submit() with an ajax call and leave the controller alone?
Antti29
  • 2,953
  • 12
  • 34
  • 36
Craig Tucker
  • 1,051
  • 1
  • 11
  • 27
  • Can you confirm that `formData` is as expected in the second ajax call? I ask because the 500 server error might be due to a missing `csrfToken`. In other words, the instance of `formData` in the first ajax call may not be visible in the second. – DFriend Dec 17 '15 at 19:35
  • On closer examination, do you really want to send `formData` to the second ajax call? Should you be using `postData` instead? That is what holds the `csrfToken`. – DFriend Dec 17 '15 at 19:43
  • Thanks for pointing that out. postData is what I need. I will check that out. – Craig Tucker Dec 17 '15 at 20:03
  • With changing to postData, That gets rid of the 500 error. The console shows `Check Date/Time Availability Post Response : true` and is stuck there. It appears that my second ajax request is just hanging. I am not sure about this line in my second ajax request: `}, 'json');` I am not sure if I am handling this correct within the other ajax request. – Craig Tucker Dec 17 '15 at 21:12
  • The piece of code `}, 'json');` is correct if the server returns json in reply to the ajax call. That seems to be the case. You're certain the second ajax call is made? Is the url for the second call what it needs to be? – DFriend Dec 17 '15 at 22:28
  • Thank you. appointments.php is the controller that `$('#book-appointment-form').submit();` was submitting to. I believe this is correct. And the code above in THE CONTROLLER heading is what I am using now. Do I need to build a function to handle the AJAX call? – Craig Tucker Dec 17 '15 at 23:48
  • I imagine that the controller/method that the submit targeted would be the place to handle the second ajax call. It will need to be provide a reply to the ajax request to satisfy the ajax round-robin. – DFriend Dec 18 '15 at 02:39
  • Ok, that makes since. Thank you so much. So, apparently it is hanging waiting for the reply. – Craig Tucker Dec 18 '15 at 03:04

1 Answers1

0

Each iteration of working on this issue brought up more questions but the final answer was posted here: AJAX submit and 500 server error

Community
  • 1
  • 1
Craig Tucker
  • 1,051
  • 1
  • 11
  • 27