Using Jquery Ajax to send a POST request with form data and display the server's response

I have an AJAX request to send data to an API and receive a response. I would like to know how to dynamically pass the value from an input field to the body data in the AJAX request.

Here is my form:

<input type="text" name="serial" />
<input type="submit" />

Here is my AJAX request:

$.ajax({ url: "http://www.example.com/api",
 beforeSend: function(xhr)
 { xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password")); }, 
type: 'POST', 
dataType: 'json', 
contentType: 'application/json', 
processData: false, 
data: '{"serial":"252625"}', 
success: function (data) { alert(JSON.stringify(data)); }, 
error: function(){ 
alert("Cannot get data"); } 
});

I am looking for a way to programmatically replace the value in data: '{"serial":"252625"}' with the one entered in the serial input field.

Thank you for any suggestions,

Answer №1

Here is your custom form:

<input type="text" name="serial_number" id="serial_number" />
<input type="submit" id="submit_button" />

Javascript using JQuery:

$(document).ready(function() {
    $('#submit_button').click(function() {
        $.ajax({
            url: "http://www.example.com/api",
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Authorization", "Basic " + btoa("user123:pass456"));
            }, 
            type: 'POST', 
            dataType: 'json', 
            contentType: 'application/json', 
            processData: false,

            data: {
                serial_number: $('#serial_number').val()
            }, 

            success: function (data) {
                alert(JSON.stringify(data));
            }, 
            error: function(error){ 
                alert("Error retrieving data");
                console.log(error);
            } 
        });
    });
});

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

"An error occurred in Pyrebase: The 'orderBy' parameter must be a properly formatted JSON path

I am utilizing Firebase and my JSON data in Firebase looks like this. I aim to extract the key values (288xxx) based on the busStopName values. https://i.sstatic.net/wzzEa.png The code I have written is shown below. Let's use '윤정사앞&apos ...

Incorporating nested JSON data into a ListActivity

Here is a snippet of nested JSON that I am working with: { "status": 1, "data": [ { "iMainServiceId": 1, "main": "NAILS", "sub": [ { "iSubServiceId": 1, "vName": ...

Adjust the stroke and fill colors of an SVG element when hovering over it

I am facing a challenge with an SVG image that I have: https://i.stack.imgur.com/r4XaX.png When hovered over or clicked, it should change to https://i.stack.imgur.com/EHRG2.png Current Icon <svg width="24" height="24" viewBox="0 0 24 24" fill="non ...

Detecting the specific button that was selected with PHP

I am in the process of developing a website for a production company where, upon clicking on a director's name from the menu, all other menu items disappear and only the selected director's biography and work are displayed. My current challenge ...

Issue with Jquery - navigation menu scrolling

I'm struggling to understand why the second gallery isn't scrolling like the first one Check it out here: Here's the jQuery code that's responsible for making it work: $(function(){ var state = 0; var maxState = 7; var winWidth = $(&a ...

Utilizing regular expressions to search through a .md file in JavaScript/TS and returning null

I am currently using fs in JavaScript to read through a changelog.MD file. Here is the code snippet: const readFile = async (fileName: string) => { return promisify(fs.readFile)(filePath, 'utf8'); } Now I am reading my .md file with this fu ...

What could be causing this compatibility issue between IE and Chrome? It's strange that the Table is displaying correctly only in Chrome

Recently, I encountered a challenge with my code in Chrome and realized that it also needs to work in Internet Explorer. Can someone assist me in making it fully functional in IE? I suspect that there might be specific code adjustments needed for IE as th ...

What could be causing the issue of the background color not being applied with SCSS and CSS?

My project utilizes both scss and css. I have two files named styles.css and styles.css, which I imported in my _app.js. import "../styles.scss"; import Head from "next/head"; import React from "react"; import App from "n ...

Managing form submissions using Jquery and checkboxes

Whenever I submit my dynamically created form, all checkboxes briefly become selected for a split second. Does anyone have an explanation for this behavior? Is it common or is there something wrong with my code? Although the form submits correctly, it migh ...

Expanding the capabilities of button properties in MUI

My goal is to customize the MUI5 components by extending their ButtonProps interface and utilizing the component prop. Following the guidelines provided in the documentation, I implemented the solution as shown in the code snippet below: import Button, ...

What is the best approach for determining the most effective method for invoking a handler function in React?

As a newcomer to React, I am navigating through the various ways to define callback functions. // Approach 1 private handleInputChange = (event) => { this.setState({name: event.target.value}); } // Approach 2 private handleInputChange(event){ t ...

The Facebook like button is mysteriously absent on all browsers except Chrome

After embedding the Facebook like button using an iframe code on a website I am working on, I noticed that it only displays correctly on Chrome, while other browsers do not show it. I attempted to use html5 and xfbml methods, but the button still did not ...

Are the new node buffers already populated with information?

Is this a node bug or is it the expected behavior? This issue can be reproduced in versions 0.12.7 and io 3.1.0: > new Buffer(5) <Buffer 00 00 02 00 00> > new Buffer(5) <Buffer 00 00 00 00 00> > new Buffer(5) <Buffer 28 94 00 02 ...

How can I create spacing between squares in an HTML div element?

Currently, I am working on my project using Laravel 5. I retrieve some integer values from a database and use them to create square divs in HTML. Below is the current output of my work. https://i.stack.imgur.com/sy2ru.png You may notice that there is spa ...

JavaScript: Adjust DIV Width Based on Window Height

Is there a way to make the width of a div equal to the height of the window in jquery? I attempted this method: <script type="text/javascript"> $(".rt-container").style.width = $(window).height(); </script> Unfortunately, it did not work. I ...

Guide on programmatically changing the position of a shape in SVG

Check out this tutorial on how to make SVG elements draggable using JQuery and Jquery-svg. The accepted answer provides an implementation for moving a circle by changing the cx and cy attributes. But how can I achieve drag-and-drop functionality for a pol ...

Is there an optimal method for passing an associative array through the map/reduce function in MongoDB?

Below are the functions I have written: map: function () { // initialize KEY // initialize INDEX (0..65536) // initialize VALUE var arr = []; arr[INDEX] = { val: VALUE, count: 1 }; emit(KEY, { arr: arr }); } reduce: function (key, values ...

Modify row attribute in php to change json file name

I am creating a JSON file using PHP and an ODBC connection. The query I have translates well into the JSON file. This is my SQL query: SELECT Date1, Nett FROM database WHERE Date1 BETWEEN '$bdate' AND '$edate' AND String13='$sr& ...

How can I include a custom shader reference in the json material format in three.js?

For those using the JSON Object Scene format 4 for Three.js, there is a specification for materials that can be found here. However, it seems unclear whether it is possible to reference a custom shader from this specification. Does anyone have any insight ...

Angular throws a 404 error when making a JSONP http request

I've been incorporating Mailchimp integration into an Angular application. For using it in pure JS, I retrieved the code from the embedded form on the Mailchimp site: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js ...