I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.
Related
I am trying to have save changes on my script and I just need an update from my table. So far if I clicked the button, the alert success will not pop and can't see any error either. I also tried to verify to my table if the changes is made but the result is nothing happened
Here is the call function from my save button:
<script>
var op = '';
var op_dif = '';
$('#btnSave').click(function () {
op = $('#op').val();
op_dif = $('#op_difficulty').val();
alert(op + " " + op_dif); // I can see the value here
$.post("/Home/UpdateOP", {
'data': JSON.stringify([{
'op': op,
'opDiff': Op_dif
}])
}, function (data) {
var resp = JSON.parse(data);
if (resp["status"] == "SUCCESS") {
alert('Data has been successfully updated');
location.reload();
}
else {
alert('Error!!');
}
});
});
</script>
My view where my update query is located:
public string UpdateOpsDiff(operation[] ops)
{
string res = "";
foreach(var op in ops)
{
string updatetQuery = "update sys.OP_difficulty set op_difficulty = #diff where op = #op;";
MySqlCommand updateCommand = new MySqlCommand(updatetQuery);
updateCommand.Connection = myConnection;
updateCommand.Parameters.AddWithValue("#diff", op.op_dif);
updateCommand.Parameters.AddWithValue("#op", op.op);
myConnection.Open();
int updatedRowNum = 0;
try
{
updatedRowNum = updateCommand.ExecuteNonQuery();
}
catch(MySqlException)
{
updatedRowNum = updateCommand.ExecuteNonQuery();
}
finally
{
myConnection.Close();
}
res = "{status:SUCCESS, updatedRowNum:" + updatedRowNum + "}";
}
return res;
}
Controller where it reads the view query:
public string UpdateOp()
{
string data = Request.Form["data"];
IQA sys = new MysqlSys();
try
{
var rows = JsonConvert.DeserializeObject<operation[]>(data);
return sys.UpdateOpsDiff(rows);
}
catch (JsonSerializationException je)
{
Console.WriteLine(je.Message);
return "{status:'DATA_FORMAT_ERROR'}";
}
}
Is there any missing items that I need. It already working using the query from my controller but this time I need to store my query from my view.
Any suggestions or comments. TIA
Since you're using AJAX callback, you should change return type to ActionResult and mark the action method with [HttpPost] attribute, also you should use return Content() or return Json() depending on returned type from UpdateOpsDiff() (string or object, respectively). Here is an example of proper setup:
[HttpPost]
public ActionResult UpdateOp(string data)
{
IQA sys = new MysqlSys();
try
{
var rows = JsonConvert.DeserializeObject<operation[]>(data);
string result = sys.UpdateOpsDiff(rows);
// return JSON-formatted string should use 'Content()', see https://stackoverflow.com/q/9777731
return Content(result, "application/json");
}
catch (JsonSerializationException je)
{
// do something
return Json(new { status = "DATA_FORMAT_ERROR"});
}
}
Then set the AJAX callback to pass JSON string into action method mentioned above:
$('#btnSave').click(function () {
op = $('#op').val();
op_dif = $('#op_difficulty').val();
var values = { op: op, opDiff: op_dif };
$.post("/Home/UpdateOP", { data: JSON.stringify(values) }, function (data) {
var resp = JSON.parse(data);
if (resp["status"] == "SUCCESS") {
alert('Data has been successfully updated');
location.reload();
}
else {
alert('Error!!');
}
});
});
Note:
The JSON-formatted string should be presented in key-value pairs to be returned as content, as shown in example below:
res = string.Format(#"{""status"": ""SUCCESS"", ""updatedRowNum"": ""{0}""}", updatedRowNum);
I have two JS files as shown below (page1.js) and (page2.js for reference included below). I am basically referring to the following JSON response while working :
{
"webservice_status": {
"status": "SUCCESS",
"message": ""
},
"my_document_list": [{
"doc1": "445",
"doc2": "445",
"doc3": "445",
"doc4": "445",
"content": "Some text here to display"
}
]
}
Here is my page1.js related work:
$("#mydoclist").on('rowclick', function (event) {
row = event.args.rowindex;
datarow = $("#mydoclist").jqxGrid('getrowdata', row);
var response = JSON.stringify(datarow, null, 10);
var docID = datarow["doc_id"];
self.getMyDocumentContents(docID);
});
this.getMyDocumentContents = function (contentID_) {
var data = {
doc_id: contentID_
}
app_.get(data, self.processContent, app_.processError, url_name);
}// End of getMyDocumentContents
this.processContent = function(data_,textStatus_,jqXHR_) {
data_ = app_.convertResponse(data_,jqXHR_);
console.log("Checking for actual data_ content:", data_);
console.log("Actual Data Length Check for data_ content:", data_.my_document_list.length);
// debugger;
var collection = data_.my_document_list.length[0].content;
console.log("Collection Check",collection);
//debugger;
var source = {
localdata: collection,
datafields: [{
name: 'content',
type: 'string'
}],
datatype: "array"
};
var dataAdapter = new $.jqx.dataAdapter(source, {
loadComplete: function (records) {
debugger;
var html;
//Get data
var records = dataAdapter.records;
console.log("Check for records:",records.length);
var length = records.length;
html = "<div style='margin: 10px;'><pre>" + records[0].content + "</pre></div>";
$("#docContentPanel").jqxPanel('clearcontent');
$("#docContentPanel").jqxPanel('append',html);
},
loadError: function (xhr, status, error) { },
beforeLoadComplete: function (records) {
}
});
// perform data binding
dataAdapter.dataBind();
var panel = $("#docContentPanel");
var content = panel.html();
panel.jqxPanel({ width: '750', height: '500', scrollBarSize: 20 });
}// End of processContent
Here is my page2.js related work:
this.get = function (data_, done_, fail_, webServiceKey_) {
// Lookup the requested web service URL
var url = https://documentlookup.com:8443/getmydocuments;
// Create the AJAX request.
$_.ajax({
data: data_,
method: "GET",
url: url
})
.success(done_)
.error(fail_);
};
// If the JSON data was returned with content type of "text/plain", parse as JSON before returning.
this.convertResponse = function (data_, jqXHR_) {
return (typeof(data_) === "object" ? data_ : JSON.parse(data_));
};
Basically there is a list of rows displayed in a jqxgrid(not mentioned in the code above), when a user clicks on it
$("#mydoclist").on('rowclick gets called , which calls the following function:
getMyDocumentContents function: This function basically passes the doc_id inside data variable which is made
available for the following function:
processContent:
In this function, I am trying to show in jqxPanel the value of the contentwhich is in my_document_list array.
Problem I am facing inside this function:
As can be seen, there are debugger I placed at various places which are currently commented except at one place
which is just below this line loadComplete: function (records) {
I don’t get any error above this line var dataAdapter = new $.jqx.dataAdapter(source, { , however, as soon as
I place it inside it, I get the following error:
Uncaught TypeError: Cannot use ‘in’ operator to search for ‘length’ in jquery-1.11.1.js:583
Where length is a numerical number which keeps on changing depending upon the length of value of content in the above JSON response.
Could anyone tell me what’s going wrong? thanks in advance !
Just in case needed, here is the jQuery line #583 isArraylike function :
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj; // THIS is LINE 583 which throws error
}
Should I try changing the jQuery version?
At data_.my_document_list.length[0].content; I think you need data_.my_document_list[0].content;.
my_document_list is an array and as such the array access should occur there.
I have a Asp.net MVC program in which i want to get a list from the View using Javascript and pass that list to the controller. I want to the variables in the list to be string type except for one to be int32.
The problem is the list is either empty or does not pass.
I tried to use stringify but it doesn't fill the requirments.
Here is the code from the javascript part:
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val();
var nodeType = $("#ColumnType").data("kendoComboBox").value();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var ListNodeDetails = JSON.stringify(ListNodedet);
var ListMethod = JSON.stringify(Listmet);
var select = 1;
var url = "/Configuration/CallMethod";
$.get(url, { ListNodeDetails:ListNodeDetails, ListMethod:ListMethod }, function (data) {
$("#Data2").html(data);
});
})
The C# code for the controller were it calls another method in models:
public bool CallMethod(List<Variant> ListNodeDetails, List <string> ListMethod)
{
var AddMethod = RxMUaClient.CallMethod(ListNodeDetails, ListMethod, "127.0.0.1:48030");
return AddMethod;
}
The Model:
public static bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod, string iPAddress)
{
var serverInstance = GetServerInstance(iPAddress);
if (serverInstance == null)
return false;
return serverInstance.CallMethod(ListNodeDetails, ListMethod);
}
The service model
public bool CallMethod(List<Variant> ListNodeDetails, List<string> ListMethod)
{
try
{
if (_mSession == null)
{
return false;
}
NodeId objectID = NodeId.Parse(ListMethod[0]);
NodeId Methodtype = NodeId.Parse(ListMethod[1]); ;
List<Variant> inputArguments = ListNodeDetails;
List<StatusCode> inputArgumentErrors = null;
List<Variant> outputArguments = null;
StatusCode error = _mSession.Call(
objectID,
Methodtype,
inputArguments,
new RequestSettings() { OperationTimeout = 10000 },
out inputArgumentErrors,
out outputArguments);
if (StatusCode.IsBad(error))
{
Console.Write("Server returned an error while calling method: " + error.ToString());
return false;
}
return true;
}
catch (Exception exception)
{
Console.WriteLine(exception.ToString());
return false;
}
}
At the end it calls some functions using OPC UA to add data.
I have changed it to be ajax function and it works well but only with one list form the lists passed to the method!
I dont know if this is because i read values from kendo box and text box, and they are different types but i tried to stringfy it and it still does not work. On the console both lists are out as strings. So still got a problem with passing the first List "ListNodeDetails"!
$('#AddColumn').click(function () {
var nodeURL = document.getElementById("IDHolder").innerHTML;
var nodeConfig= nodeURL+".CONFIG";
var nodeAdd=nodeURL+".CONFIG.AddColumn";
var nodeName = $("#ColumnName").val().toString();
var nodeType = $("#ColumnType").data("kendoComboBox").value().toString();
var ListNodedet = [nodeName, nodeType];
var Listmet = [nodeConfig, nodeAdd];
var params = {
ListNodeDetails: ListNodedet,
ListMethod: Listmet
};
var url = "/Configuration/CallMethod";
console.log(params); // added sanity check to make sure data is correctly passed
var temp = {
url: "/Configuration/CallMethod",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(params),
success: function (params) {
window.location.replace(params.redirect);
}
};
$.ajax(temp);
})
I want to send in ajax array in js, get it in php as an array and insert into with sql.
My ajax call looks like:
jQuery("#Save").click(function () {
$(".linesView").each(function () {
var action_name = "";
if (window.current_category === "Expenses") {
action_name = "Save_Expenses"
} else if(window.current_category === "Incomes") {
action_name = "Save_Incomes"
}
var line_id = $(this).attr("id").substring(5);
var category = $("#CategoryValue_" + line_id).html();
var date = $("#DateValue_" + line_id).html();
var amount = $("#AmountValue_" + line_id).val();
var repeated = $("#RepeatedValue_" + line_id).html();
var note = $("#NoteValue_" + line_id).val();
var data = json_encode([category,date,amount,repeated,note]);
$.post("AjaxHandler.php", { "action_name": action_name, "data": data }, function () {
//$("#ExpensesId_" + id).css('display', 'none');
});
});
});
The PHP code that needs to get the ajax call and add the data (by sql insert) looks like:
if(isset($_POST['action_name','data'])) {
$action_name = $_POST['action_name'];
$data=json_decode($_POST['data']);
$query = mysql_query("INSERT INTO Expenses (accountid, category, date, amount, repeated) VALUES ('$accountid', '$data[0]', '$data[1]', '$data[2]', '0')");
}
The accountid coming from the top of the page, I already do delete action and it works fine, so the accountid is ok. All others, I don't know.
I tried to do encode and then decode. I am not sure if the syntax is right. Anyway if I didn't write elegant code, please show me how it needs to look. Maybe i need to take each param from the data and not to call data[x]?
Use JSON.stringify()
var data = ([category,date,amount,repeated,note]);
$.post("AjaxHandler.php", { "action_name": action_name, "data": JSON.stringify(data) }, function () {
//$("#ExpensesId_" + id).css('display', 'none');
});
Encode the data array to JSON string using JSON.stringify() in javascript. At server side use json_decode() to decode the data.
jQuery:
jQuery("#Save").click(function() {
$(".linesView").each(function() {
var action_name = "";
if (window.current_category === "Expenses") {
action_name = "Save_Expenses"
} else if (window.current_category === "Incomes") {
action_name = "Save_Incomes"
}
var line_id = $(this).attr("id").substring(5);
var category = $("#CategoryValue_" + line_id).html();
var date = $("#DateValue_" + line_id).html();
var amount = $("#AmountValue_" + line_id).val();
var repeated = $("#RepeatedValue_" + line_id).html();
var note = $("#NoteValue_" + line_id).val();
var data = JSON.stringify([category, date, amount, repeated, note]);
//-----------------^--- Array to JSON string
$.post("AjaxHandler.php", {
"action_name": action_name,
"data": data
}, function() {
//$("#ExpensesId_" + id).css('display', 'none');
});
});
});
PHP :
if(isset($_POST['action_name','data'])){
$action_name = $_POST['action_name'];
$data=json_decode(json_decode($_POST['data']));
//-----^--- decoding JSON string
$query = mysql_query("INSERT INTO Expenses (accountid, category, date, amount, repeated) VALUES ('$accountid', '$data[0]', '$data[1]', '$data[2]', '0')");
}
The MVC that creates the array of strings is
public JsonResult GetInvalidFilesAJAX(JQueryDataTableParamModel param)
{
string[] invalidFiles = new string[] { "one.xls", "two.xls", "three.xls" };
return Json(new
{
Status = "OK",
InvalidFiles = invalidFiles
});
}
And the javascript that should loop through and print out each string is
$.ajax(
{
type: 'POST',
url: 'http://localhost:7000/ManualProcess/GetInvalidFilesAJAX',
success: function (response) {
if (response.Status == 'OK') {
//Use template to populate dialog with text of Tasks to validate
var results = {
invalidFiles: response.InvalidFiles,
};
var template = "<b>Invalid Files:</b> {{#invalidFiles}} Filename: {{invalidFiles.value}} <br />{{/invalidFiles}}";
var html = Mustache.to_html(template, results);
$('#divDialogModalErrors').html('ERROR: The following files have been deleted:');
$('#divDialogModalErrorFiles').html(html);
How do I refer to the string in the array? The way above is not correct. All the example I find seem to be for when the Jason collection has property names.. in my case it is just a key value pair (I guess?)
There is no built in way. You must convert the JSON into an array or loop through the data yourself, e.g,
var data = JSON.parse(jsonString); // Assuming JSON.parse is available
var arr = [];
for (var i = 0, value; (value = data[i]); ++i) {
arr.push(value);
}
Alternatively:
var arr = [];
for (var prop in data){
if (data.hasOwnProperty(prop)){
arr.push({
'key' : prop,
'value' : data[prop]
});
}
}
And then to display it:
var template = "{{#arr}}<p>{{value}}</p>{{/arr}}";
var html = Mustache.to_html(template, {arr: arr});
This is assuming your JSON Object is one level deep.