Is There a Standard Way to Encode a .Net String into JavaScript String for Use in Ms Ajax

Why encodeURIComponent not working if requested string contains quote?

You need to escape double quotes before output for javascript. So that it will be valid syntax. You should use something like:

<%= yourValue.Replace("\"", "\\\"") %>

Also you can use a better way of escaping with javascript:

var Details = "AgentCompanyName=" + $("<div/>").text("<%=yourValue%>").html(); 

With this you will create in memory DIV element, set value as text and get as escaped HTML.

Escaping quotes in Javascript variable from Classic ASP

You've asked how to do this "Using jQuery." You can't. By the time jQuery would be involved, the code would already be invalid. You have to fix this server-side.

Classic ASP is unlikely to have anything built-in that will help you solve this in the general case.

Note that you have to handle more than just " characters. To successfully output text to a JavaScript string literal, you'll have to handle at least the quotes you use (" or '), line breaks, any other control characters, etc.

If you're using VBScript as your server-side language, you can use Replace to replace the characters you need to replace:

var goala = "<%=Replace(goal_a, """", "\""")%>";

Again, though, you'll need to build a list of the things you need to handle and work through it; e.g.

var goala = "<%=Replace(Replace(Replace(goal_a, """", "\"""), Chr(13), "\n"), Chr(10), "\r")%>";

...and so on.

If your server-side language is JScript, you can use replace in much the same way:

var goala = "<%=goal_a.replace(/"/g, "\\\").replace(/\r/g, "\\r").replace(/\n/g, "\n")%>";

...and so on. Note the use of regular expressions with the g flag so that you replace all occurrences (if you use a string for the first argument, it just replaces the first match).

How can you encode a string to Base64 in JavaScript?

You can use btoa() and atob() to convert to and from base64 encoding.

There appears to be some confusion in the comments regarding what these functions accept/return, so…

  • btoa() accepts a “string” where each character represents an 8-bit byte – if you pass a string containing characters that can’t be represented in 8 bits, it will probably break. This isn’t a problem if you’re actually treating the string as a byte array, but if you’re trying to do something else then you’ll have to encode it first.

  • atob() returns a “string” where each character represents an 8-bit byte – that is, its value will be between 0 and 0xff. This does not mean it’s ASCII – presumably if you’re using this function at all, you expect to be working with binary data and not text.

See also:

  • How do I load binary image data using Javascript and XMLHttpRequest?

Most comments here are outdated. You can probably use both btoa() and atob(), unless you support really outdated browsers.

Check here:

  • https://caniuse.com/?search=atob
  • https://caniuse.com/?search=btoa

Pass html string to server side with Jquery Ajax

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); }

});

jQuery 1.5 Pass strings and an object to a .NET page method

Look at the close answer here, here or here. Many people made the same errors.

  1. In the initialization of JavaScript objects you can use both quotes and double quotes, but in the JSON data only double quotes are permitted.
  2. You should no time make JSON serialization manual like {"{'startDate':'" + startDate + "', ... and not use old $.toJSON jQuery plugin. The best way is to use JSON.stringify function from the json2.js. The most current version of the web browsers support the function in the native code, so it work very quickly.

One more thing which look strange is the path "/myurl/jquery.aspx/GenerateUserSchedules" instead of "/myurl/jquery.asmx/GenerateUserSchedules" (asmx instead of aspx).

In your case you should use

data: JSON.stringify({
startDate: startDate,
endDate: endDate,
ddlViewSelectedItem: ddlViewSelectedItem,
ddlViewSelectedValue: ddlViewSelectedValue,
ddlOrgSelectedValue: ddlOrgSelectedValue
})

in case of usage of type: "POST" and

data: {
startDate: JSON.stringify(startDate),
endDate: JSON.stringify(endDate),
ddlViewSelectedItem: JSON.stringify(ddlViewSelectedItem),
ddlViewSelectedValue: JSON.stringify(ddlViewSelectedValue),
ddlOrgSelectedValue: JSON.stringify(ddlOrgSelectedValue)
}

if you decide to use type: "GET".

It is important to send data for all input parameters of the web method. At least you should send parameters with the null value as the input (for nullable objects).

UPDATED: At the time you rewrote your question. So now the answer on the new version of your question.

You should use

$.ajax({  
type: "POST",
url: "/myurl/jquery.aspx/GenerateUserSchedules",
data: JSON.stringify({data: [
{UserId:8},{UserId:9},{UserId:5},{UserId:13},{UserId:6},{UserId:11}]}),
contentType: "application/json",
dataType: "json",
success: function () { alert('Made It!'); },
error: function (result) { alert(Failed: ' + result.responseText);
});

The reason is easy. Because you have the method GenerateUserSchedules(User[] data) with the data input parameter you should use JSON.stringify({data: yourData}) as the input. The array of User objects should be array with the items {UserId:8} (or {'UserId':8} or {"UserId":8}), but not {UserId:"8"}.

JavaScript equivalent to printf/String.Format

Current JavaScript

From ES6 on you could use template strings:

let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!

See Kim's answer below for details.



Older answer

Try sprintf() for JavaScript.


If you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.

Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:

"{0}{1}".format("{1}", "{0}")

Normally you would expect the output to be {1}{0} but the actual output is {1}{1}. So do a simultaneously replacement instead like in fearphage’s suggestion.

Pass Silverlight type to Microsoft AJAX and pass parameter validation

I found a pretty good overview of this here, but even that overview seemed to cover every scenario except the one you mention. I'm wondering if this can't be done because javascript objects really are functions (more or less).

What if you wrote a wrapper function that could create the state object using a string?



Related Topics



Leave a reply



Submit