Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So using AJAX I want to send this to my server

{"Question":"Shiping","Answer":"no"},{"Question":"Shiping","Answer":"no"},{"Question":"Shiping","Answer":"no"}]
Then save it to my c: drive.

But I can't seem to get it to on the server, and I have no idea what data type I should take as a parameter for it to work. This is my first time ever using AJAX.
Keep getting an error about primtive data
My JS
JavaScript
var FAQData = [
{"Question":"Shiping","Answer":"no"},
{"Question":"Shiping","Answer":"no"},{"Question":"Shiping","Answer":"no"}
];
// this is created in another way but posting it kinda messes with the display

function done() {

    alert(JSON.stringify(FAQData));//ignore alert

    $.ajax({
        type: 'POST',
        url: 'Userpage.aspx/SaveJSon',
        data: JSON.stringify(FAQData) ,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            alert('worked');
        }
    });
}


my server side
C#
[System.Web.Services.WebMethod]
       public static void SaveJSon(string[] Data)
       {
           string path = PathDetails.UserFilePath + user.Email + "\\FAQ.json";
           if (!File.Exists(path))
           {
               File.Create(path);
           }
           StreamWriter writer = new StreamWriter(PathDetails.UserFilePath + user.Email + "\\FAQ.json");
           writer.WriteLine(Data);
           writer.Close();

       }


What I have tried:

Changing the data type the server accepts, changing the ajax call to say {"Data": JSON.stringfy(FAQData)}

been stuck on this for 2 days
Posted
Updated 12-Jul-20 7:37am

1 solution

Create a class to hold your data

C#
public class QuestionData
{
    public string Question { get; set; }
    public string Answer { get; set; }
}


change your method to accept an array of this type

C#
public static void SaveJSon(QuestionData[] data)


Change your js to pass your FAQ data as a param named "data"

JavaScript
data: JSON.stringify({data: FAQData}),


If you don't want to make a type to hold the data you can use a Dictionary instead

C#
public static void SaveJSon(Dictionary<string, string>[] data)


It's less proper though and more prone to mistakes if the code changes.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900