I have a form that is used by admin to modify user details and before submitting I want to modify the structure of the data ( flat array) to be a json objects with some level of hierarchy.
User = { username: 'myUserName' , roles : [ {role : 'ADMIN'},{role: USER} ], etc..}
so to do this in my client web page I've done this :
$("#submitUpdate").click(function() {
var dataAsJson = JSON.stringify(function(){
//user
var o = {};
//spring token
var tk = {};
//var usrname
var un={};
var formData = $("#updateForm").serializeArray();
$.each(formData, function(k, v) {
if (o[v.name] !== undefined) {
if (!o[v.name].push) {
o[v.name] = [ o[v.name] ];
}
o[v.name].push(v.value || '');
} else {
if (v.name === 'userRoles') {
if (v.value !== undefined) {
var a = [];
$.each(v.value.split(','), function(i, rl) {
var r = {};
r.role = rl;
a.push(r);
});
o[v.name] = a;
} else
o[v.name] = [];
} else if (v.name === '_csrf') {
tk[v.name] = v.value;
} else if (v.name === '_username') {
un[v.name] = v.value || '';
} else
o[v.name] = v.value || '';
}
});
var obj = [];
obj.push(tk); obj.push(un); obj.push(o);
return obj;
}());
$("#updateForm").ajaxSubmit({
url : "${userUpdateCtx}",
data: dataAsJson,
beforeSubmit : function(formData, jqForm, options) {
},
success : function(msg) {
$table.bootstrapTable('refresh');
},
error : function(e) {
showError(e);
}
});
});
the problem is that the for is never gets submit and I get ERROR 400
HTTP Status 400 -
Type Report Status
message
Description request sent by the client was syntactically incorrect.
I've tried to put the processing code inside beforeSubmit and return the string JSON.stringify(obj) but this don't seem to work either.
how could I make this work ?.
EDIT
Thanks to comments below I've fixed the dataAsJson but still having the same error, the dump of the request looks like this (cut it off too long ):
URL de la requête : http://localhost:8080/WebMarket/admin/users/update?_csrf=9323a5ac-9a49-436f-a799-89b4814fb309&enabled=1&firstName=Steve&lastName=Jobs&_username=manager&username=manager&password=%242a%2410%24BVRCqPA6.qdvs%2Fma0uH6Here4ozKudoHyH2OFz2xc3.FfwL%2FEyXz6&userRoles=ROLE_MANAGER&0=%5B&1=%7B&2=%22&3=_&4=c&5=s&6=r&7=f&8=%22&9=%3A&10=%22&11=9&12=3&13=2&14=3&15=a&16=5&17=a&18=c&19=-&20=9&21=a&22=4&23=
Méthode de la requête : POST
Code d'état : HTTP/1.1 400 BAD REQUEST
Related
I have an array which is initialized with
var detail = [];
// Have also tried var detail = new Array;
Through the rest of my code, I loop through a data set creating an object in the following manner
while(true) {
var tempObj = {
qty : "",
size : "",
adr : "",
dir : ""
}
// Some Logic
tempObj.qty = val;
tempObj.size = val;
tempObj.adr = val;
tempObj.dir = val;
detail.push(tempObj);
}
Then when I attempt to JSON.Stringify my detail array to send through an AJAX request, it returns a blank array []. This can also be seen in the below screenshot of the console.
Note: The indent at the bottom calling out the prototype as an object is because the screenshot is from the object I am attempting to send to my server. There is other non array based data in that object. I want to stringify the array so it properly sends to the server.
What is causing this behavior and how can I correct it?
Edit 1: Execution of JSON.stringify(detail)
var requestObj = {
field1: “a”,
field2: “b”,
field3: “c”,
data: JSON.stringify(detail)
}
Edit 2: Add full block of code
$("#submit-button").click(function() {
var reqDate = $("#reqDate").val();
var wonum = $("#wonum").val();
var svc = $("#svc").val();
var complaint = $("#complaint").val();
var comments = $("#comm").val();
var detail = new Array;
var topValid = false;
$(".tb-rw").each(function() {
var qty = $(this).find(".quantity");
var size = $(this).find(".size");
var adr = $(this).find(".address");
var dir = $(this).find(".direction");
var mgk = $(this).find(".mgKey");
var tempObj = {};
if(fail == true || topValid == true) {
alert("Please Make Sure all Inputs are Filled Out");
return;
} else {
//tempArr.push(qty.val(), size.val(), dir.val());
tempObj.qty = qty.val();
tempObj.size = size.val();
tempObj.dir = dir.val();
}
findSimilarJobs(adr.val(), mgk.val(), function(data) {
if(data != "clear") {
console.log("FAILED VALIDATION");
console.log(data);
adr.css('border-color', 'red');
alert("Please Make Sure all Addresses are Valid");
return;
} else {
//tempArr.push(adr.val());
tempObj.adr = adr.val();
}
detail.push(tempObj);
});
});
console.log("Preparing to send!");
var requestData = {
"requestedDate": reqDate,
"svc": svc,
"wonum": wonum,
"complaint": complaint,
"comment": comments,
"data": JSON.stringify(detail)
};
console.log(requestData);
console.log(JSON.stringify(detail));
});
Stringify should be all lower case like this stringify, otherwise is won't work. So like, this JSON.Stringify(detail) should be this JSON.stringify(detail)
your tempObj is JSON object and it should have key:value like below
while(true) {
var tempObj = {
qty : "",
size : "",
adr : "",
dir : ""
}
// or you can create empty object
// var tempObj = {};
tempObj.qty = val;
tempObj.size = val;
tempObj.adr = val;
tempObj.dir = val;
detail.push(tempObj);
}
My Code
I want to make a multiple connection to a telnet console. This project is for Teamspeak and Teamspeak just communicate with telnet. I´ve a object that create a telnet connection as socket with the net lib. If we have just one instance to connect all works fine and I get the serverlist over the telnet connection back. But if I´ve two instance he says invalid loginname or password. That login informations are correct and he also try just to connect to one server.
My Class:
/*
Teamspeak query client class
#instance: Instance object of the teamspeak query client
*/
function TeamspeakQueryClient(instance) {
events.EventEmitter.call(this);
var $this = this,
socket = net.connect(instance.port, instance.ip),
reader = null,
skipLines = -2,
queue = [ ],
executing = null,
server = null;
this.Type = 'Unknown';
this.Id = null;
this.Connected = false;
this.Banned = false;
/*
Socket settings
*/
socket.setKeepAlive(true, 60000);
/*
Socket connect to the teamspeak instance
*/
socket.on("connect", function() {
reader = LineInputStream(socket);
reader.on("line", function(line) {
var s = line.trim();
console.log(line);
// Skipp the first lines
if(skipLines < 0){
if(line === 'TS3') {
this.Type = 'Teamspeak';
};
skipLines++;
if(skipLines === 0) {
checkQueue();
if(server === null) {
$this.SendCommand("login", {client_login_name: instance.client, client_login_password: instance.password}, function(err, response, rawResponse) {
console.log(err);
if(err === null) {
if(err.id === 3329) {
$this.Banned = true;
};
$this.CloseSocket();
} else {
$this.SendCommand("serverlist", null, function(err, response, rawResponse){
console.log(response);
if(response[0] === undefined) {
console.log('1 server');
} else {
console.log('mehrere server');
};
//console.log(rawResponse);
/*cl.send("clientlist", function(err, response, rawResponse){
console.log(util.inspect(response));
});*/
});
};
});
} else {
console.log(server);
};
};
return;
};
// Parse server request
var response = undefined;
if(s.indexOf("error") === 0){
response = parseResponse(s.substr("error ".length).trim());
executing.error = response;
if(executing.error.id === 0) delete executing.error;
if(executing.cb) executing.cb.call(executing, executing.error, executing.response,
executing.rawResponse);
executing = null;
checkQueue();
} else if(s.indexOf("notify") === 0){
s = s.substr("notify".length);
response = parseResponse(s);
$this.emit(s.substr(0, s.indexOf(" ")), response);
} else if(executing) {
response = parseResponse(s);
executing.rawResponse = s;
executing.response = response;
};
});
$this.emit("connect");
});
/*
Socket error
*/
socket.on("error", function(err){
log.LogLine(1, 'TeamspeakQueryClient: We got a error');
log.LogLine(1, 'Message: '+err);
$this.emit("error", err);
});
/*
Socket close
*/
socket.on("close", function(){
log.LogLine(3, 'TeamspeakQueryClient: Socket from '+instance.alias+' closeing...');
$this.emit("close", queue);
});
/*
Function to send a custom command to the telnet console
*/
TeamspeakQueryClient.prototype.SendCommand = function SendCommand() {
var args = Array.prototype.slice.call(arguments);
//console.log(args);
var options = [], params = {};
var callback = undefined;
var cmd = args.shift();
args.forEach(function(v){
if(util.isArray(v)){
options = v;
} else if(typeof v === "function"){
callback = v;
} else {
params = v;
}
});
var tosend = tsescape(cmd);
options.forEach(function(v){
tosend += " -" + tsescape(v);
});
for(var k in params){
var v = params[k];
if(util.isArray(v)){ // Multiple values for the same key - concatenate all
var doptions = v.map(function(val){
return tsescape(k) + "=" + tsescape(val);
});
tosend += " " + doptions.join("|");
} else {
tosend += " " + tsescape(k.toString()) + "=" + tsescape(v.toString());
}
}
queue.push({cmd: cmd, options: options, parameters: params, text: tosend, cb: callback});
if(skipLines === 0) checkQueue();
};
/*
Function to close the socket
*/
TeamspeakQueryClient.prototype.CloseSocket = function CloseSocket() {
socket.destroy();
$this.emit("close");
};
/*
Function to parse a string to a object
#s: String of the object that will be parsed
#return: Object of the parsed string
*/
function parseResponse(s){
var response = [];
var records = s.split("|");
response = records.map(function(k){
var args = k.split(" ");
var thisrec = { };
args.forEach(function(v) {
if(v.indexOf("=") > -1) {
var key = tsunescape(v.substr(0, v.indexOf("=")));
var value = tsunescape(v.substr(v.indexOf("=")+1));
if(parseInt(value, 10) == value) value = parseInt(value, 10);
thisrec[key] = value;
} else {
thisrec[v] = "";
};
});
return thisrec;
});
if(response.length === 0) {
response = null;
} else if(response.length === 1) {
response = response.shift();
};
return response;
};
/*
Function to write commands into the socket
*/
function checkQueue() {
if(!executing && queue.length >= 1){
executing = queue.shift();
socket.write(executing.text + "\n");
};
};
/*
Function to escape a telnet string
#s: String that want to be escaped
#return: The escaped string
*/
function tsescape(s) {
return s
.replace(/\\/g, "\\\\")
.replace(/\//g, "\\/")
.replace(/\|/g, "\\p")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/\v/g, "\\v")
.replace(/\f/g, "\\f")
.replace(/ /g, "\\s");
};
/*
Function to unescape a telnet string
#s: String that want to be unescaped
#return: The unescaped string
*/
function tsunescape(s) {
return s
.replace(/\\s/g, " ")
.replace(/\\p/g, "|")
.replace(/\\n/g, "\n")
.replace(/\\f/g, "\f")
.replace(/\\r/g, "\r")
.replace(/\\t/g, "\t")
.replace(/\\v/g, "\v")
.replace(/\\\//g, "\/")
.replace(/\\\\/g, "\\");
};
};
util.inherits(TeamspeakQueryClient, events.EventEmitter);
How I open the class
if I call example one all works fine but example two has the descriped error.
Example 1:
test1 = new TeamspeakQueryClient({
"alias": "First-Coder Testinsance",
"ip": "first-coder.de",
"port": 10011,
"client": "serveradmin",
"password": "SECURE"
});
Example 2:
test1 = new TeamspeakQueryClient({
"alias": "First Insance",
"ip": "HIDDEN",
"port": HIDDEN,
"client": "serveradmin",
"password": "SECURE"
});
test2 = new TeamspeakQueryClient({
"alias": "Second Instance",
"ip": "HIDDEN",
"port": HIDDEN,
"client": "serveradmin",
"password": "SECURE"
});
Screenshots
Picture of the error in the console
According to your error, your second instance is not sending the correct login:
error id=520 msg=invalid\sloginname\sor\spassword
The additional errors displayed are due to your code not handling errors correctly.
For example:
socket.on("connect", function() {
...
if(err === null) {
if(err.id === 3329) {
If err === null, why would err have an element id?
Most likely this is code error, and you actually meant err !== null
$this.SendCommand("serverlist", null, function(err, response, rawResponse){
console.log(response);
if(response[0] === undefined) {
This error triggers because the (above) previous error was not caught.
At this point, the client is not logged in (authorized).
So when the serverlist command is sent, it riggers another error.
This additional error is also no handled, instead response is immediately used.
I am using node js for backend, also using q promise package.
Question : I am trying to get third party product details.
1. www.abcd.com 2. www.xyz.com - this method i handle in backend.
Possible url:
localhost:8080/search?type="abcd";
localhost:8080/search?type="xyz";
localhost:8080/search;
If the above URL type is abcd means need to search some different thridparty(www.abcd.com) http url;
If the above URL type is xyz means need to search some other different thridparty(www.xyz.com) http url
If the above URL didn't get type means need to search www.abcd.com if the result found means then return response, if result not found means need to call www.xyz.com url and then return response. (Note - here two third party api need to call)
Code:
router.get('/search', function(req, res, next) {
if (!( typeof req.query === 'undefined' || req.query === null || req.query == "")) {
var type = req.query;
}
var spec = {
resp : {}
};
Q(spec).then(function(spec) {
var deferred = Q.defer();
var optionsget = {
host : 'abcd.com',
method : 'GET'
};
var reqGet = https.request(optionsget, function(res) {
var getProductInfo = '';
res.on('data', function(d) {
getProductInfo += d;
});
res.on('end', function() {
if (( typeof message == 'undefined') && (!( typeof items === 'undefined' || items === null))) {
spec.resp.list = items;
deferred.resolve(spec);
} else {
spec.resp.message = message;
deferred.reject(spec);
}
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.log(e);
deferred.reject(spec);
});
return deferred.promise;
}).then(function(spec) {
var deferred = Q.defer();
var optionsget = {
host : 'xyz.com',
method : 'GET'
};
var reqGet = https.request(optionsget, function(res) {
var getProductInfo = '';
res.on('data', function(d) {
getProductInfo += d;
});
res.on('end', function() {
if (( typeof message == 'undefined') && (!( typeof items === 'undefined' || items === null))) {
spec.resp.list = items;
deferred.resolve(spec);
} else {
spec.resp.message = message;
deferred.reject(spec);
}
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.log(e);
deferred.reject(spec);
});
return deferred.promise;
}).then(function(spec) {
spec.resp.status = 'Success';
res.send(spec.resp);
}).fail(function(spec) {
spec.resp.status = 'Error';
res.send(spec.resp);
});
});
I this is chilly question. I understand need to check the type and implement. I thought we need to add some different function for both (abcd and xyz) then can call that method based on type.
Please suggest to good way.
I am working with MVC and Ajax and jQuery. I am returning my JSON value from my action method like below.
public ActionResult GetMYSDRViews(List<string> AssetNames, List<string> UtilizationHubs, string RedirectView)
{
try
{
//ViewBag.InitParams = MvcApplication.objInitParams;
string UserType = MvcApplication.objInitParams.UserType;
bool Execute;
List<MYSDR> MysdrListCollection = new List<MYSDR>();
ServiceClient objService = new ServiceClient();
objService.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential("v-saramb", "sdatnov#2014", "REDMOND");
objService.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
var result = String.Empty;
if (RedirectView == "Agent View")
{
ViewData["Flag"] = "AgentView";
#region Agent View
result = objService.SalesDeskAgent_DynamicAsset("REDMOND\\v-susudh", "", "");
#endregion
}
else if (RedirectView == "Manager View")
{
//result = objService.SalesDeskAgent_DynamicAsset("REDMOND\\v-susudh", "", "");
ViewData["Flag"] = "Manager View";
userHUbdata.Clear();
foreach (string Hub in UtilizationHubs)
{
ServiceReference.MYSDRFields obj2 = new ServiceReference.MYSDRFields();
obj2.Hub = Hub;//cmbHubs.SelectedItem.ToString();
if (obj2.Hub != "All")
userHUbdata.Add(obj2);
}
result = objService.SalesDeskManagerView_ConditionbasedwithFilters("", "", userHUbdata, true);
}
//else if (RedirectView == "BulkAssignment View")
// {
// result = objService.SalesDeskManagerView("REDMOND\\v-susudh", "");
// }
XDocument xmldoc = null;
try
{
xmldoc = XDocument.Parse(result.ToString());
Execute = true;
}
catch
{
Execute = false;
}
if (Execute)
{
#region
MysdrListCollection.Clear();
var data = (from info in xmldoc.Elements("NewDataSet").Elements("Table1")
where Convert.ToString(info.Element("Status").Value) != "" && Convert.ToString(info.Element("Status").Value) != "New" && Convert.ToString(info.Element("Status").Value) != "Projected"
select new MYSDR
{
SRNO = Convert.ToString(info.Element("SRNO").Value),
CustomerName = Convert.ToString(info.Element("CustomerName0").Value),
ServiceLevel = Convert.ToString(info.Element("TypeofRequest").Value.Replace("Unsolicited", "Proactive").Replace("Partner Proactive", "Proactive")),
CRMID = Convert.ToString(info.Element("CRMID").Value),
//DueDate_Date = Convert.ToDateTime(info.Element("DueDate").Value),
RequestType = ((Convert.ToString(info.Element("TypeofRequest").Value) == "Managed Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Standard Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Unsolicited Proposal") || (Convert.ToString(info.Element("TypeofRequest").Value) == "Unsolicited Proposal Lite")) ? "Proposal" : ((Convert.ToString(info.Element("TypeofRequest").Value) == "AIO") || (Convert.ToString(info.Element("TypeofRequest").Value) == "AIO Prep")) ? "AIO" : ((Convert.ToString(info.Element("TypeofRequest").Value) == "M&A Full") || (Convert.ToString(info.Element("TypeofRequest").Value) == "M&A Light")) ? "M&A" : Convert.ToString(info.Element("TypeofRequest").Value),
Region = Convert.ToString(info.Element("Region").Value),
Segment = Convert.ToString(info.Element("Segment").Value),
Assigned = ((Convert.ToString(info.Element("Status").Value) == "Projected") || ((Convert.ToString(info.Element("Status").Value) == "New"))) ? "Assign" : Convert.ToString(info.Element("AssignedToName").Value),
Language = Convert.ToString(info.Element("Language").Value),
ID = Convert.ToString(info.Element("ID").Value),
Status = Convert.ToString(info.Element("Status").Value),
AM = Convert.ToString(info.Element("AM").Value),
Hub = Convert.ToString(info.Element("Hub").Value),
DueDate = Convert.ToDateTime(info.Element("DueDate").Value).Date,
RequestDate = Convert.ToDateTime(info.Element("Requestdate").Value).Date,
PrimaryContact = Convert.ToString(info.Element("PrimaryContact").Value),
Country = Convert.ToString(info.Element("Country").Value),
SolutionForProposal = Convert.ToString(info.Element("SolutionForProposal").Value),
Reactive = ((Convert.ToString(info.Element("TypeofRequest").Value).Contains("Research")) && (Convert.ToString(info.Element("RequestOrigin").Value) == "Reactive")) ? "R" : "",
CoOwner = ((Convert.ToString(info.Element("Status").Value) == "New") || (Convert.ToString(info.Element("Status").Value) == "Projected") || (Convert.ToString(info.Element("TypeofRequest").Value).StartsWith("QA"))) ? "" : (((Convert.ToString(info.Element("Status").Value) != "New") || (Convert.ToString(info.Element("Status").Value) != "Projected")) && (Convert.ToString(info.Element("Coowner").Value) == "")) ? "Add Co-Owner" : (Convert.ToString(info.Element("Coowner").Value)),
}).AsEnumerable();
MysdrListCollection = data.ToList<MYSDR>();
// Session["MYSDRGridAgentView"] = MysdrListCollection.OrderBy(a => a.DueDate);
// return View(data);
#endregion
}
var serializer = new JavaScriptSerializer();
var resultContent = new ContentResult();
serializer.MaxJsonLength = Int32.MaxValue; // Whatever max length you want here
resultContent.Content = serializer.Serialize(MysdrListCollection.OrderBy(a => a.DueDate));
resultContent.ContentType = "application/json";
return resultContent;
// return Json(MysdrListCollection.OrderBy(a => a.DueDate),JsonRequestBehavior.AllowGet);
// return View("Mysdrviews",MysdrListCollection.OrderBy(a => a.DueDate));
//return MysdrListCollection;
}
catch (Exception ex)
{
return Json("");
}
}
I am using my Ajax call from jQuery like below.
$.ajax({
url: '#Url.Action("GetMYSDRViews", "MYSDR")',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
// url: '/MYSDR/PostbtnSubmit',
data: JSON.stringify({ AssetNames: itemsListAssets, UtilizationHubs: itemUtilizationHub, RedirectView: 'Manager View' }),
success: function (result) {
debugger;
var grid = $('#MYSDRGridAgentView').getKendoGrid();
grid.dataSource.data(result);
grid.refresh();
$('#Loader').oLoader('hide');
// $('#result').html('"PassThings()" successfully called.');
},
failure: function (response) {
debugger;
// $('#result').html(response);
}
});
Up to here everything is fine. But when I try to return my JSON result in my return view method like below, I am not getting any error, but I am not able to successfully return result, and my debugger pint also is not hitting at the Success or Error functions in my jQuery.
Please let me know where to change my Ajax function. I am stuck here like anything.
Make the function a JsonResult and return Json(something).
public JsonResult GetMYSDRViews(List<string> AssetNames, List<string> UtilizationHubs, string RedirectView)
{
...
return Json(MysdrListCollection.OrderBy(a => a.DueDate));
}
You put failure instead of error.
error: function (response) {
debugger;
// $('#result').html(response);
}
I am having trouble making an PHP API to get data from MYSQL and parse JSON. I have a demo app (hiApp) and comes with some JSON files inside a folder.
The demo JSON file is like this:
{ "err_code": 0, "err_msg": "success", "data": [{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]}
This what my contacts.php is returning:
[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]
My contacts.php api looks like this:
…
…
$result = mysql_query("select * from sellers", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['nickname'] = $row['first_name'];
$row_array['location'] = $row['territory'];
array_push($json_response,$row_array);
}
echo json_encode($json_response);
?>
The js file to parse JSON, looks like this:
define(['utils/appFunc',
'i18n!nls/lang',
'components/networkStatus'],function(appFunc,i18n,networkStatus) {
//var apiServerHost = window.location.href;
var xhr = {
search: function(code, array){
for (var i=0;i< array.length; i++){
if (array[i].code === code) {
return array[i];
}
}
return false;
},
getRequestURL: function(options){
//var host = apiServerHost || window.location.host;
//var port = options.port || window.location.port;
var query = options.query || {};
var func = options.func || '';
var apiServer = 'api/' + func + '.php' +
(appFunc.isEmpty(query) ? '' : '?');
var name;
for (name in query) {
apiServer += name + '=' + query[name] + '&';
}
return apiServer.replace(/&$/gi, '');
},
simpleCall: function(options,callback){
options = options || {};
options.data = options.data ? options.data : '';
//If you access your server api ,please user `post` method.
//options.method = options.method || 'GET';
options.method = options.method || 'POST';
if(appFunc.isPhonegap()){
//Check network connection
var network = networkStatus.checkConnection();
if(network === 'NoNetwork'){
hiApp.alert(i18n.error.no_network,function(){
hiApp.hideIndicator();
hiApp.hidePreloader();
});
return false;
}
}
$$.ajax({
url: xhr.getRequestURL(options) ,
method: options.method,
data: options.data,
success:function(data){
data = data ? JSON.parse(data) : '';
var codes = [
{code:10000, message:'Your session is invalid, please login again',path:'/'},
{code:10001, message:'Unknown error,please login again',path:'tpl/login.html'},
{code:20001, message:'User name or password does not match',path:'/'}
];
var codeLevel = xhr.search(data.err_code,codes);
if(!codeLevel){
(typeof(callback) === 'function') ? callback(data) : '';
}else{
hiApp.alert(codeLevel.message,function(){
if(codeLevel.path !== '/')
mainView.loadPage(codeLevel.path);
hiApp.hideIndicator();
hiApp.hidePreloader();
});
}
}
});
}
};
return xhr;
});
I know the error is in the way contacts.php is displaying the JSON results or I need to change something in the js file.
Thanks for the help.
Based on your comments above I've tried to rewrite a solution keeping the same structure, but removing the unnecessary things; this is what the code may look like. Note that there are no references to err_code and err_msg peoperties, and the callback is called directly on data variable.
define(['utils/appFunc',
'i18n!nls/lang',
'components/networkStatus'],function(appFunc,i18n,networkStatus) {
//var apiServerHost = window.location.href;
var xhr = {
getRequestURL: function(options){
//var host = apiServerHost || window.location.host;
//var port = options.port || window.location.port;
var query = options.query || {};
var func = options.func || '';
var apiServer = 'api/' + func + '.php' +
(appFunc.isEmpty(query) ? '' : '?');
var name;
for (name in query) {
apiServer += name + '=' + query[name] + '&';
}
return apiServer.replace(/&$/gi, '');
},
simpleCall: function(options,callback){
options = options || {};
options.data = options.data ? options.data : '';
//If you access your server api ,please user `post` method.
//options.method = options.method || 'GET';
options.method = options.method || 'POST';
if(appFunc.isPhonegap()){
//Check network connection
var network = networkStatus.checkConnection();
if(network === 'NoNetwork'){
hiApp.alert(i18n.error.no_network,function(){
hiApp.hideIndicator();
hiApp.hidePreloader();
});
return false;
}
}
$$.ajax({
url: xhr.getRequestURL(options) ,
method: options.method,
data: options.data,
success:function(data){
data = data.length > 0 ? JSON.parse(data) : [];
if (typeof(callback) === 'function' && data !== undefined)
callback(data);
}
});
}
};
return xhr;
});
Then you may call it this way, using directly response var, which now contains the parsed data array:
loadContacts: function() {
if(VM.module('contactView').beforeLoadContacts()) {
xhr.simpleCall({
query: { callback: '?' },
func: 'contacts'
}, function (response) {
if (response !== undefined) {
VM.module('contactView').render({
contacts: response
});
}
});
}
}
Also, you would have to add
header('Content-Type: application/json');
before your PHP echo line in order to be able to parse it in JS.
Ok, many thanks Andrea, looks like there is something else that I'm missing because the results from the contacts.php and the initial contacts.php file is the same in my browser:
[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]
It works just fine if I use the initial contacts.php that only has pure json data like above, but if I switch to my api it stops working.
Also it stops working if I use this in the initial contacts.php:
<?php
$myString = '[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]';
echo $myString;
?>
I'll keep looking, but thanks to you I'm one step ahead.