0

I've created an AJAX function in WordPress to send a POST request and display the result in a modal upon successful completion, without refreshing the page. However, the AJAX code isn't working. When I click the button, the page refreshes instead of showing the result in the modal. I'm writing my code in the functions.php file.

I implemented an AJAX function in WordPress to send a POST request. I expected the result to be displayed in a modal upon successful completion, without refreshing the page.

//add API 
function enqueue_custom_scripts() {
    wp_enqueue_script('jquery');
   wp_enqueue_script('bootstrap-popper', 'https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js', array('jquery'), null, true);
  wp_enqueue_script('bootstrap-js', 'https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js', array('jquery'), null, true);
   
    wp_enqueue_script('custom-ajax', 'https://cdnjs.cloudflare.com/ajax/libs/custom-elements/1.6.0/custom-elements.min.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_custom_scripts');

//function add_enqueue_JS(){
//      wp_enqueue_script('API_SRTB_Voyage', get_stylesheet_directory_uri().'/assets/js/custom.js', array('jquery'));
//}
//add_action('wp_enqueue_scripts', 'add_enqueue_JS');



function display_voyage_form() {
ob_start();

// Fetch data from the API
$ch = curl_init();
 curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:8000/api/post/planificationVoyage');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer mytoken';

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);

$response = json_decode($result, true);


?>
<form id="voyageForms"  method="post" style="width: 80vh; margin-top: -25%;">
    <select name="LIGNE_VOY" class="form-control " id="LIGNE_VOY">
        <option value="">Select Line</option>
        <?php
            if (isset($response['data']) && is_array($response['data'])) {
                foreach ($response['data'] as $model) {
                    echo '<option value="' . $model['TRLI_UID'] . '">' . $model['TRLI_DES_LN3'] . ' </option>';
                }
            }
            ?>
    </select>
    
    <input type="date" class="form-control mt-2" id="DAT_VOY" name="DAT_VOY"  />

    <select name="SENS_VOY" id="SENS_VOY" class="form-control  mt-2" required>
        <option value="A">Aller</option>
        <option value="R">Retour</option>
    </select>

    <button name="SubmitButton" type="submit" class="btn  mt-2" style="width: 30vh; background-color: #f15a2d;">Send Request</button>

</form>

<script>
jQuery(document).ready(function($) {
    $('#voyageForms').on('submit', function(event) {
        event.preventDefault();
        var formData = $(this).serialize();
        console.log(formData);
        $.ajax({
            url: '<?php echo esc_url( admin_url("admin-ajax.php") ); ?>',
            type: 'POST',
            data: {
                action: 'submit_voyage_form',
                form_data: formData
            },
            success: function(response) {
                if (response.success) {
                    var tableBody = $("#tableBody");
                    tableBody.empty();
                    var data = response.data;
                    data.forEach(function(row, index) {
                        tableBody.append("<tr><td>" + row.DISTANCE_KM +
                            "</td><td>" + row.DUREE + "</td><td>" + row.HEURE_DEPART +
                            "</td><td>" + row.ARRIVEE + "</td><td>" + row.DEPART +
                            "</td><td>" + (index + 1) + "</td></tr>");
                    });
                    $("#resultModal").modal("show");
                } else {
                    alert('Error: ' + response.data);
                }
            }
        });
    });
});

</script>






<div class="modal fade" id="resultModal" tabindex="-1" role="dialog" aria-labelledby="modalTitle" aria-hidden="false">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header modal-header-center">
                <h5 class="modal-title text-center " id="modalTitle">بيانات الرحلات</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="modalBody">
                <table class="table">
                    <thead>
                        <tr>
                            <th scope="col text-end">المسافة</th>
                            <th scope="col text-end">مدة الرحلة</th>
                            <th scope="col text-end">وقت المغادرة</th>
                            <th scope="col text-end">الوصول الى</th>
                            <th scope="col text-end">الانطلاق من</th>
                            <th scope="col">#</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                        <!-- Dynamic rows will be inserted here -->
                    </tbody>
                </table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary text-white" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>





<?php

    return ob_get_clean();
}
add_shortcode('voyage_form', 'display_voyage_form');

// Handle form submission via AJAX
function handle_voyage_form_submission() {
    parse_str($_POST['form_data'], $form_data);

    $SENS_VOY = $form_data['SENS_VOY'];
    $DAT_VOY = $form_data['DAT_VOY'];
    $LIGNE_VOY = $form_data['LIGNE_VOY'];

    if (empty($SENS_VOY) || empty($DAT_VOY) || empty($LIGNE_VOY)) {
        wp_send_json_error('Error, you should select all inputs');
    }

    $date = date("d-m-Y", strtotime($DAT_VOY));

    $ch = curl_init();

    $data = [
        'SENS_VOY' => $SENS_VOY,
        'DAT_VOY' => $date,
        'LIGNE_VOY' => $LIGNE_VOY
    ];

    $dataJson = json_encode($data);

    curl_setopt($ch, CURLOPT_URL, 'http://127.0.0.1:8000/api/post/planificationVoyage');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJson);

    $headers = array();
    $headers[] = 'Content-Type: application/json';
    $headers[] = 'Authorization: Bearer mytoken';

    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $result = curl_exec($ch);
    if (curl_errno($ch)) {
        wp_send_json_error('Error:' . curl_error($ch));
    }
    curl_close($ch);

    $response = json_decode($result, true);

    if (isset($response['data'])) {
        wp_send_json_success($response['data']);
    } else {
        wp_send_json_error('No data found');
    }
}
add_action('wp_ajax_submit_voyage_form', 'handle_voyage_form_submission');
add_action('wp_ajax_nopriv_submit_voyage_form', 'handle_voyage_form_submission');
?>
8
  • 1
    This usually indicates that your form simply submitted the "normal" way, because some error in your JavaScript part prevented it from working correctly. Go and check what the browser console has to say - and make sure you have set it to "preserve history", so that loading a new page doesn't remove everything that might have been output there so far.
    – CBroe
    Commented Jun 27 at 8:59
  • Agreed this sounds like a JS/jQuery failure, not PHP. Use the browser's developer tools to debug it
    – ADyson
    Commented Jun 27 at 9:02
  • I checked my console after sending a POST request. There are no errors related to jQuery or AJAX. I verified that I am sending the parameters correctly but the response is an HTML page instead of show a modal with result. Commented Jun 27 at 9:32
  • Could you please check the network tab of the browser and look for the response of the ajax request also please share the screenshot of the same I doubt this may be caused by 127.0.0.1:8000/api/post/planificationVoyage Commented Jun 27 at 10:20
  • 1
    Your HTML form and jQuery code, as provided here, will work and submit the form via AJAX. It will not post back. Demo: jsfiddle.net/y4pvhq6g Try re-building your page starting with just the form and the jQuery submit handler, and adding in other components until that stops happening again. That should give you a clue about what's interfering with it. It's hard to believe there are really no errors at all around the JS code or form submission process - if there were genuinely no problems, the code would work, as I've demonstrated.
    – ADyson
    Commented Jun 27 at 10:27

0

Browse other questions tagged or ask your own question.