Trouble with jQuery's get method when using two arguments in the request

When attempting to send both the first name and last name to an API request using jQuery's get method, I encountered an issue. The request works perfectly when only the first name is included, but encounters a problem when adding the last name. The request functions correctly with the URL "http://localhost:5000/name?firstname="+h1;, however it fails when the URL is set to "http://localhost:5000/name?firstname="+h1+"&lastname="+h2;. In this latter case, the desired output briefly appears and then disappears, while the URL changes to "http://localhost:5000/?", with the function being called from "http://localhost:5000/" Here is the JavaScript code:

<script type="text/javascript>
    $(document).ready(function(){
        $("#submitButton").click(function(e){
            var h1 = $("#handle1").val();
            var h2 = $("#handle2").val();
            var u = "http://localhost:5000/name?firstname="+h1+"&lastname="+h2;
            
            alert(u);
            $.get(u, function(data){
                $('.result').html(data);
            })
        });
    });
</script>

And here is my Express API code:

var express = require('express');
var app = express();
var path = require("path");
const PORT = process.env.PORT || 5000

app.listen(PORT, function(){
   console.log('server running on port ' + PORT);
})
app.get('/name', function(req, res){
    res.send("Full Name: "+ req.query.firstname + " " + req.query.lastname);
});

Answer №1

To correctly execute your Ajax request using $.get, ensure that the code snippet provided below is used. If the served content is also accessed through http://localhost:5000/, then there is no need to include the relative URL.

$.get('fullname', {'firstname': h1, 'lastname': h2}).done(function(data) {
    $('.result').html(data);
});

The value specified in $.get represents the route assigned to /fullname

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

When attempting to send data using jQuery to PHP, an issue arises where PHP is unable to receive the information, resulting in an undefined variable

Has anyone successfully sent data from an HTML select to a PHP file using jQuery? I've tried multiple solutions suggested here, but none seem to be working for me. Below is the code I'm using: <select id="city" name="city" > <optgro ...

Using Ajax to fetch and display HTML and PHP pages

After successfully implementing an ajax function to load html pages inside an ajax-container div in my index.php, I am now wondering how I can also call php pages using ajax. Here is the code snippet that I currently have: htaccess rewrite Options +Fol ...

Incorporate selections from a Pop-Up menu into the Table

I'm currently in the process of establishing a timetable. Whenever I click on one of the tables, a popup window emerges with a breakdown of individual subjects. Following my selection from the options provided, the popup should close automatically, an ...

Transforming characters in a string using Javascript

Currently, I am replacing commas in a textbox. However, how do I go about replacing both a "$" and a comma if they appear together in the same line? function doValidate() { var valid = true; document.likeItemSearchForm.sup.value = document.likeItemSearc ...

Is there a way to automatically adjust the size of a textarea when closing a popup modal?

There's a form in my popup modal. Whenever I resize the textarea and then close the modal, upon reopening it, the textarea isn't in its proper form anymore. I'm looking for a way to reset the size of the textarea. Any assistance on this matt ...

Having trouble utilizing the $ selector within a for loop? Avoid attempting to use $("$i") and try an alternative method instead

for (var i = 0; i < 9; i++) { a[i] = val($("#" + i)); alert(a[i]); } UPDATE: The previous code was incorrect as it selected elements with id(#) 'i', which is invalid. Therefore, "#" + i should be used instead. My query was: How c ...

Using Jquery, retrieve items from an object and then proceed to compare them with an Array

var words = [ {word: 'cow', explain: 'animal'}, {word: 'apple', explain: 'fruit'}, {word: 'dog', explain: 'animal'}]; var word2 = ["cow", "dog"]; I am trying to compare the words arra ...

Adjusting the size of Bootstrap alerts while ensuring the close icon remains correctly positioned

Below is the HTML code snippet I am working with: <div class="row mt-2"> <div class="col-lg-5"> <div id="alertmessages"></div> </div> <div class="col-lg-7"> <div class="btn-group-sm"> ...

The panel widens unexpectedly despite the initial coding plan

I am in the process of creating a panel with a specific area where users can resize it by dragging their mouse cursor. However, instead of moving smoothly, the panel unexpectedly jumps in size before becoming resizable. Upon inspecting the element, I noti ...

Executing a JavaScript function within a React web application

Having trouble calling JS functions from ReactJS? I recently encountered an issue when trying to import and call a JS function in a button onClick event in my React project. Specifically, when trying to use this.abtest.events.on in the handleButtonColor fu ...

Why do I continue to encounter this CORS error?

Using react on the front end and laravel for user verification involves the following steps: User clicks on a link in their email with this URL structure http://example.com/verify/?id=$2y$10$uUS8zNE6vpCu.DXd2jJtv..E4sSAA..5XQaw/oHOJaYjnHrCqiUs6 React ex ...

Can the hasClass() function be applied to querySelectorAll() in JavaScript?

As a beginner in javascript and jquery, I recently attempted to manipulate classes using the following code snippet: if ($(".head").hasClass("collapsed")) { $(".fas").addClass("fa-chevron-down"); $(".fas&qu ...

Tips for excluding empty strings from the total length calculation

Issue: My input fields should turn into green buttons once the correct syllables are inserted. However, the problem lies in the fact that it determines correctness based on the length of my JSON data compared to what the user inputs. Even when my array con ...

developing various instances of an object's characteristic

I'm currently attempting to create multiple versions of an object that includes an init function. I've experimented with using the 'new' function in JavaScript, but unfortunately it doesn't seem to work in this scenario as the cons ...

What is the best way to determine if an element retrieved through jQuery matches an element stored in an array?

Currently, I am trying to store elements in an array so that I can later identify which one was clicked on. However, my current method is failing to work as expected. I plan to use the array index for some calculations. The if statement in the code block ...

Show a hidden div element when selecting an option from a dropdown menu

A task at hand requires the creation of a function that will dynamically display certain parts of a form based on user selection. For instance, if 'Pizza' is chosen, then div #section2 containing questions related to pizza should be revealed. Pr ...

When would you recommend setting localStorage in an Angular application?

In my EmployeesComponent, I have a list of employees with buttons for "Education Overview" and "Salary Overview" for each record. Clicking on an overview button takes me to the OverviewComponent, which then loads either the salary or education component. B ...

I'm interested in exploring whether p5.js allows for the creation of a class that can draw sub-classes within itself. One idea I have in mind is to create a 4x4 grid composed of individual

My goal is to create a game similar to Tetris, where the pieces are composed of smaller blocks that share attributes. My current progress includes: export class SquareTetromino { [x: string]: any; constructor(x, y, w, h) { ... } ...

tips on adjusting the page results and maximum results for a dataTable

I have retrieved over 100 rows from MySQL, which is the default limit for displaying results in DataTables. I want to change the default limit of Datatables to display 30 rows on each page until all my fetched MySQL results are shown. When querying M ...

Sending data from a PHP URL to JavaScript and then to another PHP file

After referencing the code from , I am modifying it to send the recorded audio file to a server by including a sessionId in the URL. The PHP page for this purpose is located at . My PHP versions are PHP 5.4 and PHP 5.5.22. For passing variables and data be ...