Home > OS >  How do i send string from code behind in C# to Ajax JQuery and how do i parse it?
How do i send string from code behind in C# to Ajax JQuery and how do i parse it?

Time:12-06

i would like to know how to send a string from asp.net to the JQuery

below is the code for the asp.net and the 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 jquerey
    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;
    }

CodePudding user response:

Please have a look into below URL and check if it suites your problem

https://www.aspsnippets.com/Articles/jQuery-AJAX-call-with-parameters-example-Send-parameters-to-WebMethod-in-jQuery-AJAX-POST-call.aspx

CodePudding user response:

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>
  • Related