Utilize JSON to modify the database

I have successfully implemented a code to edit records in a database, but now I am looking to enhance its functionality by adding the ability to include functions for adding or deleting records as well.

Currently, my form has three separate buttons for Add, Edit, or Delete actions. How can I modify the script to determine which button was clicked?

// Action to run on submit to add/edit/delete record from database
var request; // variable to hold request

// bind to the submit event of our form
$("#form_edit").submit(function(event){
    // abort any pending request
    if (request) {
        request.abort();
    }

    // setup local variables
    var $form = $(this);

    // select and cache all the fields
    var $inputs = $form.find("input, select, textarea");

    // serialize the data in the form
    var serializedData = $form.serialize();

    // disable the inputs for the duration of the ajax request
    $inputs.prop("disabled", true);

    // define constants to be passed as parameters
    var updateType = "edt"; // This needs to be changed to 'add' or 'del'
    var tableName  = "phasecodes";
    var indexName  = "phase_ID";
    var recNumber  = phase_ID.value;

    // Build string for query input
    var type   = "?type="  + updateType;
    var table  = "&table=" + tableName;
    var index  = "&index=" + indexName;
    var rec = "&rec="   + recNumber;
    var getS   = type + table + index + rec;

    // execute request to update database
    request = $.ajax({
        url: "files_json/update_Record.php" + getS,
        type: "post",
        data: serializedData
    });

    // callback handler called on success
    request.done(function (response, textStatus, jqXHR) {
        console.log("Data record updated!"); // log success message to the console
    });

    // callback handler called on failure
    request.fail(function (jqXHR, textStatus, errorThrown) {
        console.error( "The following error occured: " + textStatus, errorThrown ); // log the error to the console
    });

    // callback handler called regardless if the request failed or succeeded
    request.always(function () {
        $inputs.prop("disabled", false); // reenable the inputs
    });

    // prevent default posting of form
    event.preventDefault();
}); // End of submit function

Answer №1

If you have three buttons in a form and want to determine which one was clicked, you can refer to this helpful post

Here's an example of how you can retrieve the value of the button that was clicked:

 var value = $("input[type=submit][clicked=true]").val();

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

Tips for populating an array with information gathered from an axios request within a React application

Currently, I am using axios to fetch data from an API and attempting to store the retrieved data in a variable that represents an array within the state of the component. However, when I try to do so, I encounter the following error: Objects are not valid ...

Encountering Errors with Angular JS Following Update from Version 1.1.0 to 1.1.1

After upgrading, I noticed that the ng-repeat function is taking significantly longer to load and is attempting to display additional content boxes without serving the actual content provided by $resource. I have pinpointed the issue to the update from ve ...

What is the quickest way to increase value in the DOM?

Is there a more efficient method for incrementing a DOM value that you know of? let progress = +document.getElementById("progress").innerHTML; progress++; document.getElementById("progress").innerHTML = progress; Perhaps something like t ...

Working with Multiple Edit Rows Simultaneously in ASP.NET GridView

Is it possible to have multiple rows in edit mode simultaneously in the ASP.NET 4.0 GridView? The editing mode of each row is controlled using a property: Private Property Editing As List(Of Integer) Get If ViewState("Editing") Is Nothing Then ...

Javascript continuously swaps out text from distinct strings in a loop

I wrote a loop to split a string and search for certain text to replace it with another string. Here is an example of what I have done: function replaceStr(str, find, replace) { for (var i = 0; i < find.length; i++) { str = str.replace(new RegE ...

Loading data is taking longer than expected on the View Controller in Swift 2.3

When displaying JSON Response on a View Controller, certain data loads immediately with a key (start date), while other data takes time to load. Here is my code snippet: var record: NSMutableDictionary! var projectID = "" override func viewDidLoad() ...

Error: The connection to Node/Postgresql was refused at 127.0.0.1:5432. This occurred after connecting at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1141:16)

After running a Node server connecting to a Postgresql DB (via Knex) without issues, my laptop crashed. Upon restart, the DB connection stopped working, showing this error message: Error: connect ECONNREFUSED 127.0.0.1:5432 at TCPConnectWrap.afterConnect ...

Bootstrap's pill-tab feature isn't functioning properly

Why is this tab not functioning properly? Do I need to make changes to the jQuery section? The Id and Href appear to be correct, but the tab is not working as expected. $('#v-pills-tab a').on('click', function (e) { e.pr ...

Do you want to reset the validation for the paper input?

I am encountering an issue with a paper-input element in my code. Here is what it looks like: <paper-input id="inputForValidation" required label="this input is manually validated" pattern="[a-zA-Z]*" error-message="letters only!"></paper-input&g ...

How to dynamically add a form to your website

Looking to dynamically insert a form on a page based on the value selected from a datalist, all without having to reload the entire page. <form action='#' method='get'> <input list="category" name="category"> <da ...

Adjust the z-index of the div to control the overflow scrollbar

I am facing an issue with a div that has a horizontal scrollbar and an image (or another div) positioned over the entire page using absolute positioning. The problem is I wish to scroll the div that is beside the image. For anchor links (a), I have set the ...

How to access iFrame in ReactJS using document.getElementById

I am facing a challenge on my website where I need to transfer data (using postMessage) to an iframe. Typically in plain JavaScript, I would use techniques like document.getElementById or $("#iframe") in jQuery to target the iframe. However, I am unsure ...

Unable to retrieve information for PayPal v2 Order generated on client side

My website features a membership option spread across 3 pages, each serving a specific purpose - one for presenting the membership along with a PayPal button, another for member registration into the database, and the last to inform users that they can now ...

What is the process for uploading contentBytes in chunks to a Graph URL generated by the createUploadSession Graph API?

According to Microsoft Graph API documentation, the createUploadSession graph API only provides the URL where attachments can be uploaded. Does anyone know how to upload an attachment chunk by chunk in JavaScript? Thanks in advance. I found this referenc ...

Having Trouble with Imported JavaScript File in Astro

Why isn't the js file working in Astro when I try to import or add a source in the Astro file? For example: <script src="../scripts/local.js"></script> or <script>import '../scripts/local.js'</script> I am ...

Uploading files to a server using Node.js without the need for additional frameworks

I am currently working on a basic file uploading website and I am utilizing the XmlHTTPRequest to handle file uploads. So far, I have dealt with this process only in the context of a server that was already set up for file uploading. Now, however, I need t ...

The SelectedIndexChanged event fails to trigger following an onchange event

I am currently working on validating a dropdown list on the client side based on its selected index/value. My goal is to create a function that triggers an alert when the selected index is 0, or alternatively execute the SelectedIndexChandged method in the ...

Leverage the power of React in tandem with Express

My web site is being created using the Express framework on NodeJS (hosted on Heroku) and I'm utilizing the React framework to build my components. In my project, I have multiple HTML files containing div elements along with React components that can ...

How to use Angular filter to sort through an array and select multiple items based

Looking to implement a filter that, when clicked on a specific name, displays only that name: {'username': 'julio', 'status': 'created'}, {'username': 'julio', 'status': 'running&a ...

Why is it possible to enter the invalid input `1-1` into an `<input type="number">` field in Chrome, but not `1-e`?

When using an <input type="number"> in Chrome, I discovered a peculiar behavior: I can type 11, Then position the cursor between the two 1s, And finally type -. However, when attempting to input the following, it doesn't work: Type ...