Using AJAX to call a VB ASP.NET web method with parameters in the GET request

I've come across numerous inquiries regarding this issue, but I can't seem to find a solution (the abundance of questions on the internet about this topic is astonishing!!). Let me be direct:

test.asmx

'Simple POST method with parameters
    <WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json)>
Public Function TestarPost(ByVal Valor as String) As String
  Dim x
End Function

'Simple GET method without parameters
    <WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function Testar() As String
        return "ok ;>D"
End Function

'GET method with parameters
    <WebMethod(EnableSession:=True)>
<ScriptMethodAttribute(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)>
Public Function TestarGet(ByVal Valor as String) As String
        return Valor
End Function

Testing it in the JavaScript console:

  obj = { Valor: "x" }
  $.ajax({
      type: "POST",
      url: "test.asmx/TestarPost",
      dataType: "json",
      data: JSON.stringify(obj),
      contentType: "application/json; charset=utf-8",
      success: function(ret) {
          console.log(ret.d);
      },
      error: function(xhr,textStatus,errorThrown) {
          console.log(xhr.status + "||" + xhr.responseText);
      }
  });

Success!

  $.ajax({
      type: "GET",
      url: "ServerSide.asmx/Testar",
      contentType: "application/json; charset=utf-8",
      success: function(ret) {
          console.log(ret.d);
      },
      error: function(xhr,textStatus,errorThrown) {
          console.log(xhr.status + "||" + xhr.responseText);
      }
  });

Success! Returns the data correctly in JSON format

  $.ajax({
      type: "GET",
      url: "test.asmx/TestarGet",
      dataType: "json",
      data: JSON.stringify(obj),
      contentType: "application/json; charset=utf-8",
      success: function(ret) {
          console.log(ret.d);
      },
      error: function(xhr,textStatus,errorThrown) {
          console.log(xhr.status + "||" + xhr.responseText);
      }
  });

Fails! Same approach as with POST

The error message states "Invalid web service call, missing value for parameter: \u0027Valor\u0027." It also fails when sending an object literal ("Invalid JSON primitive"). However, accessing the URL .../ServerSide.asmx/TestarGet?Valor=x returns "opa" (perhaps a clue?)

It's perplexing why it fails to work, given that the approach is similar to the one used in POST. Maybe because the POST method isn't affecting anything visibly (although no errors are returned).

My objective is to develop a function serverSide(asmxMethod, obj) to establish a generalized connection between client and server functions.

Answer №1

After doing some research, I've come across a workaround (though not a definitive answer). A friend informed me that GET requests do not support json parameters. Despite attempting to specify dataType as "text," the request still fails.

The workaround involves using POST consistently. Surprisingly, POST can also handle data retrieval (a fact I was unaware of). By utilizing a POST request, I am able to successfully send and receive data in json format without any issues.

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

TypeScript does not recognize the $.ajax function

Looking for help with this code snippet: $.ajax({ url: modal.href, dataType: 'json', type: 'POST', data: modal.$form.serializeArray() }) .done(onSubmitDone) .fail(onSubmitFail); ...

Perl: Retrieve a single value from a JSON array each time by parsing it from a URL

JSON RESPONSE: Here's the JSON response I need to parse from a URL. [ { "ID": 17682, "TVEStationID": 0, "CallLetters": "DIYHD", "StationName": "DIYHD", ...

Do not use href for ngview change

I have been using ng-view to switch views by setting href="/..." in anchor tags and clicking on them. However, I am now looking for a way to change the view within the ng-view tag based on an event. Can anyone provide guidance on how to accomplish this? ...

Transferring data from Array/Dict in Xcode to JSON, then to PHP, and finally

I'm struggling with this issue and it's driving me crazy. It should be simple, but I feel like I'm missing something obvious. I suspect my lack of PHP/mysql skills is the root cause, as I can't seem to get it to work. I've searched ...

Exploring Cypress: Leveraging the Power of Variable Assignment

Recently, I encountered an issue while working with a variable in a Cypress each loop. Despite incrementing the variable within the loop, it resets to zero once outside of it. Can someone shed light on why this happens and suggest a solution? Thank you. p ...

Having trouble importing OrbitControls in three.js with an error?

I'm currently working on localhost and I've encountered an issue while trying to import "orbitcontrols()" which is not functioning properly and displaying an error. Here is the error message main.js:1 Uncaught SyntaxError: Cannot use import stat ...

Struggling with making react-hook-form correctly validate an email address

I've been struggling for a long time to make this validation work correctly, but it seems impossible. I even added some text at the bottom to display an error message related to the email, but it always shows no error, regardless of the situation. Ed ...

Heroku experiencing difficulty loading JavaScript files within a Django application

After attempting to deploy my Django app on Heroku, I encountered an issue. Everything seems to be working when I use "heroku open", but certain buttons and glyphicons are not functioning correctly. The JavaScript files and Bootstrap CDN JS files are not l ...

Creating an AI adversary for a simple Tic Tac Toe game board: a step-by-step guide

Being new to programming, I recently completed a basic Tic Tac Toe gameboard successfully. However, as I progress to the next phase of my assignment which involves implementing an AI opponent, I encountered several challenges. As a novice in programming, ...

Can getServerSideProps be adjusted to avoid triggering a complete page reload after the first load?

My server-rendered next.js app consists of a 3-page checkout flow. The first page involves fetching setup data like label translations and basket items within the getServerSideProps function, as shown below: UserDetails.js import React from 'react&apo ...

How would you define 'Idiomatic' in the context of Idiomatic Javascript?

During his initial discussion on TypeScript, Anders repeatedly mentions the term 'idiomatic javascript'. Can you clarify the specific definition of idiomatic in this context? I've attempted to research this on Wikipedia and Stack Overflow, ...

Ways to address the absence of the 'Access-Control-Allow-Origin' header on the requested resource

CORS: Dealing with Cross-Origin Resource Sharing (CORS) can be a common challenge for developers, and it's something I've encountered myself when trying to access a REST service from a different domain. When this issue arises, the error message ...

change the return value to NaN instead of a number

Hey there, I have something similar to this: var abc1 = 1846; var abc2 = 1649; var abc3 = 174; var abc4 = 27; if(message.toLowerCase() == ('!xyz')) { client.say(channel, `abc1` +`(${+ abc1.toLocaleString()})` +` | abc2 `+`(${+ abc2.toLocaleStri ...

"Having trouble getting the onChange function to work with Material-UI's Select

I have encountered an issue while trying to implement the material-ui SelectField component in my project. While the common select component works seamlessly, I face problems when using the SelectField component. The main problem arises with the invocati ...

Deactivate a single choice within the select field while allowing the rest to remain active

I am facing a challenge where I have two select elements with the same options. My goal is to disable an option in one select element if it has already been selected in the other select element. Below are my two select elements: <select class="form-co ...

The planebuffergeometry does not fall within the three namespace

I am currently working on a project using three.js and next.js, but I keep encountering this error: 'planeBufferGeometry is not part of the THREE namespace. Did you forget to extend? See: As a beginner in three.js, I'm unsure what exactly is ca ...

Creating interactive routes and pages using Next.js and Prisma, embracing dynamic functionality

I have product information cards stored in my database, and I successfully display them on the user's page. Now, I want to add a "More Details" button on each card that will link to a new page (/pages/card/[id]). However, I'm unsure how to retrie ...

steps to eliminate a cookie upon second click

I have successfully implemented a feature where the color of a button is stored in a cookie, so that when the button is clicked, the CSS color remains even after page refresh. However, I am struggling to figure out how to destroy the cookie after the secon ...

Parsing JSON data in SwiftUI with enums for Element types

I'm encountering difficulties with decoding JSON data that contains an array of dictionaries within it. Despite using online parsers to determine the structure and implement the format accordingly, I am only able to retrieve the data encapsulated with ...

Is it possible to modify the local reference point of an object in three.js?

Is there a method to readjust the center point of an STL file once it has been relocated or turned? For example, if the original rotation of my object is set at (0,0,0), and then I rotate it to (20,70,90) degrees, is it possible to modify the local origi ...