Updating database through AJAX calls does not work

I'm currently developing a system that requires the ability to remove employees from their Saturday shifts. This process involves clicking on an icon that triggers the JavaScript function "removeEmpFromSaturday" and passes relevant parameters.

Within this script, an Ajax request is made to update values in the database and subsequently remove the employee from their Saturday shift.

However, it seems that the PHP page I have specified is not being called or requested ("As indicated by Alerts on the PHP page").

Since I am still relatively new to AJAX, I acknowledge that my syntax for this particular function may be incorrect. Hence, any extra guidance would be highly appreciated.

Upon checking, when I perform an alert for the values "id, loc, week, year," they all display the expected correct values. Therefore, the issue does not seem to lie there.

The section of code where I suspect the problem exists:

<script>

function removeEmpFromSaturday(id, loc, week, year){

    xhttp = new XMLHttpRequest();
    xhttp.open("GET", "includes/ajax/remove_emp_from_saturday.php?e_id=" + id + 
                      "&location=" + loc + "&week=" + week + "&year=" + year, false);
    xhttp.send();
    resetPlanner();
}

</script>

The PHP script I am referencing:

<?php require_once dirname(__FILE__)."/../admin_header.php"; ?>

<script>alert("STARTED");</script>

<?php

if(isset($_REQUEST['e_id'])){
    $emp_id = escape($_REQUEST['e_id']);
    $loc = escape($_REQUEST['location']);
    $week = escape($_REQUEST['week']);
    $year = escape($_REQUEST['year']);

    $query = "SELECT e_hp_daily_pat FROM employees WHERE e_id = '{$emp_id}'";
    $get_hp_daily_pat_query = mysqli_query($connection, $query);
    $row = mysqli_fetch_assoc($get_hp_daily_pat_query);
    $e_hp_daily_pat = escape($row['e_hp_daily_pat']);

    $query = "SELECT * FROM slots WHERE s_location = '{$loc}' AND s_day = '6' 
        AND s_week = '{$week}' AND s_year = '{$year}'";
    $get_emps_query = mysqli_query($connection, $query);
    $row = mysqli_fetch_assoc($get_emps_query);
    $s_real_sub = escape($row['s_real_sub']);
    $s_emps = escape($row['s_emps']);
    $s_emps = explode(";", $s_emps);
    $process = false;
    $e_match = 0;
    foreach($s_emps as $emp){
        if($emp == $emp_id){
            unset($s_emps[$e_match]);
             $process = true;
          }
        $e_match++;
    }

    if($process == true){
        $s_emps = implode(";", $s_emps);
        $s_real_sub -= $e_hp_daily_pat;
        $query = "UPDATE slots SET s_emps = '{$s_emps}', s_real_sub = '{$s_real_sub}' WHERE s_location = '{$loc}' AND s_day = '6' AND s_week = '{$week} AND s_year = '{$year}'";
        $set_emps_query = mysqli_query($connection, $query);
      }
    }
?>

<script>alert("COMPLETE");</script>

Before addressing it, I am aware that I have not bound my parameters which is somewhat outdated in mysqli. I will make sure to update that at a later stage.

Answer №1

Your update query contains an error:

   $query = "UPDATE slots SET s_emps = '{$s_emps}', s_real_sub = '{$s_real_sub}' WHERE s_location = '{$loc}' AND s_day = '6' AND s_week = '{$week} AND s_year = '{$year}' ";

You're missing a single quote after the s_week.

   $query = "UPDATE slots SET s_emps = '{$s_emps}', s_real_sub = '{$s_real_sub}' WHERE s_location = '{$loc}' AND s_day = '6' AND s_week = '{$week}' AND s_year = '{$year}' ";

For debugging PHP code, it is recommended to avoid using

<script>alert("")</script>
, and instead use echo statements directly within the PHP code.

This approach will ensure that the PHP code is being correctly interpreted and executed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Performing an XMLHttpRequest in the same JSP file using Javascript

I am working on a JSP file that contains three dropdown boxes labeled "countries", "regions", and "cities". My goal is to populate the regions based on the selected country, and the cities based on the selected region. I have managed to achieve this using ...

Remove the initial section of the text and provide the rest of the string

I am a beginner in the world of Javascript and unfortunately I have not been able to find an answer to my current problem. Here is the situation. On a webpage, I am receiving a URL that is sometimes presented in this format: http://url1.come/http://url2.c ...

Discovering a User's Current Game on Discord.js: How Can You Find Out?

Hello, I'm attempting to implement a feature on my gaming server that automatically assigns roles based on the game people are playing. I've searched for a solution, but I seem to be at a standstill. Could someone please point out what mistake I ...

Tips for saving data to a file using the frontend

Is it possible for draw.io to write directly to a local file from my browser without the need for any server app or browser extension? I'm not referring to simply downloading a file, but actually writing to a file. For example, when creating a new dia ...

Is there a way to retrieve the data selected in my modal window when a button is clicked, depending on the v-for value?

As someone who is new to Vue and utilizing Bootstrap modals to showcase product information, I have grid containers that contain a product image, description, and two buttons. One of the buttons, labeled More details >>, is intended to trigger a moda ...

Switching over the database for a session away from using ajax

I am currently working with an XML API that interacts with a database. My website utilizes the functions of this XML API to retrieve data from the database. I am facing a challenge where I need to update the database based on the user's selection on t ...

What is the origin of this MouseEvent attribute?

In my jsfiddle project, there is a white square that can be moved around by the mouse. When the mouse button is released, it displays the x and y coordinates of the square. To see the project in action, visit: http://jsfiddle.net/35z4J/115/ One part of t ...

A guide to resolving the error "Unable to find 'require' in vuejs"

I am currently working on a project using vuejs and firebase. I encountered an issue while trying to import firestore. When I accessed my page, I saw this error message in the console: ReferenceError: require is not defined I attempted to place the import ...

Guide on how to showcase the template by leveraging the roomList information with ngTemplateOutlet in Angular

TS roomList = [{ name: 'Room2' }] HTML <div class="Layout-body"> <ng-container *ngFor="let dt of roomList; index as i" [ngTemplateOutlet]="Room1" [ngTemplateOutletContext]="{ data: dt, i: i }&qu ...

It is my goal to populate the array with numbers while avoiding any duplicate entries

I am currently facing an issue with my code as it is returning a length of 0 instead of the expected result of 5 after excluding duplicates from the array. I have a feeling that there might be something missing in my code, but I just can't seem to fig ...

The v-list-group does not automatically expand sub-groups based on the path specified in the group prop

I have a navigation sidebar that includes nested v-list-groups. Based on the documentation, the "group" prop of v-list-group should expand based on the route namespace. To see more information, visit: https://vuetifyjs.com/en/components/lists/ While this ...

Technical Glitch in Advanced PHP Form Handling

FRESH UPDATE: After using the print_r function on the $_REQUEST, I discovered a peculiar issue with some values not being written to the file even though they are correctly passed by the GET request. It seems that only certain fields are processed, while ...

What is the process for AngularJS to automatically populate the initial tag value in an SVG template?

I'm currently working on an AngularJS directive that needs to update different attributes within an svg tag. angular.module("complexNumbers") .directive("cartesianPlane", function() { return { restrict: "E", scope: { }, templateUrl: " ...

adjust time in jQuery AJAX request when a button is clicked

I have the following code snippet that triggers when a button is clicked. When a user clicks on a button, I want to show a progress bar or waiting image in the browser for 5 seconds. How can I set a timeout and display the progress bar or waiting image wh ...

Is it possible to implement UseState in Server-Side-Rendering scenarios?

Is it possible to utilize useState (and other react hooks?) with Server Side Rendering? I keep encountering the following error when attempting to execute the code: TypeError: Cannot read property 'useState' of null. Oddly enough, if I disable ...

Before the async function, make sure to set the value using React's useState

Exploring the world of react context api for the very first time. Below is my react code utilizing the context api: const [valChanged, setValChanged] = useState(false); async function modalSave() { await setValChanged(true); // STEP 1 await o ...

Adding an item to the collection

When I log my cartProducts within the forEach() loop, it successfully stores all the products. However, if I log my cartProducts outside of the loop, it displays an empty array. var cartProducts = []; const cart = await CartModel .fin ...

In what situations is it beneficial to utilize inherited scope, and when is it best to avoid it

Is it better to use inherited scope (i.e scope:true) when creating a directive, or is it more appropriate not to use it (i.e scope:false)? I grasp the distinction between scope types and their respective functionalities. However, I am uncertain about whic ...

Utilize JavaScript to trigger a div pop-up directly beneath the input field

Here is the input box code: <input type='text' size='2' name='action_qty' onmouseup='showHideChangePopUp()'> Along with the pop-up div code: <div id='div_change_qty' name='div_change_qty&ap ...

JavaScript Accordion malfunctioning

I'm attempting to implement an accordion feature for each row of an HTML table using the script provided below HTML <table class="list" id="table" data-bind="visible: !loading()"> @*<table class="productTable" data-bind="sortTable:true" ...