Is there any way to pass JSONObject from android to javascript. We are using WebView.evaluateJavascript mehtod and are able to send only String type object. In JS if we are checking the method paramter;s typeof(data) then it is displaying as string but in iOS it displays typeof(data) as OBJECT.
In both android and iOS we are passing String and NSString.
JS method is:
response: function(id, err, data) {
var dataObj;
if(typeof(data) == 'string' ){
dataObj = JSON.parse(data || '{}');
}
}
Android call:
String responseStr = "{\"ok\":\"ok\"}";
String nativeToWebMethod = "javascript:window.nativeService.response("1",'','"+responseStr+"')";
webView.evaluateJavascript(nativeToWebMethod, null);
Just send it as if you were loading a url:
private void loadJS(String jsonResponse){
mWebView.loadUrl("javascript:" + "(function(){" + "yourJsMethodName" + "(" +jsonResponse + ");" + "})()");
}
This will execute a JS Code that will call a function called yourJsMethodName and will pass the JSON as parameter.
Consider execute the last code in the Main Thread
I find out the issue, it was in the way I was sending data:
String nativeToWebMethod = "javascript:window.nativeService.response("1",'','"+responseStr+"')";
should be replaced with
String nativeToWebMethod = "javascript:window.nativeService.response("1",'',"+responseStr+")";
removed single quote around the responseStr.
Related
The function getClientData() gets called from one of the anchor tags in a grid's column. The anchor tag has a couple of Data-Tags which are passed to the code behind method. I have to perform some DB operation through these parameters but before that I wanted to make sure if this prototype would work.
This is how the anchor tag looks:
Show
This is my Javascript method:
function getClientData() {
//var dataValue = { "keyData": this.event.target.getAttribute("data-kt"), "valueData": this.event.target.getAttribute("data-kv")};
$.ajax({
type: "GET",
url: "Clients.aspx/GetClientData",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ keyData: this.event.target.getAttribute("data-kt"), valueData: this.event.target.getAttribute("data-kv")}),
dataType: 'json',
error: function (error) {
alert(error.statusText);
},
success: function (result) {
alert("Success: " + result );
}
});
}
I put a break point here and it never gets triggered. This is my web method in the code behind file:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string keyData, string valueData)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}
This is the URL that gets created for the POST request "http://localhost:60825/Clients.aspx/GetClientData?{%22keyData%22:%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22,%22valueData%22:%221p7q9%22}". Please let me know if I am doing something wrong.
I am not sure how you configured routing but based on your API method (code behind) your data should be formatted in following manner:
Method 1:
http://localhost:60825/Clients.aspx/GetClientData?keyData=Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy&valueData=1p7q9
As you can see, instead passing stringified JSON object I am sending data in format of query string where keyData and valueData has corresponding values.
Method 2:
If you prefer to send stringified JSON you can modify your Payload in URL like this:
http://localhost:60825/Clients.aspx/GetClientData?data=%7BkeyData%22%3A%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22%2C%22valueData%22%3A%221p7q9%22%7D
Here I am sending stringified JSON as data parameter in query string. For that purpose your code behing method needs to be like this:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string data)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}
I have a jsp page. There is a form in the jsp page and when I press submit the control goes to the servlet and the servlet sends the response in the same jsp. I want to call a javascript fuction after the response is called.
String operation = request.getParameter("operation");
if (operation.equals("create")) {
String value = null;
Map<String, String> requestMap = new HashMap<>();
String entity = request.getParameter("entity");
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
if (paramName.equals("operation") || paramName.equals("entity")) {
value = request.getParameter(paramName);
} else {
value = Constraints.toTitleCase(request.getParameter(paramName));
}
requestMap.forEach((k,v)->System.out.println("{KeY} :"+k+".....{VAlue} :"+v));
requestMap.put(paramName, value);
}
masterHelper.processRequest(requestMap);
log.debug("js");
response.getOutputStream().println("<script>sucess();('hello');</script>");
response.sendRedirect("user/master/" + entity + ".jsp");
}
Looks like you are redirecting the page .
response.sendRedirect("user/master/" + entity + ".jsp");
try sending the function definition also.
All you can do is use just set extra variable for it and then based on the value of that variable call the javascript function. You can follow steps below
In your servlet set a boolean variable
boolean isResponse=true;
Then add it to your response
request.setAttribute("isResponse", isResponse);
the add below code in your jsp.
${ isResponse=="true"?'windows.onLoad=functionname()':'' }
And you are done with it.
Is it possible to pass multiple arguments in the __doPostBack call?
I Know how I use one arrgument
__doPostBack('Service', $("input[name=celservice]:checked").val());
and in code behind vb.net
If eventTarget = "Service" Then
'Something
EndIf
but how when I use two arguments
We have created our own library to pass data from web page to ASP.NET. Without getting too much into details, the javascript code wraps info into an XML stream (you can use JSON just as well) that is then parsed on the server.
At its core, our javascript object looks something like this:
function MyArgs() {
var args = '';
this.add = function (id, value) {
args += ('<param id="' + encodeURI(id) + '" value="' + encodeURI(value) + '" />');
};
this.output = function () {
return '<request>' + args + '</request>';
};
}
And we use it like this:
var args = new MyArgs();
args.add("param1", "value A");
args.add("param2", "Value B");
__doPostBack("YOUR_SERVICE", args.output());
We like it because we are quite comfortable with XML data, but you may as well use JSON or URL encoding. The logic is the same: you create a stream that you can parse on the server.
This technique is also useful the other way around, server to client, especially as a response to AJAX requests.
I hope this may be of help to you :)
You can wrap your multiple results in an object, like so:
var result = {
celservice: $("input[name=celservice]:checked").val(),
somethingElse: true
}
then
__doPostBack('Service', result);
I have a C# method that works if you call it from another C# method, but not from javascript. How do I make it work from my ajax call?
I need to get a file based on an ID that is passed in, so I have an ajax post with the statusID. That ID is pulling the proper file in my C# method, it is just not giving the file save dialog.
However, if I call this from my C# page load method with a static statusID for testing purposes, it works just fine.
Here is the C# method:
public void Get_Attachment_By_StatusID(int statusID)
{
SqlDataReader _reader = null;
string _connString = "Data Source=133.31.32.33;Initial Catalog=Reports;Integrated Security=True";
string sql = "SELECT a.StatusID ,a.DocumentName ,a.MIMETypeID ,a.Binary ,a.CreatedDate ,a.CreatedBy " +
",b.MIMEType FROM Attachments a Inner join MIME_Types b on a.MIMETypeID = b.ID " +
"WHERE [StatusID] = {0} ";
sql = string.Format(sql, statusID);
try
{
_connection = new SqlConnection(_connString);
_connection.Open();
using (SqlCommand cmd = new SqlCommand(sql, _connection))
{
cmd.CommandType = System.Data.CommandType.Text;
_reader = cmd.ExecuteReader();
if (_reader.HasRows)
{
while (_reader.Read())
{
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
System.Web.HttpContext.Current.Response.ContentType = _reader["MIMEType"].ToString();
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + _reader["DocumentName"].ToString() + ";");
byte[] b = (byte[])_reader["Binary"];
System.Web.HttpContext.Current.Response.BinaryWrite(b);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
}
}
_reader.Close();
_connection.Close();
}
}
catch (Exception ex)
{
//Log exception to error Logging app
string err = ex.ToString();
}
finally
{
if (_connection != null)
_connection.Close();
if (_reader != null)
_reader.Close();
}
}
Here is how I am calling it from my page, in javascript:
function GetFile(statusID) {
var url = '/Home/Get_Attachment_By_StatusID';
$.ajax({
url: url,
type: 'post',
cache: false,
data: JSON.stringify({ "statusID": statusID }),
contentType: 'application/json',
success: function (data) {
}
});
}
Nothing happens. In Chrome, I don't see anything in the javascript console, and in IE, my console spits this out: "XML5619: Incorrect document syntax."
Again, if I go into the controller, and call the method in my page load method, it presents the save file dialog and saves the file just fine. So I must be doing something wrong with my javascript/jquery/ajax...
I am new to MVC4 and know I'm missing something here. What am I missing?
Use window.open('CONTROLLER_URL/STATUS_ID'); instead of an AJAX request.
<a target="_blank" href="javascript:window.open('/Home/Get_Attachment_By_StatusID/12345');">Test</a>
Here's one suggestion, largely based on answer from LastCoder:
Decorate your action with the [HttpGet] attribute and change the parameter name to id:
[HttpGet]
public void Get_Attachment_By_StatusID(int id) ...
Now in your client-side code, simply do this:
function GetFile(statusID) {
var url = '/Home/Get_Attachment_By_StatusID/'+statusID;
window.location=url;
}
I work on an ASP.NET MVC project.
I have to pass two parameters to an action in my controller. the first is a serializable object, and the second one is an integer.
First time I tried to pass only one parameter, the serializable object. There is no problem, but when I add the second parameter, the serializable object doesn't delivered (null value), but the integer parameter delivered successfully.
this is my action look like :
[HttpPost]
public bool MyAction(MySerializableObject myData, int intParameter)
{..}
and this is how I try to pass the parameters :
$('#submit-button').click(function () {
var formData = $("#MyForm").serialize();
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, { myData: formData, intParameter: '5005' }, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});
});
Anyone can explain about it ? how can it happens and how to solve the problem ?
thanks.
this may be a bit of a longshot but have you tried swapping the order of the parameters around (IE public bool MyAction(int intParameter, MySerializableObject myData) The reason im asking is that it may be that your client side serialize isnt working quite right.
If not your best bet is to take a look at whats actally getting posted to the server. Open up firebugs net tab or similar in webkit and take a look at whats actually going back to the server.
You could use the following plugin (serializeObject) instead of .serialize:
var formData = $('#MyForm').serializeObject();
// add some data to the request that was not present in the form
formData['intParameter'] = 5005;
var posturl = '/MyController/MyAction';
var retUrl = '/MyCOntroller/SomeWhere';
...
$.post(posturl, formData, function (result) {
if (result == 'True') {
location.href = retUrl;
}
else {
alert('failed');
}
});