skip to Main Content

I would like to know how to send a string from asp.net to jQuery.

This is the code for ASP.NET and jQuery:

var jQueryXMLHttpRequest; 

$(document).ready(function () {

readNamesSent();
});

//Method         readNamesSent
//Parameters    : string
//Retrun        :  
//Description   : This file reads the name being sent from the StartingPage.aspx
function readNamesSent() {

jQueryXMLHttpRequest=$.ajax({
    type: "POST",
    url: "StartingPage.aspx/sendString",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {

        document.getElementById("status").innerHTML = response + "hi";
      
    },
    fail: function (response) {
       
    }
});
}

Below is the ASP.NET file code. The string that I am trying to send over to jQuery is the "name2".

The main problem we are having is trying to send the value and establishing a connection. jQuery to me is quite confusing.

Any help would be greatly appreciated!

public partial class StartingPage : System.Web.UI.Page
{
    // name in a string array over to jQuery
    public void openFile()
    {
        //  string LoadFile = "";
        //Store the file name 
        List<string> list = new List<string>();
        string fileStatus;
        string[] fileNameListToBeSent;

        string filepath = HttpContext.Current.Server.MapPath("MyFiles");
        
        string filepath2 = HttpContext.Current.Server.MapPath(""); 

        filepath2 = filepath2+@"" + "MyFiles";

        bool tof = Directory.Exists(filepath2);
       
        fileNameListToBeSent = list.ToArray();
        string name2 = string.Join("|", fileNameListToBeSent);
        sendString(name2);
    }

    [WebMethod]
    public static new string sendString(string names)
    {
        string returnData;
        returnData = JsonConvert.SerializeObject(new { listOfName = names });
        return reutrnData;
    }
}

2

Answers


  1. Refer the below sample

    **Code**
    [WebMethod]
    public static string SayHello(string name)
    {
        return "Hello " + name;
    }
    **HTML**
    <button type="button" onclick="callAJAX()" >Say Hello</button>
    <script type="text/javascript">
        function callAJAX() {
            $.ajax({
                type: "POST",
                url: "Default.aspx/SayHello",
                data:"{name: 'richie'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    alert(msg.d);
                }
            });
        }
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search