Retrieve data via AJAX using a combination of JavaScript and ASP

Can someone help me figure out how to retrieve the value of value1 on my server-side ASP using Javascript? I am using this Ajax code but unsure of how to do it.

In my serverside code, I would like to have something like <% var newdata = value1 (which is the one from the serverside - which was sent here) %>

Please Help! Thank you in advance!

I know it's possible with PHP, but can someone guide me on how to do it with Javascript?

<script>
function ajaxNow(_data)
{
  var xmlHttp;
  try
  {
    /* Firefox, Opera 8.0+, Safari */
    xmlHttp=new XMLHttpRequest();
  }
  catch (e)
  {
    /* newer IE */
    try
    {
      xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
      /* older IE */
      try
      {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
      catch (e)
      {
        alert("Your browser is old and does not have AJAX support!");
        return false;
      }
    }
  }
  xmlHttp.onreadystatechange=function()
  {
    if(xmlHttp.readyState==4)
    {
      /* this puts the value into an alert */
      alert("Value read is: "+xmlHttp.responseText);
    }
  }
  xmlHttp.open("GET","ajax_file.asp?value1="+_data,true);
  xmlHttp.send(null);
}
</script>

Answer №1

It's important to note that client-side Javascript is unable to directly access server-based databases, for security reasons. To achieve what you're trying to do, I recommend implementing an ASP script that can execute the query using VBA, C#, or another appropriate language. From there, you can process the results in your client-side ajax call as usual.

Answer №2

To ensure secure transmission, make sure to URL encode the variables _data and nbquestions. Use Request.QueryString("param1") to decode them when needed.

For JavaScript URLEncode:

encodeURIComponent(_data);

You can also utilize Server.URLEncode() methods with VB script for encoding.

Answer №3

The correct way to send xmlHttp

  • It overlooks the need to check for a status of 200 before processing the data.
  • There is a failure to properly encode the data for URL safety.

My recommendation would be to utilize a library for handling XHR operations, rather than attempting to create your own solution from scratch. Check out Microjs which offers a variety of small libraries if you are not using one of the bigger ones like YUI or jQuery.

How can I extract values on the server-side using Javascript?

The data will be in query string format, accessible through Request.QueryString.

Answer №4

When an AJAX request is made, the server-side script processes the request and retrieves the required data from the database before sending it back to the client side.

There are numerous tutorials available that demonstrate how to set up this functionality. It's essential to prioritize securing your script to prevent potential exploitation.

Answer №5

If you want your ASP page to output results in JSON format that can be directly read via the XMLHttpRequest Object for further processing, consider the following approach:

Here is an example of JSON format:

var myJSONObject = {"bindings": [
        {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"},
        {"ircEvent": "PRIVMSG", "method": "deleteURI", "regex": "^delete.*"},
        {"ircEvent": "PRIVMSG", "method": "randomURI", "regex": "^random.*"}
    ]
};

You can then utilize native parsers available in web browsers or use eval() (not recommended) to parse the data generated by your ASP page and incorporate it into your client-side JavaScript code.

For more information on JSON basics, please refer to this resource.

JSON support in various browsers:

Answer №6

//(javascript, ajax = xmlHttp)

if you have an array as your response text, you can utilize the following code snippet:

var myArray = eval(xmlHttp.responseText);

If your response is just plain text, this code will come in handy:

var value = xmlHttp.responseText

Here's another approach. The following template can be used with jQuery to handle responses:

html part:

<div id="willupdate"></div>
<div id="willupdate2"></div>

JQuery part:

 $(document).ready(function() {

getValue("serverurl", updateName)
getValue("serverurl", updateSurName)
 });

function updateName(name){
 $("#willupdate").text(name)
}


function updateSurName(name){
 $("#willupdate2").text(name)
}

function updateSurName(name){
 $("#willupdate").text(name)
}

function getValue(url,opt_onRecieved){
    if( !url || url == ""){
        alert("request url error");
        return;
    }

    $.ajax({
        type:"POST",
        url: url,
        dataType:"json",
        success: function(data){
            opt_onRecieved(data);

        }
    });
}

Answer №7

Upon successful completion of your Ajax request, the query string variables will be stored in the QueryString Collection of the Request Object.

Here is an example of how it could be implemented on the server side:

<% var newdata = Request.QueryString("value1"); %>

Answer №8

Check out this fantastic tutorial on AJAX. It covers everything you need to know. https://developer.mozilla.org/en/AJAX/Getting_Started

Don't forget to add a double quote:

xmlHttp.open("post","CmsAjax.asp",true)

Here's how to retrieve the data:

/* This will display the value in an alert */
alert(xmlHttp.responseText);

Answer №9

To ensure secure data transmission, it is recommended to encode the data on the server and decode it on the client side. One popular method for achieving this is by using JSON-RPC.

Here are a few helpful links:

Check out the Official JSON-RPC Website

Read the Wikipedia Article about JSON-RPC

Explore different Implementations of JSON-RPC Service in various languages

If you only have one value to encode, you can simply use JSON in ASP to encode it and then decode it in JavaScript like so:

var array = JSON.parse(xmlHttp.responseText);

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

Looking for a solution to resolve the issue of a jQuery function that only works once? This problem is directly related to using

I'm experiencing an issue with my jQuery code where it only works once in a fresh browser session. After that, the e.preventDefault() function stops working and the entire code fails to run. I suspect this issue may be related to the .load AJAX funct ...

The ajax method for loading an xml file results in displaying the undefined message

When attempting to fetch content from an xml file using ajax, the page initially displays "undefined". However, upon refreshing the page, the content loads successfully. Take a look at my code snippet below: $.ajax({ type: "GET", url: "xm ...

What is the best way to remove current markers on google maps?

This is how I implemented it in my project. The issue I'm facing is that the clearAirports function does not seem to clear any existing markers on the map or show any errors in the Google console. googleMaps: { map: null, init: function () { ...

Troubleshooting problems in transferring JSON data between a React application and a Spring Boot service running locally

Running a local Springboot server, accessing it locally in the browser returns a properly formatted JSON object. However, encountering issues when trying to fetch this JSON object from a React application running on node locally. Managed to overcome CORs h ...

Django template experiences issue with AJAX functionality when attempting to open a new window through right-click action

I have successfully created a link using AJAX with the following HTML code: <a id="post_click" href="{{ post.online_url}}" rel="nofollow"> <button class="w-100 " type="button" name="button& ...

Inquiry about an IP board forum

When using an IP board forum, you may have noticed that you can easily click on the "quote" button for any message you wish to quote. Then, when you navigate to the "add reply" page, the quoted messages are automatically included in your response form. I ...

Express.JS failing to save data to file when using NeDB

Currently, I am developing a bulk import feature for my personal password manager and I have encountered a problem. The issue arises when trying to import an array of passwords using the forEach() method to iterate through each one. After calling the inse ...

Check the email for accuracy and show as needed

I need help verifying email validity in JavaScript and displaying an alert box if it's invalid. If the email is valid, I want to display div2 instead. However, my current code doesn't seem to be working as expected. Below is the JavaScript code ...

Can you explain the distinction between browser.sleep() and browser.wait() functions?

Encountering timing problems with my protractor tests. Occasionally, test cases fail because of network or performance-related issues. I managed to resolve these issues using browser.sleep(), but recently discovered browser.wait(). What sets them apart an ...

Creating a personalized filter list in Vue Instant Search: A step-by-step guide

Currently, I'm utilizing Laravel Scout with Algolia as the driver. Vue is being used on the front end and I've experimented with the Vue instant search package, which has proven to be very effective. The challenge I am encountering involves cust ...

Leveraging React hooks to combine an array and an object within an array

Struggling to incorporate an array and an object into another array. This is the setup in my constructor: const [dashboard, setDashboard] = useState({ loading: true, data: [], address: '' }) This is how I envision the final data structure: { ...

Obtain the non-dynamic route parameters as query parameters in Next.js

I need help figuring out how to extract specific query parameters from a URL in my component. I want to exclude dynamic route parameters, such as {modelId}. For example, if the URL is /model/123456?page=2&sort=column&column=value, I only want to re ...

Vue 2.0: Exploring the Power of Directive Parameter Attributes

It has come to my attention that directive param attributes have been phased out in Vue.js 2.0. As a result, I am unable to use syntax like v-model="msg" number within an input tag. Are there alternative methods to achieve the same outcomes without relyi ...

Tips for invoking a particular function when a row in a Kendo grid is clicked

I have a Kendo grid named "mysubmissionsGrid" and I want to execute a function when each row is clicked with a single or double click. How can I accomplish this? <div class="col-xs-12 col-nopadding-left col-nopadding-right" style="padding ...

Utilize promise-style for Sequelize associations instead, please

I am in the process of merging information from 3 tables - Products, Suppliers, and Categories. My goal is to retrieve the row with SupplierID = 13. I recently came across a helpful explanation on How to implement many to many association in sequelize, whi ...

Steps to send an object array using a promise

I've put in a lot of effort but haven't found a solution that works well for me. I attempted using promise.all and setting the array globally, but it didn't work out. My goal is to search through three MongoDB collections, match the finds, ...

'jQuery' is not recognized as defined, error no-undef

I am currently working on a file that utilizes jQuery for testing purposes: (function($) { "use strict"; // Start of use strict // Configure tooltips for collapsed side navigation $('.navbar-sidenav [data-toggle="tooltip"]').tooltip({ ...

Issues encountered while utilizing the jQuery function $.ajax()

I'm encountering issues with utilizing ajax in conjunction with jQuery... Here is the script I am using: $(document).ready(function() { $('rel[close]').click(function() { $(this.parent).close(); }); $('a[rel=trac ...

Contrast in executing an Arrow Function versus a regular Function when passing them as Props in REACTJS

Here is the component code: <SelectCampanha titulo="Preenchimento obrigatório" listaOpcoes={ category ? riskModel.filter((item) => item.CategoryType.includes(categoria) ...

The button fails to function properly following the initial successful loading of ajax data

var Update = { init: function(){ $('.find').on('click', function(e){ e.preventDefault(); var $this = $(this), $form = $('#searchForm'); BLC.ajax({ ...