Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass html string to server side with Jquery Ajax

i have seen a lot of answers in this site that have helped me a lot but in this one i need to ask guys to help me out.

i have a textarea as a Html editor to pass html content to the server and append it to a newly created Html page( for user POST,etc), but jquery or ASP.NET does not accept the Html content passed by jquery through data: {}

--For Jquery:

  $("#btnC").click(function (e) {
    e.preventDefault();

    //get the content of the div box 
    var HTML = $("#t").val();

    $.ajax({ url: "EditingTextarea.aspx/GetValue",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: '{num: "' + HTML + '"}', // pass that text to the server as a correct JSON String
        success: function (msg) { alert(msg.d); },
        error: function (type) { alert("ERROR!!" + type.responseText); }

    });

and Server-Side ASP.NET:

[WebMethod]
public static string GetValue(string num)
{ 
    StreamWriter sw = new StreamWriter("C://HTMLTemplate1.html", true);
    sw.WriteLine(num);
    sw.Close();       
return num;//return what was sent from the client to the client again 
}//end get value

Jquery part gives me an error: Invalid object passed in and error in System.Web.Script.Serialization.JavascriptObjectDeserializer.

It's like jquery doesnt accept string with html content.what is wrong with my code ?

like image 375
Mr. Lost Avatar asked Sep 11 '13 02:09

Mr. Lost


2 Answers

Pass it like this

JSON.stringify({'num':HTML});

You have to stringify the content to JSON properly. HTML may contain synataxes that would make the JSON notation invalid.

var dataToSend = JSON.stringify({'num':HTML});
     $.ajax({ url: "EditingTextarea.aspx/GetValue",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            data: dataToSend , // pass that text to the server as a correct JSON String
            success: function (msg) { alert(msg.d); },
            error: function (type) { alert("ERROR!!" + type.responseText); }

        });
like image 162
Subin Jacob Avatar answered Oct 23 '22 19:10

Subin Jacob


You can use this

var HTML = escape($("#t").val());

and on server end you can decode it to get the html string as

HttpUtility.UrlDecode(num, System.Text.Encoding.Default);
like image 26
Bibhu Avatar answered Oct 23 '22 17:10

Bibhu