Updating a column in a SQL Table via an Ajax request

I am attempting to store the on or off value from a form into an SQL database by calling a JS function with an AJAX request that sends it to a PHP page for processing. I seem to be facing some issues with my code and could really use some assistance as the API documentation hasn't been very clear. Any help would be greatly appreciated!

Below is the current code snippet:

<?php require('../php/validation.php');?>
<?php require('../php/background.php');?>
<?php
  if(isset($_POST['selectonoff'])){
    $_SESSION['onoff'] = $_POST['selectonoff'];
    $query = 'UPDATE onoff SET onoroff = $_POST["selectonoff"] WHERE ID = 1;';
    $update = mysqli_query($db, $query);
  }
     ?>
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>User Settings Dropdown Menu</title>
      <link rel="stylesheet" href="../css/settings.css">
<script type="text/javascript">
  function load() {
      document.getElementById("selectonoff").value = '<?php echo $_SESSION['onoff'];?>';
}
</script>
<script src="jquery.js"></script>
<script>
  function rel(id)
  {
      jQuery.ajax({
       type: "POST",
       data: 'id='+id,
       url: "../php/update.php",
       cache: false,
       success: function(response)
       {
         alert("Record successfully updated");
       }
     });
 }
</script>
</head>
<body onload="load();">
  <!-- <div id="wrap"> -->
    <br><br><br><br>
    <h1>Admin Settings Menu</h1>
      <form method="post" action="adminconfig.php">
        <p>Toggle BBQ Form</p>
        <select id="selectonoff" name="selectonoff" onchange="this.form.submit(); rel();">
          <option value="NONE">Select</option>
          <option value="ON">Toggle ON</option>
          <option value="OFF">Toggle OFF</option>
        </select>
      </form>
    <form action="../index.php">
    <input type="submit" value="Home" />
    </form>
<script type="text/javascript"=>
</script>
</body>
  <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <script  src="../js/index.js"></script>
</html>

Current PHP Code:

<?php 
    require ('php/server.php');
    $database = mysqli_connect('localhost', 'root', '', 'dedricks');
    if(!$database){
        die("Connection Failed: ".mysqli_connect_error());
    }
    $data = @$_POST['id'] ;
    $sqlQuery = 'UPDATE onoff SET onoroff = $data WHERE ID = 1;';
    mysqli_query($database, $sqlQuery);
?>

Answer №1

Some adjustments are necessary in this code snippet.

ISSUES

  1. The select control value is not being read anywhere in the code, which is required for sending in the ajax call.
  2. The onchange event for the selectonoff list attempts to submit the form and simultaneously calls the rel function without any parameter. It should trigger the ajax request when the selection in selectonoff changes.
  3. Jquery must be included only once either through cdn or local directory.
  4. It should be added before the script tag in the head section.

ACTION ITEMS

Remove this.form.submit(); and rel from onchange. Instead, remove the entire onchange section.

A functional code snippet that submits data to a php page based on your requirements:

<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="UTF-8">
    <title>User Settings Dropdown Menu</title>
    <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <script type="text/javascript">
      function rel(id){

          var formData = {"id": id};
          $.ajax({
           type: "POST",
           data: formData,
           url: "../app/update.php",
           cache: false,
           success: function(response){
               console.log("response", response);
             alert("Record successfully updated");
           },
           error: function(error){
                console.log("error", error);
           }
         });
     }

     $(document).ready(function(){
         $("#selectonoff").change(function(){
             var val = $("#selectonoff option:selected").val();
             rel(val);
         });
     });
    </script>
</head>
<body>
  <!-- <div id="wrap"> -->
    <br><br><br><br>
    <h1>Admin Settings Menu</h1>
    <form method="post" action="adminconfig.php">
        <p>Toggle BBQ Form</p>
        <select id="selectonoff" name="selectonoff">
            <option value="NONE">Select</option>
            <option value="ON">Toggle ON</option>
            <option value="OFF">Toggle OFF</option>
        </select>
    </form>
    <form action="../index.php">
        <input type="submit" value="Home" />
    </form>
</body>

</html>

REMARK I have verified that the provided code functions correctly and sends the ajax request to a php script as intended.

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

Increasing the size of a div container based on the position of the cursor on the

I recently stumbled upon a fantastic website where two images slide left and right based on mouse movement. When the cursor is on the right, the right part of the image expands, and when it's on the left, the left part expands. You can check out the ...

Tips for accessing Ajax data within Ember computed property

I'm facing a challenge with returning data from an Ajax call in a computed property. Despite being aware of the asynchronous nature, I am unable to figure out how to do it due to the specific requirement of returning the data in an array format with o ...

Is it possible to set a different default page index other than 0 in a material table using reactjs?

I have noticed that the default page index in the material table is set to '0', but the API I am currently using begins with a page index of '1'. Is there a way to adjust the default page index of the table to match that of the API? ...

Implementing a feature to automatically set the datepicker value to the selected date upon page initialization

I am working with a datepicker element, identified by id="from_dt", and a button with id="fromToDate". When a date is selected from the datepicker and the button is clicked, the page will load. At that point, I want to transfer the selected date to a textb ...

Executing Java method via JavaScript by simply clicking a button

I am currently facing a challenge in finding a way to invoke a Java method from JavaScript and pass user input variables into the method call. The main issue I have encountered is that JavaScript seems to interpret/resolve the Java method during page load. ...

AngularJS and JQuery: smoothly navigate from current position to specified element

This particular directive I am currently implementing was discovered as the second solution to the inquiry found here - ScrollTo function in AngularJS: .directive('scrollToItem', function($timeout) { ...

Understanding ReactJS's process of batching all DOM updates within a single event loop, ultimately minimizing the number of repaints needed

While perusing an article on DOM updates in ReactJS, I came across the concept of React updating all changes within a single event loop. Having a background in understanding event loops in JavaScript and how they function in core JavaScript, I am curious ...

Video background in webflow not currently randomizing

I want to add a dynamic video background to my website created with Webflow. I attempted to achieve this using Javascript by including the following links: "https://s3.amazonaws.com/webflow-prod-assets/63e4f3713963c5649a7bb382/63f787b42f81b8648e70fed ...

Bring in styles from the API within Angular

My goal is to retrieve styles from an API and dynamically render components based on those styles. import { Component } from '@angular/core'; import { StyleService } from "./style.service"; import { Style } from "./models/style"; @Component({ ...

Guide on accessing data from Infrared sensors sent to a local host via an Arduino with the help of jQuery

Currently, I have a setup where Infrared sensors are connected to an Arduino board. These sensors transmit the value of 1 when no object is detected and 0 when an object is present. To monitor these sensor readings, I have successfully created an HTTP web ...

Assistance with Validating Forms

Hello, I am currently in the process of developing a straightforward registration form that utilizes ajax validation. The form is working as intended for the most part... where an error message displays on the page for each incorrectly filled field. Never ...

Using jQuery to Drag: Creating a draggable effect on a div element

I recently posted a question, but I feel like I need to rephrase it to make it more general. Basically, I have an element that can be moved around and resized using jQuery. I used CSS to attach another div to the right of this element. Initially, when you ...

What causes the discrepancy in results between the quoted printable encoding operation in JavaScript and Oracle?

Programming Languages: // JavaScript code snippet //https://www.npmjs.com/package/utf8 //https://github.com/mathiasbynens/quoted-printable par_comment_qoted = quotedPrintable.encode(utf8.encode('test ąčęė')); console.log('par_comment_qot ...

Chrome's keyup event restricts the use of arrow keys in text fields

Could you please test this on Google Chrome browser: jQuery('#tien_cong').keyup(function(e) { jQuery(this).val(jQuery(this).val().replace(".", ",")); var sum = 0; var tien_cong = jQuery('#tien_cong').val(); tien_cong = tien_ ...

Utilize JavaScript declarations on dynamically added strings during Ajax loading

Is there a way to append HTML strings to the page while ensuring that JavaScript functions and definitions are applied correctly? I have encountered a confusing issue where I have multiple HTML elements that need to be interpreted by JavaScript. Take, for ...

Developing a dynamic web application using the Django framework along with the Vue.js library and Highcharts for

I am currently working on a data visualization web app using Django, Highcharts, and JQuery. I have recently transitioned from JQuery to Vue JS and I am struggling with fetching JSON data from a specific URL. Below is the code snippet: Template <!doc ...

The sidebar vanishes when you move your cursor over the text contained within

My issue is that the side menu keeps closing when I hover over the text inside it. The "About" text functions correctly, but the other three don't seem to work as intended. Despite trying various solutions, I am unable to identify the root cause of th ...

Example of fetching Pubnub history using AngularJS

I am not a paid PubNub user. I am utilizing the example code for an Angular JS basic chat application from PubNub, and I want to access the chat history. This specific example can be found on the PubNub website. git clone https://github.com/stephenlb/an ...

Printing a modified div element that was created using jQuery on an ASP.NET MVC webpage after the initial page has finished loading

In my view, there is a div that holds multiple tables generated based on the model. Each row in these tables contains fields that can be edited using TextBoxFor. Through jQuery, rows can be moved between tables and new tables can be created dynamically wit ...

Send an array of data from the view to the Controller in CodeIgniter

I have been searching for a solution to this question. However, for some reason, my code is not functioning properly. Here is what I want to achieve: Data Array -> ajax post -> codeigniter controller(save data in DB and redirect to another page) ...