OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

WordPress AJAX POST Request Not Working: Page Refreshes Instead of Displaying Result in Modal

  • Thread starter Thread starter iyed ghodhbane
  • Start date Start date
I

iyed ghodhbane

Guest
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.

Code:
//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');
?>
<p>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 <code>functions.php</code> file.</p>
<p>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.</p>
<pre><code>//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');
?>
</code></pre>
Continue reading...
 
Top