Transferring data through Ajax communication

I am currently facing an issue while working on a project. I cannot seem to figure out what is wrong with my code. Below is the snippet of my code where I am having trouble with the Ajax url not being able to access the function ReceivedMessageByIndexNumber in default.aspx. Any help would be greatly appreciated.

JavaScript:

    ReceivedMessage(1);

    function ReceivedMessage(indexNumber) 
    {
        $.ajax({
            type: "Post",
            url: "Default.aspx/ReceivedMessageByIndexNumber?indexNumber="+indexNumber,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var data = response.d;
                for (var i = 0; i < data.length; i++) {
                    alert(data[i]);
                }
            },
            failure: function (msg) {
                $('#output').text(msg);
            }
        });
    }

Default.aspx :

    [WebMethod]
    public static bool ReceivedMessageByIndexNumber(int textIndex)
    {
        string connectionString = @"Data Source=localhost;Initial Catalog=NotificationSystem;Integrated Security=True";
        using (SqlConnection connection = new SqlConnection(connectionString))
        using (SqlCommand command = connection.CreateCommand())
        {
            connection.Open();
            command.CommandText = @"SELECT TextWord FROM TextProperty WHERE TextIndex = '" + textIndex + "'";
            command.ExecuteNonQuery();
            return true;
        }
    }

Answer №1

It seems that you are using the HTTP POST method, but attempting to pass the parameter as if it were an HTTP GET. In my experience, parameters are not usually specified in the URL for a POST request.

You'll notice that I have included the line for JSON Data below. This is what populates your post request.

data: '{textIndex: "' + indexNumber + '" }',

Complete Function:

function ReceivedMessage(indexNumber) 
{
    $.ajax({
        type: "Post",
        url: "Default.aspx/ReceivedMessageByIndexNumber",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: '{textIndex: "' + indexNumber + '" }',
        success: function (response) {
            var data = response.d;
            for (var i = 0; i < data.length; i++) {
                alert(data[i]);
            }
        },
        failure: function (msg) {
            $('#output').text(msg);
        }
    });
}

Answer №2

When making a post request, it's important to include parameters in the request body instead of in the URL. Make sure to adjust your ajax call accordingly.

function HandleReceivedMessage(indexNumber) 
    {
        $.ajax({
            type: "Post",
            url: "Default.aspx/ReceivedMessageByIndexNumber?indexNumber="+indexNumber,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: "{'textIndex': " + indexNumber+ "}",
            success: function (response) {
                var data = response.d;
                for (var i = 0; i < data.length; i++) {
                    alert(data[i]);
                }
            },
            failure: function (msg) {
                $('#output').text(msg);
            }
        });
    }

Answer №3

function GetMessagesByIndex(index) 
{
    $.ajax({
        type: "Post",
        url: "/Default/GetMessagesByIndex/",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: { messageIndex: index },
        success: function (response) {
            var messages = response.data;
            for (var j = 0; j < messages.length; j++) {
                alert(messages[j]);
            }
        },
        error: function (errMsg) {
            $('#output').text(errMsg);
        }
    });
}

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

Tips for defining the type restriction in the code provided

interface IRouteProps { path: string name: string } const routesConfig: IRouteProps[] = [ { path: '/login', name: 'login' } ]; let routeNames: any; const routes: IRouteProps[] = routesConfig.forEach((route: IRouteProp ...

JavaScript - Iterating over an object using a loop

I'm attempting to generate dynamic buttons based on an object: var buttonsMenu = { "A":{ A1: 97, A2: 85, A3: 65, A4: 70, A5: 40 }, "B":{ B1: 97, B2: 85, B3: 65, B4: 70, B5: 40 } }; var categoryButt ...

"415 Unsupported Media Format" Issue

I am encountering difficulties in sending JSON from my form to work with Spring MVC. The form is dynamic, and the JSON is returned as an object that is saved. However, when working with the case, I keep getting a 415 error which indicates that the media ty ...

What could be causing the issue with multiple selection in jQuery?

I am interested in implementing multiple selection on my ASP page. I came across the pickList jQuery plugin and followed the instructions provided at the following link: Below is a snippet from my ASP page: <%@ Page Language="C#" AutoEventWireup="true ...

Tips for utilizing window.scrollTo in tandem with react/material UI?

I have a simple functional component that displays an alert panel with an error message under certain conditions. The issue I am facing is that when the alert panel is rendered due to an error, it might be off-screen if the user has scrolled down. To addre ...

How to insert a new list item with specific attributes using Jquery

Can anyone help me troubleshoot why I keep getting an error when trying to add a list item with attributes in my code? <div class="subway-map" data-columns="12" data-rows="10" data-cellSize="40" data-legendId="legend" data-textClass="text" data-gridN ...

I am searching for a regular expression in JavaScript that can detect balanced parentheses within a phone number. The pattern I currently have is /^([1]{0,1})s?(?d{3})?[-s]?d{3}[-s]?d{

When entering a phone number, the following format must be followed: The phone number may start with a "1," which is optional. There can be a space after the starting digit, which is also optional. An opening parenthesis "(" is optional. This should be fo ...

What could be causing my ng-grid footer to refuse to align with the bottom border?

Currently utilizing ng-grid and various AngularJS UI Bootstrap components on my website, I have encountered a recurring issue. By diligently investigating, I have successfully replicated the problem. Access the Plunker demonstration through this link. The ...

Updating the placeholder text of a textarea using a conditional statement in PHP

I currently have a textarea within a form that is being outputted: <textarea id='textarea' name='msg' rows='2' maxlength='255' cols='80' placeholder=' Share a thought...'></textarea> ...

Html2Canvas failed to save the image

Can someone help me troubleshoot the issue I'm having with capturing an image using HTML2Canvas library? The code below includes a tab with an image inside it, but for some reason, the image is not being captured when I try to download the entire div. ...

Enhance the post data in jqGrid by including an extra parameter when inserting a new row through a modal form

When trying to add a new record with a modal form in jqGrid, I am having trouble adding an additional dynamic parameter to the POST data. I attempted: $('#table').setPostData({group: id}); $('#table').setPostDataItem('group' ...

Is AJAX malfunctioning while the success function is functioning properly?

the function for success is operational, however the data isn't being saved in the database $(document).ready(function() { $("#ChatText").keyup(function(e){ if(e.keyCode == 13) { var ChatText = $("#ChatText").val(); ...

Preventing callbacks from proceeding until animations in ajax beforeSend event are finished

While using slideUp and slideDown in the beforeSend ajax event, I encountered an issue where it works flawlessly in Firefox. However, in other browsers, the ajax postback appears to finish before the slideUpDown animation completes. As a result, my success ...

Encountered an error while trying to export a vast amount of data to xls format due to

Currently, I am facing an issue when exporting a large DataTable to an Excel sheet in .xls format. The stored procedure that I call returns 750,000 rows with 93 columns. When running the stored procedure from the back end with parameters, it takes approxi ...

The functionality of Jquery is successfully integrated into a specific function, however it seems to only work for one of the calls. To make the other call work,

After a user makes a selection, I am attempting to reset the 'selected' item. This process calls the Vue function tS() shown below. The issue lies with the first call $('#sel1').prop('selectedIndex',0);, as it only seems to wo ...

Tips for applying custom gradient colors and styles to React Native's LinearGradient component

"react-native-linear-gradient" - tips on passing colors and styles as props interface Props { // gradientColors:string[] gradientColors:Array<string> } const BaseButton: React.FC<Props> = ({ gradientStyle ,gradientColors} ...

What is the best way to prevent a page from refreshing every second when the Bootstrap modal is being displayed or active?

I am working on a project that involves two PHP pages. In the first page, I have set up a system to display data from a MySQL database using Ajax, with the content refreshing every second. The second page contains the PHP code responsible for fetching the ...

Show only the results that have identifiers matching the parameter in the URL

My goal is to filter objects based on a URL parameter gatewayId and display only those whose id matches the parameter. import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @Component({ selector ...

Mongodb is processing a multitude of queries simultaneously

Our previous PHP application was able to handle 30k unique queries in a mongo collection with great performance. foreach ($request->numbers as $number) { $query = [ 'cn' => $ddd, 'prefix_init' => array(&apo ...

What are some ways to reduce the delay of Dark mode on a website?

Can anyone help me optimize the speed at which dark mode is applied on my website? Currently, there seems to be a delay between page load and the dark mode taking effect. Below is the jQuery.js code I am using: onload = function () { if (localStorage. ...