I am creating some JSON data to be validated through an ajax call.
Here's my constructed JSON :
{"telephone1":"66",
"telephone2":"66",
"fax":"66",
"mobilePhone":"66",
"dateEffectiveChangementAdresseOuTel":"66",
"adresse1IdentiqueAdresse2":true}
Here's the one obtained :
{ "adresse1IdentiqueAdresse2" : true,
"dateEffectiveChangementAdresseOuTel" : "66",
"fax" : "66",
"mobilePhone" : "66",
"telephone1" : "66",
"telephone2" : "66"
}
As you can notice, my key are reordered in alphabetical order, which I do not want.
This causes errors to be returned to the page in the 2nd order, but I need them in the 1st order. I want my error summary (Html.ValidationSummary) to follow the errors on the page (1st error = 1st field in error).
Is there any way to preserve my original order?
Or someway to bypass this?
edit
var coord = {
telephone1: $("#Telephone1").val(),
telephone2: $("#Telephone2").val(),
fax: $("#Fax").val(),
mobilePhone: $("#MobilePhone").val(),
dateEffectiveChangementAdresseOuTel: $("#DateEffectiveChangementAdresseOuTel").val(),
adresse1IdentiqueAdresse2: $("#Adresse1IdentiqueAdresse2").is(":checked")
};
$.ajax({
type: 'POST',
url: urlControleur + '_ActionTransmettre',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(coord),
success: function (data, textStatus, jqXHR) {
if (typeof (data) == "string") {
window.location = data
MsgErreur("");
}
else {
ListeMsgErreur(data);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
handleAjaxError(XMLHttpRequest, "M000017");
}
});
ajax call return (in error)
["The value {0} is not valid for Effective.",
"Le numéro saisi doit respecter le format 999 999-9999",
"Le numéro saisi doit respecter le format 999 999-9999",
"Le numéro saisi doit respecter le format 999 999-9999 ou, si vous devez saisir un numéro de poste, le format est 999 999-9999 x 9999999.",
"Le numéro saisi doit respecter le format 999 999-9999"]
It's impossible to reorder the return as is.
I would review the code that returns the json. this is where it's happening. if you cannot change the code which renders the JSON then remodel the data before passing it along
return {
telephone1: theJson.telephone1,
telephone2: theJson.telephone2,
fax: theJson.fax,
mobilePhone: theJson.mobilePhone,
dateEffectiveChangementAdresseOuTel: theJson.dateEffectiveChangementAdresseOuTel,
adresse1IdentiqueAdresse2: thsJson.adresse1IdentiqueAdresse2
};
Related
How get full objets with pointers?.
I have this
ParseObject { _objCount: 4, className: 'Task', id: 'I593WXO24i' }
Update:
This is my code
var taskQuery = new Parse.Query("Task");
taskQuery.get(req.params.task,{
success: function(task){
console.log(task);
},
error: function(error){
errorCodeFor(res, "not_found", "item.task", "Task was not found");
}
});
But when console.log(task).I have a pointers.I want the full object.
You can use the include method:
https://docs.parseplatform.org/js/guide/#relational-queries
It would be something like this:
query.include('myPointerFieldName');
Before, I'm used Ajax to save events and it was ok. But now, with the v4, my code doesn't work anymore like if Ajax doesn't recognise anymore. Does someone have the solution ?
My code in v3.09
eventDrop: function(event, delta, revertFunc) { // Déplacement d'une événement
var date = new Date();
if (($.fullCalendar.formatDate(event.start, "M")>=date.getMonth()+1 && $.fullCalendar.formatDate(event.start, "D")>=date.getDate()) || ($.fullCalendar.formatDate(event.start, "M")>date.getMonth()+1)) {
$.ajax({
url: 'php/update_events.php',
data: 'title='+ event.title+'&start='+ $.fullCalendar.formatDate(event.start, "YYYY-MM-DD HH:mm:ss") +'&end='+ $.fullCalendar.formatDate(event.end, "YYYY-MM-DD HH:mm:ss") +'&id='+ event.id ,
type: "POST",
success: function(json) {
$('#script-info').show();
setTimeout('divOff()',1000);
}
});
} else {
alert ("Vous ne pouvez pas déplacer une absence à une date antérieure à la date du jour.");
revertFunc();
}
},
My code in v4
eventDrop: function(info) {
var date = new Date();
if (calendar.formatDate(info.event.start, {month: 'numeric'})>=date.getMonth()+1 && calendar.formatDate(info.event.start, {day: 'numeric'})>=date.getDate()) {
$.ajax({
url: 'php/update_events.php',
data: 'title="Test"',
type: "POST",
success: function(json) {
$('#script-info').show();
setTimeout('divOff()',1000);
}
});
alert('Ok');
} else {
alert('Vous ne pouvez pas déplacer un créneau de sport à une date antérieure à la date du jour.');
info.revert();
}
}
You give me the solution !
I've removed script src='lib/jquery.min.js' script.
How stupid i am ! So, it's works again. Sorry for the inconvenient
Not sure if this helps others, but if you want to save events via ajax in V4 this is what I did assuming calEvent is coming from sort of event (click, drag etc) in V4:
eventClick: function (calEvent) { var cloned= jQuery.extend(true, {},calendar.getEventById( calEvent.event.id ));
cloned.start=clientEvents[i].start;
cloned.end=clientEvents[i].end;
cloned.title=clientEvents[i].title
delete cloned.jsEvent;
delete cloned.view;
Above shows how you can clone the event (needs jquery) and then add custom properties, remove some unneeded properties and ultimately turn this into JSON to send back to server.
HTH
I'm new with promise. I'm trying to receive an answer from the service. LoginController call LoginService.
I debugged it and the controller receive undefined answer, and then I can check that the service return te value.
So I need that the controller wait for the service answer. I tried to use Promise but didn't work.
I'm working with Cordova Sqlite.
Controller
function iniciarSesion() {
loginService.iniciarSesion(vm.username, vm.password, dispositivo, registration)
.then(function(sesion) {
console.log("dataControllee:"+JSON.stringify(sesion)); // receive undefined
if(sesion.success > 0){
$ionicHistory.nextViewOptions({
disableAnimate: true,
disableBack: true
});
if(sesion.success == 1){
$location.path("/complejo/home");
$state.go('app.home');
}
else if(sesion.success == 2){
$location.path("/usuario/home-usuario");
$state.go('app.homeusuario');
}
else{
$location.path("/login");
$state.go('app.login', {
registration: registration
});
}
}
else{
var alertPopup = $ionicPopup.alert({
title: 'Hubo un problema',
template: 'Hubo un problema al conectarse al servidor. Intente nuevamente.'
})
}
})
.catch(function(e){
var alertPopup = $ionicPopup.alert({
title: 'Hubo un problema',
template: e
});
});
}
Service
/funcion para iniciar sesión
function iniciarSesion(username, password, dispositivo, registration) {
return remoteDataService.iniciarSesion(username, password, dispositivo, registration)
.then(function(respuesta) {
var datos = respuesta.data;
var status = respuesta.status;
if(status == 200){
var exito = datos.success;
if(exito == 0){
return $q.reject(datos);
}
else if(exito == 1 || exito == 2){
return new Promise(function (res, rej) {
datos.registration = registration;
res(obtenerDatos(datos));
});
}
}
return $q.reject('Hubo un problema al conectarse al servidor. Intente nuevamente.');
})
.catch(generarError);
}
function obtenerDatos(data, status, headers, config){
if (data.token) {
// Agregamos el token al header para cada futura consulta al servidor
$http.defaults.headers.common.Authorization = 'Bearer ' + data.token;
console.log("Obtengo los datosssss");
db = window.sqlitePlugin.openDatabase({name: 'example.db', location: 'default'});
// guardamos en la base de datos SQL el token y el id del usuario
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS exampleTable (id INTEGER PRIMARY KEY, clave text NOT NULL, valor TEXT NOT NULL, UNIQUE (clave) ON CONFLICT REPLACE)');
tx.executeSql('INSERT OR REPLACE INTO exampleTable(clave,valor) VALUES (?,?)', ['token', data.token]);
tx.executeSql('INSERT OR REPLACE INTO exampleTable(clave,valor) VALUES (?,?)', ['usuario', data.identificadorUsuario]);
tx.executeSql('INSERT OR REPLACE INTO exampleTable(clave,valor) VALUES (?,?)', ['registrationId', data.registration]);
}, function(error) {
$q.reject('hubo un error al iniciar sesión.');
}, function() {
return new Promise(function (res, rej) {
console.log("dataa:"+JSON.stringify(data)); //get the value AFTER the loginController receive undefined answer
res(data);
});
});
}
else {
return $q.reject('Hubo un problema al conectarse al servidor. Intente nuevamente.');
}
}
//generar error si hubo un problema
function generarError(e){
console.log("hasta acá esta definido4: "+JSON.stringify(e));
debugger;
if (e.message) {
return $q.reject(e.message);
}
return $q.reject('Hubo un problema al conectarse al servidor. Intente nuevamente.');
}
So.. How can I solve my problem? May be I can refactor my code.
Thanks!
The problem is that obtenerDatos doesn't return a Promise when data.token is truthy
Wrap the WHOLE body of that function in a new Promise that is returned from that function. this also means you don't need to use $q.reject
function obtenerDatos(data, status, headers, config){
return new Promise(function (res, rej) {
if (data.token) {
// Agregamos el token al header para cada futura consulta al servidor
$http.defaults.headers.common.Authorization = 'Bearer ' + data.token;
console.log("Obtengo los datosssss");
db = window.sqlitePlugin.openDatabase({name: 'example.db', location: 'default'});
// guardamos en la base de datos SQL el token y el id del usuario
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS exampleTable (id INTEGER PRIMARY KEY, clave text NOT NULL, valor TEXT NOT NULL, UNIQUE (clave) ON CONFLICT REPLACE)');
tx.executeSql('INSERT OR REPLACE INTO exampleTable(clave,valor) VALUES (?,?)', ['token', data.token]);
tx.executeSql('INSERT OR REPLACE INTO exampleTable(clave,valor) VALUES (?,?)', ['usuario', data.identificadorUsuario]);
tx.executeSql('INSERT OR REPLACE INTO exampleTable(clave,valor) VALUES (?,?)', ['registrationId', data.registration]);
}, function(error) {
rej('hubo un error al iniciar sesión.');
}, function() {
console.log("dataa:"+JSON.stringify(data)); //get the value AFTER the loginController receive undefined answer
res(data);
});
}
else {
rej('Hubo un problema al conectarse al servidor. Intente nuevamente.');
}
});
}
another code change I'd recommend - to avoid the promise constructor anti-pattern
Service
function iniciarSesion(username, password, dispositivo, registration) {
return remoteDataService.iniciarSesion(username, password, dispositivo, registration)
.then(function(respuesta) {
var datos = respuesta.data;
var status = respuesta.status;
if (status == 200) {
var exito = datos.success;
if (exito == 0) {
// use throw to reject the Promise returned by .then
throw datos;
} else if (exito == 1 || exito == 2) {
datos.registration = registration;
// return the obtenerDatos Promise, no need to create one
return obtenerDatos(datos);
}
}
// use throw to reject the Promise returned by .then
throw 'Hubo un problema al conectarse al servidor. Intente nuevamente.';
})
.catch(generarError);
}
I am seeing 2 types of JSON format out there and getting really confused.
I a trying to do the following:
I have an excel model with a range
Type RV
MRC 10
CRC 20
CVA 30
OpRisk 0
Using ExCelToWeb vba function from cDataSet (http://ramblings.mcpher.com/Home/excelquirks/json/excel-json-conversion), I convert this range to a JSON string. Output is as follows:
{ "cDataSet":[
{
"Type":"MRC",
"RV":10
},
{
"Type":"CRC",
"RV":20
},
{
"Type":"CVA",
"RV":30
},
{
"Type":"OpRisk",
"RV":0
}
]}
I save this into a text file called myData.json
In Default.aspx.cs, I have
[WebMethod]
public static String GetDataJSON(){
String myvar = File.ReadAllText("C:\\Users\\Serge\\Downloads\\GoogleChartExample\\GoogleChartExample\\myData.json");
return myvar;
}
I call the function from Java Script in Default.aspx
google.load('visualization', '1', { packages: ['corechart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'Default.aspx/GetDataJSON',
contentType: 'application/json',
data: {},
async: false,
success:
function (response) {
console.log(response.d);
var data = new google.visualization.DataTable(response.d);
var csv = google.visualization.dataTableToCsv(data);
console.log(csv);
new google.visualization.ColumnChart(document.getElementById('myChart1')).draw(data, { title: "MyChart1" });
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus + '\n' + errorThrown);
if (!$.browser.msie) {
console.log(jqXHR);
}
}
});
}
=> console.log(response.d) outputs my JSON string exactly as intended
=> console.log(csv) does not output anything
=> the google chart outputs a red box saying “Table has no columns”
I understand that there are 2 types of JSON format. The one that google has in its example has "cols": [ , and "rows": [ . Does it mean that Google Chart / Dataset is not compatible with my format? Is there anyway for me to convert from one to the other?
Would I be better not to use JSON and export from excel -> cvs => a C# array -> a google dataset?
Thank you very much.
Serge
You are my last chance :(. Im trying do work a paging grid with mvc pattern.
The grid show the fisrt 21 records, but not refresh when click "next" pagingtoolbar icon.
All my codes are detailed below:
The Store:
Ext.define('CRUDManantiales.store.grid.AbmUsuarios', {
extend: 'Ext.data.Store',
model: 'CRUDManantiales.model.grid.AbmUsuarios',
proxy: {
type: 'ajax',
url: 'resources/bundles/usuarios/generarJsonTodos.php',
reader: {
type: 'json',
root: 'data',
successProperty: 'success',
totalProperty: 'total'
}
}
});
The main view code:
Ext.define('CRUDManantiales.view.grid.AbmUsuarios', {
// [..........]
initComponent: function () {
this.store = 'grid.AbmUsuarios';
this.dockedItems = [{
xtype: 'pagingtoolbar',
store: this.store,
beforePageText: 'Página',
afterPageText: 'de {0}',
displayMsg: 'Mostrando {0} - {1} de {2} registros',
emptyMsg: 'No hay datos que mostrar',
dock: 'bottom',
displayInfo: true,
pageSize: 21
}];
this.callParent(arguments);
}
});
I wasted four days in this code, appreciate your assistance. Thanks !!
Thanks for all. The problem has been resolute. The fail was that i was using POST array in my PHP script and needed use GET method. :)