How to post a Map with $.ajax - javascript

I have a JS function which is supposed to post several Maps that i need in my controller :
var valuesOriginal = new Map();
var valuesEdited = new Map();
var valuesBackup = new Map();
$.each($('#zgImport').serializeArray(), function(i, field) {
if(field.name.substring(0,13) == "userLinesAuto"){
valuesEdited.set(field.name, field.value);
}else if (field.name.substring(0,17) == "userLinesOriginal"){
valuesBackup.set(field.name, field.value);
}else if (field.name.substring(0,9) == "userLines"){
valuesOriginal.set(field.name, field.value);
}
});
$.ajax({
type : 'POST',
url : '<%= importAfterValidationUsers %>',
data : {
original : valuesOriginal,
edited : valuesEdited,
backup : valuesBackup,
formValidationSource : "original"
},
success: function(serverResponse) {
alert("ok");
},
error: function () {
alert("error");
},
timeout: 3000
});
But in my controller my maps are always null
public void importAfterValidationUsers(ResourceRequest request, ResourceResponse response) throws IOException {
Map<String, String[]> users = request.getParameterMap();
Map lala = request.getParameter("original");
}
The request.getParameterMap() contains the "formValidationSource" var but not the map, and request.getParameter("original") returns null.
What do i miss?

Change:
formValidationSource : "original"
TO
"original" : formValidationSource
Edit: Try:
original : JSON.stringify(valuesOriginal)

Related

Accessing a variable in vuejs or javascript

I have this javascript variable, I'm using vuejs.
when I try to access an array field to validate a form, the chrome dev tools returns an error.
var checkItems = {contact_email: "", contact_name: "", contact_phone: "", message: "", subject_id: null, …}
I try to access this way:
if(checkItems.contact_email)
alert("email required");
This is the error:
Property or method "contact_email" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option
If the form fields are empty, I want to detect individually which one is empty and send a custom error for each one, for example:
Name field is empty
The email field is empty
This is my vuejs code:
var locale = '{{ $lang }}'; //'es-ES',
var V_Alerts = new Vue({
el : '#v-alerts',
data : {
types : ['danger', 'warning', 'success', 'info'],
alerts : [
]
},
methods : {
add : function(type, content, opts)
{
this.alerts.push({
type : type,
content : content,
opts : opts
});
},
addSuccess : function(content, opts){
this.add('success',content, opts)
}
}
});
var new_ticket = new Vue({
el : '#create_ticket',
data : {
uploading : false,
submitting : false,
subject_id : null,
message : '',
errors: [],
},
methods : {
validation: function (params)
{
return {
contact_email : IsEmail(params.contact_email),
contact_name : !!params.contact_name.trim(),
message : !!params.message.trim(),
subject_id : params.subject_id && !!params.subject_id.trim(),
captcha : params.captcha !== 0
}
},
isValid : function(params)
{
var validation = this.validation(params);
return Object.keys(validation).every(function (key) {
return validation[key];
});
},
restart : function()
{
this.uploading = false;
this.submitting = false;
this.subject_id = null;
this.$refs.subjects.restart();
this.$refs.uploads.restart();
$('#message').text('');
$('#order_number').val('');
$('#contact_email').val('');
$('#contact_name').val('');
$('#contact_phone').val('');
$('#message').val('');
grecaptcha.reset();
},
onSubjectSelect : function(subject_id){
this.subject_id = subject_id;
},
_onSubjectsLoaded : function(subjects){
emitOnWidgetContentChanged();
},
createTicket : function(e)
{
var params = {
contact_email : $('#contact_email').val(),
contact_name : $('#contact_name').val(),
contact_phone : $('#contact_phone').val(),
message : $('#message').val(),
subject_id : this.subject_id,
message_files : this.$refs.uploads.completed_ids.join(','),
captcha : grecaptcha.getResponse()
};
#if (Input::has('public_token'))
params.public_token = '{{ Input::get('public_token') }}';
#endif
if ($('#order_number').val() != '')
params.contact_orders = $('#order_number').val();
if (!this.isValid(params))
{
var checkItems = params;
if(checkItems.contact_email)
alert("email");
alert('{{ addslashes(trans('common.empty_or_error_input')) }}');
return;
}
this.submitting = true;
// only ie11 need this manuall
params._token = '{!! csrf_token() !!}';
AjaxServices.post('createTicket', params, function(error, result)
{
this.submitting = false;
if (error)
{
alert('{{ addslashes(trans('accounts/tickets.error_creating_ticket')) }}');
grecaptcha.reset();
}
else
{
alert('#'+ result.ticket_id +' - {{ addslashes(trans('accounts/tickets.new_ticket_created_ok')) }} :)');
V_Alerts.addSuccess('#'+ result.ticket_id +' - {{ addslashes(trans('accounts/tickets.new_ticket_created_ok')) }}');
this.restart();
emitOnWidgetContentChanged();
}
}.bind(this));
},
onUploadComplete : function(ids){
this.uploading = false;
emitOnWidgetContentChanged();
},
onUploadStarted : function(){
this.uploading = true;
setTimeout(emitOnWidgetContentChanged,1);
},
onItemDeleted : function(){
},
onFilesSelected : function(){
}
}
});
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$(document).ready(function(){
//new_ticket.restart();
});
You are not utilizing Vue properly. The error you are receiving stems from not defining your properties in the data object. You cant just return them as you are in the validation method because Vue is looking for a data object called contact_email, or a method called contact_email() or even a computed property called contact_email.
data : {
// define your properties here
contact_email: '';
},
methods: {
yourMethod: function(){
//modify your properties here
this.contact_email: IsEmail(params.contact_email)
}
}

Value returned by service not update in controller's variable in angularjs

function getList() {
SubCategoryService.getAllList().then(function (response) {
$scope.subCategoryList = response.data;
$scope.subCategoryDetailsList = [];
var subCategoryDetails = [];
for(var i=0; i < $scope.subCategoryList.length; i++) {
var subCategoryListData = $scope.subCategoryList[i];
var subcategory = {
'id' : subCategoryListData.id,
'category' : '',
'name' : subCategoryListData.name,
'created_on' : subCategoryListData.created_on,
'modified_on' : subCategoryListData.modified_on,
'is_deleted' : subCategoryListData.is_deleted,
'is_active' : subCategoryListData.is_active,
'image_name' : subCategoryListData.image_name,
'image_path' : subCategoryListData.image_path
}
CategoryService.getCategoryById(subCategoryListData.category_id).then(function(response1) {
console.log(response1.data);
subcategory.category = response1.data;
}, function(error) {
swal("Error", error.data, "error");
})
subCategoryDetails.push(subcategory);
}
console.log(JSON.stringify(subCategoryDetails));
}, function (error) {
swal("Error", "Something went wrong", "error");
});
}
CategoryService:
this.getCategoryById = function(id) {
return $http({
url: globalUrl.baseurl + 'category/getCategoryById/' + id,
method: 'GET'
})
}
in the above code i am tring to fetch data from CategoryService service and it successfully return the data within the CategoryService.getCategoryById function. Now i am trying to assign returned value by service to subcategory.category which is present in controller. but my problem is it is not updateing the value in subcategory.category.
my guess is:
you are pushing the new variabile inside the array BEFORE the API call is executed (because of the js callback), can you try something like:
CategoryService.getCategoryById(subCategoryListData.category_id)
.then(function(response1) {
console.log(response1.data);
subcategory.category = response1.data;
// PUSHING AFTER API RETURNS THE VALUE
subCategoryDetails.push(subcategory);
}, function(error) {
swal("Error", error.data, "error");
})
// subCategoryDetails.push(subcategory);

$.post always getting null values into server

Ok, this might be simple, I'm having a simple $.post call to server sending string array as parameters..
$.get('/home/ReadCalPacTagValue', data, function (data) {
data = $.parseJSON(data);
if (data.length != 0) {
var ReadFromDb = data[0]["PushToDb"].replace('PushToDb','ReadFromDb');
var DBAckno = ReadFromDb.replace('ReadFromDb', 'DataAck');
var FIdTag = ReadFromDb.replace('ReadFromDb', 'FluidTypeId');
var UserIdTag = ReadFromDb.replace('ReadFromDb', 'UserId');
var UniqueIdTag = ReadFromDb.replace('ReadFromDb', 'UniqueRecordId');
var dbconnTag = ReadFromDb.replace('ReadFromDb', 'DatabaseConnectionString');
updateTags = [dbconnTag,FIdTag,ReadFromDb, UserIdTag,UniqueIdTag];
actionvalue = ["", fluidtypeid, '1', userid, uniqueID];
var data_Tags = { updateTags: updateTags, actionvalue: actionvalue }
$.post('/home/WriteCalPacTagValue', data_Tags, function (response) {
//var Path = "Config/16_CalPac/" + FluidType + "/" + metername + "/" + FileName
//$.cookie('FileName', FileName, { expires: 7, path: '/' });
//$.cookie('FilePath', Path, { expires: 7, path: '/' });
//$.cookie('ModuleName', "CalPac", { expires: 7, path: '/' });
//window.open('../home/CalPac', '_blank');
});
} else {
swal("Error !", "Data operation tag not binded for this product", "warning");
}
})
my problem is, every time it makes $.post call, server is getting null values int prarameters..
public void WriteCalPacTagValue(string[] updateTags, string[] actionValue)
{
string[] writetags = { };
DanpacUIRepository objNewTag = new DanpacUIRepository();
if (updateTags.Count() > 0)
{
actionValue[0] = ConfigurationManager.AppSettings["DBString"].ToString();
for (int i = 0; i < updateTags.Count(); i++)
{
writetags = updateTags[i].Replace("<", "").Replace(">", ">").Split('>');
objNewTag.WriteTag(writetags, actionValue[i]);
}
}
}
I'm not getting what I've done wrong here.. whereas same function is working from another JS file with some difference string into array updateTags.
any help?
Having
public class DataTags
{
public string[] UpdateTags { get; set; }
public string[] ActionValue { get; set; }
}
At the server: Change the method to this
[HttpPost()]
public void WriteCalPacTagValue([FromBody]DataTags data_Tags)
{
}
At the client: call it
$.ajax({
type: 'POST',
url: '/home/WriteCalPacTagValue',
data: data_Tags,
success: function (response) {
//your code
}
});
Also you can send the whole data as json string using data: JSON.stringify(data_Tags), in javascript code the change the WriteCalPacTagValue to accept a single string at the parameter and deserialize it in C# code at the server side.
EDIT if you cannot change the server side code, you may follow this as stated in the comments.

How to make it async in javascript or node?

var responseArr = new Array();
async.each(response, function (value, k) {
if(isDateFlag)
{
var defaultValue = value.auction_id;
grpArray.push(value.title);
var postData = {
parent_id : parent_id,
defaultValue : defaultValue,
isDateFlag : isDateFlag,
search_text : search_text
}
getChildNotificationList(postData, function (childArrayData) {
//Creating the response array
responseArr.push({
'notification_id' : childArrayData['notification_id'],
'notification_text' : childArrayData['notification_text']
});
});
}
});
return responseArr;//Blank Array
I want to return the final responseArr after manipulating it from child data query. It return blank array because it does not wait for the query response.
So how it can be async. Thanks
I referred http://justinklemm.com/node-js-async-tutorial/ and https://github.com/caolan/async.
This happens because the control goes on executing the code since javascript is synchronous. For getting the expected result modify the code as below:
var responseArr = new Array();
async.each(response, function (value, k) {
if(isDateFlag){
var defaultValue = value.auction_id;
grpArray.push(value.title);
var postData = {
parent_id : parent_id,
defaultValue : defaultValue,
isDateFlag : isDateFlag,
search_text : search_text
}
getChildNotificationList(postData, function (childArrayData) {
//Creating the response array
responseArr.push({
'notification_id' : childArrayData['notification_id'],
'notification_text' : childArrayData['notification_text']
});
k();
});
} else {
k();
}
}, function (err) {
if (err) {
console.log(err);
} else {
return responseArr;
}
});
The above code is inside a function block. You could get the result by calling the function.
Including the answer using async.map:
async.map(response, function (value, k) {
if(isDateFlag){
var defaultValue = value.auction_id;
grpArray.push(value.title);
var postData = {
parent_id : parent_id,
defaultValue : defaultValue,
isDateFlag : isDateFlag,
search_text : search_text
}
getChildNotificationList(postData, function (childArrayData) {
k(null, {
'notification_id' : childArrayData['notification_id'],
'notification_text' : childArrayData['notification_text']
});
});
} else {
k(null, {
'notification_id' : '',
'notification_text' : ''
});
}
}, function(err, results){
// results is now an array
return results;
});

Parse cloud code loop is only going through first instance

I want the following loop to go through every instance of matchCenterItem, yet for some reason, it pings ebay using the properties of only the first instance. The console logs at the end of the function however, loop through all instances and log their respective properties.
Parse.Cloud.define("MatchCenterTest", function(request, response) {
var matchCenterItem = Parse.Object.extend("matchCenterItem");
var query = new Parse.Query(matchCenterItem);
var promises = [];
query.limit(10);
query.find().then(function(results) {
for (i=0; i<results.length; i++) {
url = 'http://svcs.ebay.com/services/search/FindingService/v1';
promises.push(Parse.Cloud.httpRequest({
url: url,
params: {
'OPERATION-NAME' : 'findItemsByKeywords',
'SERVICE-VERSION' : '1.12.0',
'SECURITY-APPNAME' : '*App ID goes here*',
'GLOBAL-ID' : 'EBAY-US',
'RESPONSE-DATA-FORMAT' : 'JSON',
'REST-PAYLOAD&sortOrder' : 'BestMatch',
'paginationInput.entriesPerPage' : '3',
'outputSelector=AspectHistogram&itemFilter(0).name=Condition&itemFilter(0).value(0)' : results[i].get('itemCondition'),
'itemFilter(1).name=MaxPrice&itemFilter(1).value' : results[i].get('maxPrice'),
'itemFilter(1).paramName=Currency&itemFilter(1).paramValue' : 'USD',
'itemFilter(2).name=MinPrice&itemFilter(2).value' : results[i].get('minPrice'),
'itemFilter(2).paramName=Currency&itemFilter(2).paramValue' : 'USD',
//'itemFilter(3).name=LocatedIn&itemFilter(3).Value' : request.params.itemLocation,
'itemFilter(3).name=ListingType&itemFilter(3).value' : 'FixedPrice',
'keywords' : results[i].get('searchTerm'),
},
// success: function (httpResponse) {
// // parses results
// var httpresponse = JSON.parse(httpResponse.text);
// response.success(httpresponse);
// console.log('MatchCenter Pinged eBay dude!');
// },
// error: function (httpResponse) {
// console.log('error!!!');
// response.error('Request failed with response code ' + httpResponse.status);
// }
}));
console.log(results[i].get('itemCondition'));
console.log(results[i].get('maxPrice'));
console.log(results[i].get('minPrice'));
console.log(results[i].get('searchTerm'));
}
});
Parse.Promise.when(promises).then(function(results) {
var httpresponse = JSON.parse(httpResponse.text);
response.success(httpresponse);
}, function(err) {
console.log('error!!!');
});
});
This is because the http request is asynchronous, and you're calling response.success in the completion handler for the first (and all) requests. Use the promise syntax and only complete when they are done. Simplified concept:
var promises = [];
for (...) {
promises.push(Parse.Cloud.httpRequest({...})); // no success/error params
}
Parse.Promise.when(promises).then(function(results) {
response.success(...);
}, function(err) {
});

Categories