extracting URL parameters using AJAX

I have successfully created an AJAX request using the GET method, passing variables to the URL and receiving a response. Now, I need to retrieve the current URL variables by clicking on a newly created button in order to proceed with further processing. These variables are not visible in the browser's address bar but are included in the AJAX request URL. How can I access these variables upon button click?

View the screenshot

 function pagi_ajax(records_per_page){

 var data = 'action=' + 'testing_ajax' + '&records_per_page=' + records_per_page;

    var url_string = window.location.href;
    console.log(url_string);

 $.ajax({
     url: "ajax_pagi.php",
     dataType: "json",
     type: "get",         
     data: data, 

success: function (result) {

    }
  });
}

<a href="javascript:void(0)" onclick="pagi_ajax(records_per_page);">Next</a>
<button class="pagi_button" onclick="pagi_ajax( <?php echo $records_per_page; ?>, 
 <?php echo $rec_limit[$i]; ?>, 
 <?php echo $total_records; ?>)"> <?php echo $i+1; ?> </button>

Answer №1

If you already have the variables, such as "records_per_page," which is used to create the url, you can easily pass it to another function. Simply add a function call within your success callback and pass the necessary variables.

function pagi_ajax(records_per_page){

    var data = 'action=' + 'testing_ajax' + '&records_per_page=' + records_per_page;

    var url_string = window.location.href;
    console.log(url_string);

    $.ajax({
         url: "ajax_pagi.php",
         dataType: "json",
         type: "get",         
         data: data, 

    success: function (result, records_per_page) {
        // Your code here
        console.log(records_per_page)
        }
});

Answer №2

Although the current page's URL can be accessed using the location object, there is currently no standardized API for retrieving URLs used in HTTP requests made with XMLHttpRequest.

If you require this information, it will need to be stored manually somewhere.

In this particular scenario, it seems that the necessary data is already saved in the global variable records_per_page. Therefore, utilize that information accordingly.

Answer №3

It is common practice to define certain variables like recordPerPage as constants and store them in a specific location. If not, you can cache this variable within the pagi_ajax function and retrieve it when needed.

One way to cache this variable is through a service, as shown below:

  pagingInfo = (function(){
    var info = {
      recordsPerPage: 10
    } 
    var get = function(){
      return info;
    }
    var setrecordsPerPage = function(value){
      info.recordsPerPage = value;
    }
    return {
      get: get,
      setrecordsPerPage: setrecordsPerPage
    }
  })()

  function pagi_ajax(records_per_page){
    pagingInfo.setrecordsPerPage(records_per_page);
  }

  function handleClick(){
    var recordsPerPage = pagingInfo.get().recordsPerPage
  }

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

Validating complex ASP.NET MVC objects using AngularJS

I am encountering an issue with validating my model in a subform using AngularJS. Despite making changes to the SearchPostCode values and seeing updates in classes, the error message fails to display, and the button remains disabled. <form novalidate&g ...

Troubleshooting Problem with ListItem Alignment in Material UI v0 involving Custom Avatar Component

Material UI version: v0.20.0 I'm facing an issue with aligning the leftAvatar value using the CustomAvatar component, as shown in the attached screenshot. Any assistance would be appreciated. CustomAvatar: The functionality of this component is cond ...

Deciding between Bull queue and Database Triggers

My current project requires creating records in the database for users on a recurring basis, such as every Monday weekly or biweekly. I have identified two potential solutions to achieve this goal. One option is to utilize Database Triggers to generate ...

Observing the timepiece malfunctioning beyond expectations

Let me explain the issue here in a simple way. I have a parent component where I execute a method that changes a property value of an object called products. This is working fine. However, when I pass this object as a prop to a child component and watch i ...

`How can you adjust the language preferences for users in Meteor?`

My website is internationalized using the tap-i18n plugin. I am looking to allow users to switch between languages on the site. Currently, I have a file called client/setLanguage.js where I set the language on startup: getUserLanguage = function () { ...

Comparing two inherited classes in Typescript: A step-by-step guide

Let's say we have two classes: Animal and Dog. The Dog class is a subclass of the Animal class. I am trying to determine the types of these objects. How can I accomplish this task? class Animal {} class Dog extends Animal {} //The object can be of ...

Aggregate X and Y values based on a key in a scatter plot using dc.js

Here is a glimpse of my dataset: var items = [ {name: "X", duration: 1, quantity: 2}, {name: "X", duration: 2, quantity: 1}, {name: "Y", duration: 1, quantity: 4}, {name: "X", duration: 3, quantity: 1 ...

VueJS allows for seamless image uploading using either a gallery of images or input files

Is there a way to enable image selection from "Pick from gallery" feature in addition to the file upload functionality demonstrated in the example below? I would like the same behavior for selecting an image from the gallery as when uploading a file using ...

Error in saving webpage as HTML

I have integrated FileSaver.js into my project to enable users to save web pages as HTML. The code below is triggered when a user clicks on the download button: var originalstr=$.ajax( { type: "GET", url:"url", async: false }).resp ...

Is there a method to determine if localForage/indexedDb is currently handling data operations?

Currently, I am working on a webapp that utilizes async localForage (specifically angular localForage). My goal is to alert users if they attempt to close the browser window while there are ongoing localForage operations. I have observed that some browser ...

An error popped up: "argument list is missing) after"

Encountered an issue: Error message: missing ) after the argument list $('.next-btn').append("<a class="actionsubmit" ng-click="onSubmit('hello.html')">Check</a>"); ...

Having trouble sending a function as a prop to a child component in React

Something odd is happening, I'm confident that the syntax is correct, but an error keeps popping up: Error: chooseMessage is not a function // MAIN COMPONENT import React, { useState } from 'react' export default function LayoutMain(prop ...

When JSON data is displayed in an HTML table, it mysteriously duplicates

I was able to retrieve the data using this code, but I am encountering an issue where the data is being displayed multiple times for certain entries. For example, "tom" might appear as tom, tom, tom... <div class="row"> <div class="col-12"> ...

problem encountered when loading an HTML file within another HTML file using AJAX

By clicking a button, I successfully loaded a full HTML page (refer to the structure below) into another HTML page. <!--START:HTML to be loaded by ajax--> <head> <!--START: The content inside this head tag is not processed while the pag ...

Utilize the lodash times method for indexing

I have a requirement to duplicate a component "n" number of times. I achieved this by utilizing the lodash method called "times". However, I encountered an issue with assigning an index as a key for the generated components. Below is the snippet of code t ...

No content found in jQuery .text() values within iframe

I am experiencing an unusual issue with assigning a value to a variable using jQuery. I am unable to retrieve the values from .text() specifically on Spotify, while other functions on different sites are working fine. Even after the elements have loaded, i ...

Out-of-sync movement in animated characters

Looking for some assistance with my page coding. I have a scenario where two stars are moving around a button, simulating an animation by incrementing the CSS properties top and left. Initially, everything appears fine and they move synchronously. However, ...

Adjust the body class dynamically based on the URL in AngularJS

Here is the link to my website To Log In - http://localhost/ang/#/login To Access Dashboard - http://localhost/ang/#/dashboard See below for the HTML code for the body tag If the current URL is http://localhost/ang/#/login, then the body should include ...

Result of a callback function

Having trouble returning a value for form validation using a callback function. It's not working for me... <form action="loggedin.php" onsubmit="return test(valid)" method="post"> function test(callback) { var k = ""; var httpRequest = ...

Error detected in Deno project's tsconfig.json file, spreading into other project files - yet code executes without issues?

I am working on a Deno project and need to utilize the ES2019 flatMap() method on an array. To do this, I have created a tsconfig.json file with the following configuration: { "compilerOptions": { "target": "es5", ...