I build the following encoded url:
actionUrl = "MyAction?Vendors=A*A,A%26A,A%2CA"
I want to send this back to my server via an ajax call:
$.ajax({
url: actionUrl,
cache: false,
dataType: "HTML",
success: function (data) {
alert('hooray');
},
error:function(data) {
alert(data.responseText);
}
});
But when this reaches my action on the server, the string is this:
Vendors = "A*A,A&A,A,A"
I need to parse by a comma before i decode the string, but its coming to my server decoded. How do I send an encoded string to my action method via ajax? I'm using asp.net MVC4 but i think thats moot. Thanks
Send the data as JSON like this:
var values = ["A*A","A&A","A,A"];
actionUrl = "MyAction?Vendors=" + JSON.stringify(values);
Then in ASP.net you could use system.Web.Script.Serialization.JavaScriptSerializer to serialize this into an object.
using System.Web.Script.Serialization;
var json = "[\"A*A\",\"A,A\",\"A&A\"]"; //this is the received JSON from the ajax call
var jss = new JavaScriptSerializer();
var values = jss.Deserialize<dynamic>(json);
var value1 = values[0].ToString(); //A*A
var value2 = values[1].ToString(); //A,A
var value3 = values[2].ToString(); //A&A
This way no further (unwanted) conversion takes places between the client and the server. JavaScript converts it to JSON, ASP.net converts it back to its native object notation. Thus eliminating the need to encode your characters, this will be done automatically by the browser and the server decodes it back, as you have seen.
Related
I am using Java 1.7 and struts 1.3 framework. I am working for Japanese client. Currently my requirement is to send Search key (containing Japanese string) to the Action class using JQuery Ajax call. But at the action side I found some Japanese character are corrupted.
My code:
var searchKey = $('#searchtxt').val();
// some Japanese string value for search.
var data = {
// other properties
"searchKey": searchKey,
// Other properties
};
$.ajax({
type: 'POST',
url: url,
data: data,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (resultData){//dostuff}
});
I am quite new to SO I don't know how to format.
I have tried many solution on SO but not work for me. Any help will be appreciated.
Thank you for any help.
To solve this Japanese encoding problem, use URL Encoding mechanism and then send data through ajax call. And then at the Struts action side simply you need to decode it by using URL decoder mechanism.
It will solve this problem.
For the more clarity see the below code.
At the Java script side while fetching data from the hidden field use URL encoding method:
var searchKey = encodeURIComponent($('#searchtxt').val().trim());
// It will encode the Japanese string before send from Ajax call.
At the Struts Action side use URLDecoder class to decode the string value:
String searchKey=form.getSearchKey();
if(!searchKey.isEmpty()) //Check for empty or null string
{
// Decode the string using URLDecoder class from java.net package
form.setSearchKey(URLDecoder.decode(searchKey, "UTF-8"));
}
I am trying to pass an array of bytes to my WebMethod through JavaScript.
The problem is that my WebMethod returns with the message "The test form is only available for primitive methods as parameters."
When I change data type to string or any other kind of primitive variables the WebMethod accepts it goes on.
I'm transforming an object into a byte[], named msgpackEnvio using MessagePack(The transformation itself occurs well), and then sending to WebService.
Here's my request to WebService using jquery
$.ajax({
beforeSend: function (request) {
request.setRequestHeader("Content-Type", "application/json");
},
processData: false,
dataType: "json",
url: url,
data: msgpackEnvio,
type: "POST",
error: function (data) {
$('#upload-load').hide();
$('.bt-enviar-excel').removeAttr('disabled', 'disabled');
var msg = document.getElementsByClassName('msg')[0];
msg.style.color = 'red';
msg.innerHTML = 'Erro interno servidor!';
},
success: //some code
In fact, the code above doesn't matters at all, my problem is in the webService, and how to make it receive an array or perhaps an object.
And here's my WebMethod that should be able to receive a byte[]
[WebMethod]
public string TestMessagePack(byte[] name)
{
//my code
return "Finish";
}
You can use base64 encoding and decoding to send byte arrays as strings. Anything more than that and you might want to use post requests and JSON serialization/deserialization instead. There's not going to be a generic one size fits all conversion between complex C# objects and javascript objects which is why only primitive parameters are allowed, so for nonprimitive things you'll need a translation layer. That's normally going to mean some form of string serialization and deserialization.
I have used dojo/dom from a javascript file before to call a php file on another domain that handles some database queries and returns the result to the javascript file.
The call to the php file was (i offcourse hope i can use the same call to asp)
postdata = dojo.toJson({ action: "get", userid: 1 });
require(["dojo/_base/xhr", "dojo/dom", "dojo/domReady!"],
function (xhr, dom) {
var xhrArgs = {
url: "http://otherdomain.com/file.php",
postData: postdata,
handleAs: "text",
load: function (result) { }
};
var deferred = dojo.xhrPost(xhrArgs);
In the php file i had
$foo = file_get_contents("php://input");
$postvalue = json_decode($foo, true);
to read the values from the dom call.
The reason i need to do this is because i get an error from the browser about a security risk because of the cross domain request.
So i think i need to use Jsonp
How do I write the php code in asp? NOT asp.net
Since your post data is JSON, the Request.Form won't be filled in, so you will have to use Request.BinaryRead and convert this result as a string.
See here to convert this JSON string into an object.
Im currently trying to sent a javascript array to my .php file handler and save it to my database.
The request is successful however it seems my array doesn't get POSTED / saved correctly.
In my POST request source it just turns up as: round_items%5B%5D=1
What am I missing?
id = 5;
var roundChallenges = new Array("item1", "item2", "etc");
//Save the data
var url = path.php;
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: { uid: id, round_items: roundChallenges },
success: function(data)
{....
round_items%5B%5D=1 is correct. That is what it should be sending. That decodes to round_items[]=1, which is how you make arrays in query strings.
When you pass an object to $.ajax, jQuery converts it to a query string, a standard transport format.
In PHP, you don't need json_decode or anything. It will parse it into $_POST for you. $_POST['round_items'] will be an array, and $_POST['uid'] will be your id.
I will be passing a json string to a servlet via an ajax request :
function add() {
$.ajax({
url: "pathToServlet" ,
dataType: "text",
data: ({
name : 'myJsonString'
}),
success: function(data) {
alert('returned!!');
});
}
To build up this json string I have a listener which when fired appends a new piece of json to string :
var json = "";
json += "{ new json ..... }"
Is this the correct way to build up the jSon String ? Should I be using jQuery methods to create a json object(if they exist) and add elements to it and then convert the json object to a string instead of creating the json string myself ?
What I would recommend doing is building up an object, and then when you're ready to send it to the server, serialize the object via JSON.stringify.
So for instance, you might have an object called data:
var data = {};
...to which you might periodically add properties:
data.foo = "bar";
data.stuff = {nifty: "stuff"};
Or perhaps data is an array:
var data = [];
...to which you add things:
data.push({nifty: "stuff"});
Then, when you're ready to send it:
function add() {
$.ajax({
url: "<%=savePortlet%>" ,
dataType: "text",
data: {
name : JSON.stringify(data)
},
success: function(data) {
alert('returned!!');
});
}
Because you're passing an object into ajax, you don't have to worry about URL-encoding the JSON string; jQuery will do it for you.
JSON.stringify is defined as part of ECMAScript5 and suppoted natively by many browsers, but of course many of us have to support outdated versions of browsers. In those cases, you can get a "JSON shim" to add JSON.stringify to an environment that doesn't have it. One of those is available from the originator of JSON, Douglas Crockford, on his github page.
If using jQuery you can use jquery-json, a really handy plugin to handle JSON with JavaScript and jQuery.
Usage:
var jsonString = $.toJSON(myObject);