What is the process of retrieving user input from an HTML form and locating specific data within it?

Here is the structure of my form:

<div  id="employeeinfo" style="padding:40px" class="employee-body">
            <form id="employeeform"  title="" method="post">

            <label class="title">First Name</label>
            <input type="text" id="fname" name="first_name" >

            <label class="title">Last Name</label>
            <input type="text" id="lname" name="last_name" >

            <input type="submit" id="submitButton" onclick="formSubmit()" name="submitButton" value="Submit">

            </form>
        </div>

I am trying to retrieve data from a JSON URL at "app.employee.com/employeedata"

The goal is to extract the first and last names entered in the form above, search for them within the JSON data retrieved from the specified URL, and display the results.

This is what I have accomplished so far:

<script type='text/javascript'>
          function formSubmit(){

            var formData = JSON.stringify($("#employeeform").serializeArray());

            $.ajax({
              type: "POST",
              url: "serverUrl",
              data: formData,
              success: function(){},
              dataType: "json",
              contentType : "application/json"
            });
          }

        </script>

Could someone advise me on how to proceed with this? This is being implemented in Shopify.

Answer №1

To begin, utilize the getElementById function.

function submitForm(){
    ...
    var firstName=document.getElementById("firstName").value; 
    var lastName=document.getElementById("lastName").value; 
 }

Answer №2

give this method a shot

function submitForm(){
 var firstName=$('#fname').val();
 console.log('First Name:',firstName);
 var lastName=$('#lname').val();
 console.log('Last Name:',lastName);
}

Answer №3

The successful function within the XMLHttpRequest request retrieves data from the server:

success

Type: Function( Any data, String statusText, jqXHR obj ) This function is executed when the request is successful. It takes three arguments: The data returned by the server, formatted based on the dataType parameter or dataFilter callback function if specified; a string describing the status; and the jqXHR object. Starting from jQuery 1.5, multiple functions can be added to the success setting in an array format, executing them sequentially. This is considered an Ajax Event.

Source: jQuery.ajax documentation

Here's what you need to do:

<script type='text/javascript'>
  function submitForm(){

    var formData = JSON.stringify($("#employeeform").serializeArray());

    $.ajax({
      type: "POST",
      url: "serverUrl",
      data: formData,
      success: function(responseData){
          // responseData holds the json response from the server. You can retrieve the firstname and lastname fields from this data.
      },
      dataType: "json",
      contentType : "application/json"
    });
  }

</script>

Answer №4

If you use the serializeArray function, it will gather all the form data and return an array like this:

[
  {
    name: "fname",
    value: "zydexo"
  },
  {
    name: "lname",
    value: "test"
  }
]

To access each element value individually in your backend file, you can do the following:

var fname=document.getElementById("fname").value;
or
var fname=$('#fname').val();

Then, you can submit the form using AJAX like this:

function formSubmit(){
        var fname= $("#fname").val();
        var lname= $("#lname").val();

        $.ajax({
          type: "POST",
          url: "serverUrl",
          data: {fname:fname,lname:lname},
          success: function(data){
           //
          },
          dataType: "json",
          contentType : "application/json"
        });
      }

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

Instructions for concealing and revealing a label and its corresponding field before and after making a choice from a dropdown menu

Currently, I am working on developing a form that will enable customers to input their order information. This form includes a selection list for payment methods, with three available options. If the user chooses either credit or debit card as the paymen ...

Unleashing the power of specific dates with the angularJS datepicker directive

I am looking to develop a custom Datepicker directive using Angular JS, with the requirement of allowing only specific dates for selection by the user. For instance, I have a predefined list of numbers such as 1,3,5,7, and my goal is to make these particu ...

Material-UI - Switching thumb styles in a range slider

Looking for a way to style two entities differently on the Material-UI Slider? Entity A as a white circle and Entity B as a red circle? While using data-index can work, there's a flaw when sliding. Is there a better approach? if (data-index === 0) { ...

Looking for guidance on utilizing pushState and handling onpopstate events?

By using ajax, I am able to load specific page content without refreshing the entire page. In order to make the back button functionality work, I utilize pushState and onpopstate as shown below: function get_page(args){ .... $.ajax({ url ...

Unpacking a GZip Stream retrieved from an HTTPClient's Response

I'm attempting to establish a connection to an API that returns GZip encoded JSON from a WCF service (WCF service to WCF service). Utilizing the HTTPClient, I've managed to retrieve the JSON object as a string. However, my goal is to store this d ...

Converting jQuery ajax success response data into a PHP variable: A step-by-step guide

When sending data to a php page for processing using jQuery and ajax, I receive a response in the form of: success: function(data){ mydata = data; } The data retrieved is a URL represented as mydata = https://myurl.com. Now, I want to assign this data to ...

Parsing JSON data in Java may require skipping over certain characters before successfully parsing the data

Currently, my focus is on handling json responses and processing them with a json parser. However, there are some cases where the json response includes a specific format like 'jquery-id99999999({json response})'. When this format is encountere ...

Tips for correctly positioning CSS elements:

I am currently working on a slider using noUi Slider and aiming for an elegant solution. To accommodate the large size of the handle, I expanded the base UI with extra values which are not allowed, causing the handle to jump back to the permitted values. T ...

Go back to the top by clicking on the image

Can you help me with a quick query? Is it feasible to automatically scroll back to the top after clicking on an image that serves as a reference to jQuery content? For instance, if I select an image in the "Portfolio" section of , I would like to be tak ...

What is the best way to have a text field automatically insert a hyphen after specific numbers?

Is there a way to make a text field insert hyphens automatically after certain numbers? For example, when typing a date like 20120212, could we have the input automatically formatted with hyphens after the first 4 digits and the second two, so it displays ...

Avoid including line breaks when using JSON_ENCODE to prevent any issues in the

When attempting to add a new record to my JSON file, I encounter an issue where after encoding the files, there are numerous instances of \ and \n. How can I go about removing these unwanted characters? JSON { "clients": [ { ...

Issue Alert: Inconsistencies with Google Scripts spreadsheets

Objective I have been working on a script that will make consecutive calls to an API (with a JSON response) and input the data into a Spreadsheet. Issue: When I debug the script, everything runs smoothly without any major problems. However, when I try r ...

Encountering an inexplicable "undefined" error in HTML after receiving an

(apologies for any misspelled words) Hey everyone, I hope you're having a great time. This is my first experience with ajax, and I'm trying to incorporate some elements (messages sent and received) into HTML using ajax. However, all I see is an u ...

Is half of your important information disappearing during JSON conversion?

I have a mysql database of countries, containing 250 records that I want to integrate into an Android app. I understand that using PHP is necessary to convert the data into JSON format. Here is my implementation: <?php require_once('connection. ...

What causes the presence of invalid characters in this JSON data?

This is an example of my JSON data: { "Master" : { "Major" : "S", "Minor" : "E", "IPAddress" : "0.0.0.0", "Detail":"<root> <key keyname=\"state\">3</key> <key keyname=\ ...

Create a script that ensures my website can be set as the homepage on any internet browser

I am currently in search of a way to prompt users on my website to set it as their homepage. Upon clicking "Yes," I would like to execute a script that will automatically make my website the user's browser homepage. I have come across a Similar Thread ...

I am hoping to transmit an array from a function using Ajax and JSON

Having trouble sending a JSON array from a function. This is my code: function categoryTree($parent_id = 0, $sub_mark = ''){ global $connection; $query = 'SELECT * FROM ws_categories WHERE parent_id = :parent_id ORDER BY sort_order ...

Creating a universal header for all webpages in Angular JS by dynamically adding elements using JavaScript DOM manipulation techniques

I have successfully created a json File containing an array of "learnobjects", each including an id, name, and link. Check out my plnkr example var myMessage = { "learnobjects": [{ "id": "1", "name": "Animation-Basics", "link": "animation_bas ...

Unveiling the Mystery: Java Tips for Capturing the Chosen Value from a DropdownChoice in Apache W

In my Java class, I created a method where I instantiate a DropDownChoice object for a select menu and add it to the form. Within this method, I am populating the projects list into the billableProjectsList. public class ReportCriteria implements Serializa ...

Conceal the element if the offspring is devoid of content

I want to implement a feature where a div is hidden when its child element is empty. To achieve this, I aim to assign the class .no-content to the div if it contains no elements. Below is my existing code with spaces: <div class="ee-posts-list&quo ...