Is there a way to retrieve request parameters in a JavaScript file using AJAX?

When I send an ajax request to the js file as shown below:

 function add(lt,ln)

{

    $.ajax({

          type: 'get',
            url: "js/abc.js",
            data: {action: "addme", lt: lt,ln:ln},
            async: false,
            success: function(data){

            }
            });



}

The question now is, how can I access the 'lt' and 'ln' variables in the abc.js file when this request is sent?

if(action==addme)
{
var lt=set value which is coming from ajax request.
}

Answer №1

It's not possible to achieve this in a JavaScript file

When you send an Ajax GET request, the URL will change to

./js/abc.js?action=action&lt=lt
. This means that you are passing parameters to a JavaScript file, which won't automatically execute or change due to the '.js' extension, unless the server configuration is modified.

Another solution is: to modify the file extension to .php or .html or any other format (JavaScript code within a PHP file)

For example:

function add(lt,ln)
{
    $.ajax({
          type: 'get',
          url: "js/abc.php",
          data: {action: "addme", lt: lt,ln:ln},
          async: false,
          success: function(data){
           ///Do something with 'data'
           ///'data': var lt=lt; alert(lt);
            }
            });
}

js/abc.php:

<?php
   $action = $_GET["action"];
   if($action=="addme"){ //check if action=addme
      echo "var lt=".$_GET["lt"].";"; //Adding variable coming from Ajax request
    ?>
 alert(lt);

Take the time to understand the code. Hopefully, it will be beneficial for you

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

The color of the background does not remain changed permanently

I'm having an issue where the background color changes when I click a button, but reverts back almost immediately to its original color. How can I ensure that the new color stays permanently? Here is a simple JavaScript function you can use: functio ...

Showing ng-attributes in haml partials in Rails using jQuery ajax and $q

As I work on developing an Angular Frontend for an existing Rails Application, I have come across the challenge of integrating $q in my current setup. While I understand that transitioning to a REST API served directly to ngResource would be ideal, the com ...

Incorporate Monaco Editor into an AngularJS 1.X project

Due to the challenges presented in this particular issue, I am seeking an alternative JavaScript-based source code editor compatible with AngularJS 1.X. My current exploration has led me to consider utilizing Monaco Editor. While I have successfully execu ...

In search of a highly efficient webservices tutorial that provides comprehensive instructions, yielding successful outcomes

I've reached a point of extreme frustration where I just want to break things, metaphorically speaking, of course. For the past week, I've been trying to learn how to create a web service using C# (whether it's WCF or ASMX, I don't rea ...

Looking for an angular split pane library that is built exclusively for AngularJS without any reliance on other frameworks?

Is there a split-pane library available that can enable me to display 2 tables on a screen and allow users to drag the divider in the middle to adjust the sizes of each table? I have come across libraries such as the shagstrom one that offer this function ...

Styling multiple Higher Order Components (HoCs) using Material UI withStyles

When developing my application, I encountered an issue with using Higher Order Components (HoCs) and withStyles for styling. If I apply multiple HoCs to one component, the classes prop of the first HoC gets passed to the next one in the compose chain, caus ...

sending a JSON string from the Visual Basic.NET side to the ASP.NET server

Struggling with transferring a JSON string to my asp.net using jQuery? Unclear about web methods, arrays, or functions and need assistance parsing the JSON string? Here is an example of how you can achieve this using VB.NET: Protected Sub Page_Load(ByVal ...

Creating, editing, and deleting data in Ng2 smart table is a seamless process that can greatly enhance

While working on my Angular 2 project, I utilized [ng2 smart table]. My goal was to send an API request using the http.post() method. However, upon clicking the button to confirm the data, I encountered the following error in the console: ERROR TypeErro ...

What are some best practices for preventing unforeseen rendering issues when utilizing React Context?

I am encountering an issue with my functional components under the provider. In the scenario where I increase counter1 in SubApp1, SubApp2 also re-renders unnecessarily. Similarly, when I increase counter2 in SubApp2, SubApp1 also gets rendered even thou ...

jQuery does not cache Ajax requests by default

I have implemented the following code to make an AJAX request. I am trying to determine if the requests are being cached by using the Chrome developer tools. However, when I check the request tab, I notice that all data is always being pulled from the serv ...

The View Component is experiencing issues with loading the CSS and JS files correctly when an AJAX call is made

Hey there! I'm having trouble loading a view component via ajax when the button is clicked. It seems like the css and javascript are not working properly. Check out the ajax call for the controller to load the component: $.ajax({ url: window.locat ...

Unique title: "Personalized on-click.prevent feature"

I'm having trouble coming up with a name for this concept, so I don't know what specific term to search for. I've checked out some directives, but I'm not convinced that's what I need. Essentially, I want to be able to do the follo ...

Is there a way to make a try-catch block pause and wait for a response before moving

I've been successfully retrieving data from my Firestore database, but I've encountered a major issue that I can't seem to resolve... Whenever I click the "Read Data" button, I have to press it twice in order to see the console log of the d ...

In the event that the final calculated total is a negative number, reset it to zero. Inform the user of an error through the use of a prompt dialog box

I'm having trouble getting the grand total to display as 0 when I enter all amounts in positive values and then change the unit prices to negative values. However, it works fine when I only enter negative values throughout. Can someone please help me ...

What causes the premature termination or truncation of a mysqli query when utilizing ajax/php response?

Currently, I am utilizing an ajax script to transmit parameters and retrieve a response from ajax.php. The process of sending parameters and receiving responses is functioning properly. However, the issue arises when I echo the query in the ajax.php script ...

The Material-ui DatePicker seems to be malfunctioning and as a result, the entire form is not

Struggling to get my DateTimePicker component (could be DatePicker) working after following installation instructions from various sources. I've spent a day and a half attempting to make it functional without success. If you can help me create a separ ...

How to capture a specific part of a model using Autodesk Forge Viewer

I have a situation where I have 20 element Ids that I need to capture screenshots of in a specific size (400x400) like a detail view. The current viewer I am using has different dimensions, so I'm wondering if there is a way to achieve this and return ...

Instructions on transforming an img into an Image component within next.js

I have successfully implemented all the logic in this component, tailored to the <img> tag. Now, I am aiming to apply the same logic to the Image component. However, when attempting to do so, I encounter an error. TypeError: Failed to construct &apos ...

Find the element that is being scrolled in order to delete its attributes

Issue with the sidebar causing whitespace on mobile devices, and scroll properties need to be removed. When expanding the sidebar, white space appears below it. Various display modes have been tried, but they all push elements below instead of keeping th ...

Exploring ReactJS: Utilizing the useEffect Hook for Retrieving Various Data Sources

I have recently started working with react and currently have a function that fetches data in my useEffect hook. I am using a loading state to handle component rendering, and then populating my state component with the fetched data successfully. However, ...