Trying to pass an array variable from asp to javascript - javascript

trying to pass an array variable to java
The following is not working, any idea why and how to make it work
Code behind
Public myArray (5) As String
myArray(1) = "A1"
myArray(2) = "A2"
myArray(3) = "A3"
myArray(4) = "A4"
myArray(5) = "A5"
In asp
<button type = "button" onclick="myJava('<%= myArray %>');">Search</button>
In Javascript
function myJava (myArray) {
alert(myArray[1]); // expected answer is A1 but it is not
}

You need to properly encode your array. Firstly, you need to convert it to a JSON string; then you need to encode that string as an HTML attribute value.
Add a reference to the Newtonsoft.Json NuGet package. Add an Imports statement for the Newtonsoft.Json namespace. Add a method to your code-behind to return the properly-encoded function call:
Public Function PassArrayToJavascript(ByVal functionName As String) As String
Dim json As String = JsonConvert.SerializeObject(myArray)
Dim result As String = functionName + "(" + json + ");"
Return System.Web.HttpUtility.HtmlAttributeEncode(result)
End Function
Then update your markup to call this function:
<button type = "button" onclick="<%= PassArrayToJavascript("myFunction") %>">Search</button>

Related

how to get string 'Sugar&Jaggery, Salt' via <a> in codeigniter?

plz anyone me i m beginner in codeigniter in herf passing url with string but the whole can't get in
controller & can't accepting as sting so what shold i do for it plz someone help me
//Here is html code which pass sting value
index.php/Home/product_show?type='Sugar&Jaggery , Salt'">Sugar & Jaggery , Salt
//controller get sting in type variable but on Sugur got not whole sting and pass type variable to model
public function product_show(){
$type = $_GET['type'];
die(var_dump($type));
$data['testdata']= $this->Globle_model->get_multiple_record($type);
$this->load->view('display_product',$data);
}
//model type variable check the subcategory from database and return to controller
public function get_multiple_record($type){
$this->db->where_in('Subcategory_name',$type);
$get_data = $this->db->get('productmaster');
return $get_data->result_array();
}
//o/p
get this much of string(6) "'Sugar"
Please follow the below way to get all your string into the controller into
$_GET['type'] variable.
Combine all your strings into a single variable using _ into href
Example :
Sugar & Jaggery , Salt
In the controller, I have created one array() with variable subcategory_type .In which key is coming from the view but its value from the database.
Example :
function get_product_type(){
$get_info = $this->input->get();
$subcategory_type = array(
"Sugar_Jaggery_Salt" => "Sugar&Jaggery , Salt"
);
$type_arr = $subcategory_type[$get_info['type']];
$data['testdata']= $this->Globle_model->get_multiple_record($type_arr);
$this->load->view('display_product',$data);
}
In model,
function get_multiple_record($type_array){
$this->db->where_in('Subcategory_name',$type_array);
$get_data = $this->db->get('productmaster');
return $get_data->result_array();
}
Try this and update me in case of anything.

Java hashmap : Not write comma after printing the last entry

I'm using hashmap in Java to hold three pairs of servers in format (name,size), and then pass this hashmap to Javascript.
In Javascript there is no comma after the last entry:
data: [
{
name : "client3",
y:23,
},
{
name : "client1",
y:245,
},
{
name : "client2",
y:23,
}]
so I don't know how to get rid of this comma in Java using HashMap iterator :
for (Map.Entry<String, String> entry : listClientSize.entrySet()) {
String name = entry.getKey().toString();;
String size = entry.getValue();
out.println("name : \""+name+"\",");
out.println("y:"+size+",");
out.println("},");
}
Any ideas?
Instead of writing the comma at the end of the loop, write it at the beginning. It's much easier to check first iteration than last iteration.
boolean first = true;
for (Map.Entry<String, String> entry : listClientSize.entrySet()) {
String name = entry.getKey().toString();;
String size = entry.getValue();
if (first)
first = false;
else
out.println("},");
out.println("{");
out.println("name : \""+name+"\",");
out.println("y:"+size);
}
out.println("}");
BTW: You were missing the print of the start-brace {, and had a comma after the y value.
Update: Since that pattern for handling first iteration is so common, and the action is so simple (usually just appending a separator), I usually collapse the code as follows (don't do this if you have strict coding standards):
if (first) first = false; else out.println("},");
It seems you are creating JSON, so consider using proper JSON parser to generate your results. For instance with gson library your code could look like
Class containing single informations you want to store
public class Server{
private String name;
private int value;
public Server(String name, int value) {
this.name = name;
this.value = value;
}
//getters and setters
}
You can use this class like:
List<Server> list = new ArrayList<>();
list.add(new Server("1", 245));
list.add(new Server("2", 23));
list.add(new Server("3", 23));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(list);
System.out.println(json);
which will generate:
[
{
"name": "1",
"value": 245
},
{
"name": "2",
"value": 23
},
{
"name": "3",
"value": 23
}
]
You can add later data = at start if you absolutely need it.
If you can use Java 8, use StringJoiner
final StringJoiner stringJoiner = new StringJoiner(",");
Map<String,String> listClientSize = new HashMap<String,String>(){{
put("client3","23");
put("client1","245");
put("client2","23");
}};
for (Map.Entry<String, String> entry : listClientSize.entrySet()) {
String name = entry.getKey().toString();;
String size = entry.getValue();
stringJoiner.add(String.format("{name:\"%s\", y:%s}", name, size));
}
System.out.println(stringJoiner.toString());
To get rid of the comma after the y property, which is the last property in the object, just do this:
for (Map.Entry<String, String> entry : listClientSize.entrySet()) {
String name = entry.getKey().toString();;
String size = entry.getValue();
out.println("name : \""+name+"\",");
out.println("y:"+size);
out.println("},");
}
To get rid of the comma at the very end, instead of printing from the for loop, build up a string and then use substring to cut off the last character after your for loop, then print the string
One easy thing you could try is accumulating the string to print in a StringBuilder, and then stripping the last comma, using substring. It should look like this:
StringBuilder output = new StringBuilder();
for (Map.Entry<String, String> entry : listClientSize.entrySet()) {
String name = entry.getKey();
String size = entry.getValue();
output.append("{name :\"").append(name).append("\", ");
output.append("y: ").append(size).append("},");
}
String toPrint = output.substring(1, output.size() - 1);
out.println(toPrint);
You probably need a way to tell if its not last entry then append the comma. One simplistic way is to keep a counter n n increment each iteration. If counter != hashmap size append comma

How to access array returned by a json call

How to access the typeMatch which is of type array from the below object using javascript.
Here is what i am trying and able to access message but not typeMatch
$.getJSON(uriGetTypeMatch)
.done(function (data) {
document.getElementById('MessageBox').innerHTML = data.message;
});
Return object
Sample:
{
"typeMatch": {
"sample string 1": 2,
"sample string 3": 4
},
"message": "sample string 2"
}
Any help is appreciated.
Thanks.
I hope this will help you.
On your main form put this on the top:
Imports Newtonsoft.Json
You can download and add this dll to your References from here:
https://www.nuget.org/packages/newtonsoft.json/
After that create simple class with all your objects in Json, paste this on your main form:
#Region " - Classes - "
Public Class JSON_result
Public typeMatch As String
Public sample_string_1 As String
Public sample_string_3 As String
Public message As String
End Class
#End Region
You can add more objects, depends on your Json.
To Get Data from your Json Link use this:
Private Sub GetJsonData()
Try
Dim wc As WebClient = New WebClient
Dim jsonlink As String = "http://yourJsonlink.com/data.txt"
Dim jsondata As String
jsondata = wc.DownloadString(jsonlink)
TextBox1.Text = jsondata.ToString
Catch ex As Exception
End Try
End Sub
After that the final is to Load and show Data and values into textboxes:
Private Sub LoadDataToTextBoxes()
Try
Dim obj As JSON_result
obj = JsonConvert.DeserializeObject(Of JSON_result)(Me.TexTbox1.Text)
typeMatchTXT = obj.typeMatch
sample_string_1TXT = obj.sample_string_1
sample_string_3TXT = obj.sample_string_3
messageTXT = obj.message
Catch ex As Exception
End Try
End Sub
You can make TextBox1.Visible = False on your main app, to hide Json
loaded data from the link.

Razor inside javascript key value declaration?

Given the need to extract data from a viewdata into a javascript key/value object:
var stuff = {
something : [#someVar.Prop2, #someVar.Prop3, etc]
};
I want to make the key have the "name" of someVar.Prop1 so that:
var stuff = {
#someVar.Prop1 : [#someVar.Prop2, #someVar.Prop3, etc]
};
Yet when I use the form in the second code block above, I get a Expected identifier, string or number error at the colon:
#someVar.Prop1 : [#someVar.Prop2, etc]
---------------X (x marks the spot)
How do I need to format the razor code so that it knows what I'm trying to say?
You should definitely not be trying to build your JSON piece by piece in your Razor view. That can go wrong very easily.
To expand on #DLeh's answer, what you can do is build a dictionary of the values you want, serialize that into JSON right in your Razor view, and assign that to your variable as shown here:
#{
// Assume that someVar is provided from somewhere else;
// this is just for demonstration
var someVar = new { Prop1 = "My Prop", Prop2 = "Prop Value", Prop3 = 7 };
}
#{
var obj = new Dictionary<string, object>
{
{someVar.Prop1, new object[] { someVar.Prop2, someVar.Prop3 } }
};
}
<script>
var stuff = #Html.Raw(Json.Encode(obj));
</script>
Rendered output:
<script>
var stuff = {"My Prop":["Prop Value",7]};
</script>
You can surround razor expressions in quotes ' or " to have them output into a javascript block. If you need the type to be preserved properly, you can use methods like parseInt() or parseFloat() to do so.
Example:
var stuff = {
value1 : '#val1',
value2 : [ parseInt('#val2'), parseInt('#val3') ]
};
If you need to left side of the assignment to be variable, you will probably need to build a json string and then parse that into the object. Something like this, my quotes might be off.
var stuffJson = '{"#value1" : "#val1", "#value2" : "[ #val2, #val3 ]" }';
var stuff = JSON.parse(stuffJson);
If you're doing this a lot, you might want to consider using the Json() method in your controller to help you build these more easily. You could build a dictionary of key / value and have that output json:
public virtual ActionResult GetStuff()
{
string value1 = "key1",
value2 = "key2",
val1 = "str1",
val2 = "str2",
val3 = "str3";
var dict = new Dictionary<string, object>
{
{ value1, val1},
{ value2, new List<string> { val2, val3} },
};
return Json(dict, JsonRequestBehavior.AllowGet);
}
Output:
{"key1":"str1","key2":["str2","str3"]}
The answer is to ignore Visual Studio's complaint of the problem as the code runs and throws no error:
#country.CountryCode: ['#someVar.Prop1', '#someVar.Prop2', etc],

How to pass model data in javascript

I need to pass a model value item.ID to one of my javascript function how can I do that ?
I triedfunction("#item.ID") but its not working
It generally works this way, you just have to omit the "" otherwise it gets interpreted as string. So you can write something like that in your JS:
var myinteger = #item.ID;
which renders as
var myinteger = 123; //for example
Edit: This makes sense when you id is an integer, of course, for strings you need to encapsulate it in '' or "". And don't get annoyed by any syntax errors reported by intellisense, it seems to have a problem with that but it works out just nicely.
You can pass the model data into the java script file in these ways
(1). Just set the value in hidden field and access the value of hidden field in java script.
(2). And pass the value using function parameter.
(3).
var LoginResourceKeyCollection = {
UserName_Required: '<%= Model.UserName%>',
Password_Required: '<%= Model.Password%>'
}
</script>
Try this...mind single quotes on parameter value while calling js function
function MyJsFunction(modelvalue)
{
alert("your model value: " + modelvalue);
}
<input type="button" onclick="MyJsFunction('#item.ID')" />
OR
<input type="button" onclick="MyJsFunction('#(item.ID)')" />
The best solution is pass your textbox ID to javascrpit function and then in function retrieve the value form the ID,
#Html.TextBoxFor(model => model.DatemailedStart, new {id = "MailStartDate", placeholder = "MM/DD/YYYY", maxlength = "40", #class = "TextboxDates", #onblur = "isValidDate('MailStartDate');" })
function isValidDate(id) {
var dateString = $('#'+id+'').val();
}

Categories

Resources