"Using AJAX to send a POST request to asp.net and receiving a response with a

Hey there! I'm currently working on my computer science project for school, using asp.net and c#. I've run into a bit of an issue where my AJAX POST request is being received as a GET request. I've tried to troubleshoot it myself but no luck, so I could really use some help :)

The problem occurs when I try to send an AJAX POST request upon changing a textbox, intending to write its content to a file in the backend. However, when I check for Request.HttpMethod, it shows as a GET request.

Here's a snippet of my HTML code:

<%@ Page Async="true" Language="C#" AutoEventWireup="true" CodeBehind="FilePage.aspx.cs" Inherits="filmhelperschoolproject.Pages.FilePage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<body>
    <center>
        <form runat="server" id="form1">
            <div>
            <textarea style="width:40%; height:800px;" runat="server" id="fileTextArea" oninput= "saveText()"></textarea>
            </div>
        </form>
        
    </center>
</body>
    <script>
        function saveText() {
            event.preventDefault();
            var url_string = window.location.href;
            var url = new URL(url_string);
            var name = url.searchParams.get("name");
            var id = url.searchParams.get("id");
            var filename = name + id;
            var text = document.getElementById('fileTextArea').value;
            $.ajax({
                method: "POST",
                url: "FilePage.aspx?id=" + id + "&name=" + name,
                data: {
                    "text": "hello world"
                },
                dataType: "html",
                success: function (response) {
                    console.log('File written successfully!');
                },
                error: function (xhr, status, error) {
                    console.log('Error writing file: ' + error);
                }
            });
        }
    </script>
</html>

Here's a snippet from my Page_Load function:

 protected void Page_Load(object sender, EventArgs e)
        {
            string name = Request.QueryString["name"];
            string id = Request.QueryString["id"];
            string path = "C:\\Users\\User\\source\\repos\\filmhelperschoolproject\\filmhelperschoolproject\\Files\\";
            if (Request.HttpMethod == "POST")
            {

                string text = Request.Form["text"];
                File.WriteAllText(path + name + id + ".txt", text);
                return;

            }
            if (!IsPostBack)
            {
                fileTextArea.InnerText = "";


                string [] lines=File.ReadAllLines(path + name + id + ".txt");
                foreach( string line in lines)

                {
                    fileTextArea.InnerText += line + "\n";
                }

            }
            
        }

Your help would be greatly appreciated!

(P.S. You're looking very sharp today, sir!)

Answer №1

It is recommended to include: dataType: "json" in your code. For more detailed information on using JQuery ajax, please refer to the official documentation here.

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

Displaying various images within a bootstrap modal window

I'm facing an issue with my gallery. It contains small images, and when a user clicks on a thumbnail, a modal should open with the full-size image. The problem is that even though I have the full-size images stored in the "/uploads/" folder and the th ...

Examples of Docusign implementation in dotnet 4.7

Can anyone help me locate some dotnet 4.7 Docusign examples that I can incorporate into my Umbraco website? So far, all I have come across are examples for dotnet Core. Appreciate any assistance. Regards, Tom ...

Cross-Origin Resource Sharing (CORS) and Google Chrome

I'm currently working on a Javascript file that is responsible for sending data to a remote server using websockets and ajax POSTs. The code appears to be functioning correctly as the server receives the requests, and the different browsers I've ...

What is the reason for the vertex shader failing to compile?

Recently diving into the world of WebGl, I decided to experiment with a simple example. Here is how I set up my script: Here's my setup script import testVertexShader from './shaders/test/vertex.glsl' import testFragmentShader from './ ...

I want to import JSON information from a file to display on my website

I am trying to implement a JSON array on my webpage when a button or image is clicked. Here is the array I have: var products = [ { "productID":"1", "name":"Stark Navy", "url": "stark.jpg", "description": "Waterproof, double velcro straps", "price": " ...

Guide on displaying a grid in the center of the screen with a vertical sliding feature

I've noticed certain apps displaying a grid view or form on an alert box with vertical sliding, but I'm clueless about how to make it happen. As far as I know, this can be achieved using jQuery.. Any assistance would be greatly appreciated. Th ...

How can Symfony, Jquery, and Ajax work together to append elements to themselves?

I've implemented a jQuery function that dynamically adds rows of data from one table to another table for submission. Essentially, when a user selects an item or items (a row) in the initial table, it gets duplicated in a separate area where they can ...

Removing a row from MySQL using JQuery Ajax

Hello there! I'm currently facing an issue while trying to remove a row from a MySQL database using PHP and AJAX. I initially thought it would be a simple task with $.ajax {}, but unfortunately, the row is not getting deleted for some reason. Here&apo ...

Request from across origins in AmpersandJS is being made

Here is a sample AmpersandJS model: var AmpersandModel = require('ampersand-model'); module.exports = AmpersandModel.extend({ urlRoot: 'http://0.0.0.0:4567/api/v1/people', props: { id: 'any', name: [& ...

Is your Angular5 service failing to transmit data?

I have two components in my code, A and B. Component A contains a form with data that I want to send to component B. However, it seems like component B is not receiving any data. Here is the code for Component A: import { MyService } from 'path/my ...

Error: The API_URL_KEY variable has not been declared

hardhat.config.js require("@nomicfoundation/hardhat-toolbox"); /** @type import('hardhat/config').HardhatUserConfig */ module.exports = { solidity: "0.8.18", }; /* @type import('hardhat/config').HardhatUserConfig* ...

Creating interactive <td> elements in HTML with JavaScript editor capabilities

Currently, I am working on creating an editable table feature and managed to find a good example to follow. However, I have encountered some issues along the way. <td contenteditable="true" class="hover" onBlur="saveToDatabase(this,'question' ...

I am unfamiliar with this scenario but I can utilize Axios, async/await, and TypeScript to navigate it

Having trouble creating a workflows list from an axios response Error: Argument of type 'Promise<unknown>' is not assignable to parameter of type 'SetStateAction<WorkflowForReactFlowProps[] | null>'. Here's the Axios c ...

Removing elements from an array of objects using specific values stored in another array - JavaScript

I'm currently working on implementing a reducer in redux that can delete multiple items from the state based on an array of values. Let's say I have the following array: const idArray = ["935", "933", "930"]; My goal is to remove objects that ...

What is the process for updating the source in an input box?

How can I use JavaScript to update the src value of an iframe based on input? <input class="url" id="url1" type="url" value="youtube url"> <input onclick="changevideo()" class="add-video" id="add-video1" type="submit" value="add to play ...

Struggling with filtering an array fetched from an API using VueJS

Currently, I am working on a Nativescript-Vue app and facing some challenges that I need help with. The Scenario I have data coming in from an API. Here is the structure of the data I receive: { "count": 9, "results": [ { "id": 1, "c ...

Counting records in a nested ng-repeat using AngularJS

As a newcomer to AngularJS, I am facing an issue with a nested ng-repeat using a custom filter. I want to display the record count of Orders being shown, but when applying a product filter, it does not work as expected. For instance, if an order has no pro ...

Guide on implementing react hook form 7 together with Material-UI switch

When utilizing react-hook-form with MUI switch, there is an issue where the initial value does not display on page load despite being set to true. However, upon form submission without any changes, the switches reflect their correct values (true or false). ...

Chai spy does not recognize sinon stubbed functions when verifying function calls

I am working with two asynchronous functions that return bluebird promises: Async1: function() { return new Promise(function(resolve, reject) { execute(query) .then(function(resp) { resolve(resp); }) .catch(function(err) { ...

How can jQuery be used to target a specific class based on its inner value?

For instance, within a div of the same class, there are 6 "p" tags - some containing 'member' text and others not. I aim to use jQuery to select all "p" tags with 'member' as their inner text and apply an additional class to them. Here ...