how can i parse json data using ajax - ajax

I am having this json string how can i print "data" one by one in java script.
please help me.
{"results":[{"data":"zzx"},{"data":"as"},{"data":"gfdg"},{"data":"nbn"},{"data":"an"},{"data":"sa"}]}
I tried below but its not working. i am using ajax to retrieve data from controller in codeigniter.
$.each(data.results, function(k, v) {
$.each(v, function(key, value) {
$('#result_table').append('<br/>' + key + ' : ' + value);
})
})

Related

How to prevent a 400 code being returned from java server side when you expect an empty result?

I have an ajax call to a server side java servlet and a null response is quite valid. However, I also get a 400 error code. The issue with this is that the 400 errors are filling up my report-uri log making it hard to find any 'real' errors. Is there a way to prevent the 400 code.
The ajax call is:
$.ajax({
url : 'NewsDispView',
data : {
ssAccountLevel : sessionStorage.getItem('ssAccountLevel'),
ssAccountID : sessionStorage.getItem('ssAccountID'),
ssGroupID: sessionStorage.getItem('ssGroupID'),
ssGroupSection: sessionStorage.getItem('ssGroupSection'),
},
type : 'POST',
cache: false,
})
.fail (function(jqXHR, textStatus, errorThrown) {
// alert(jqXHR.responseText);
if(jqXHR.responseText.includes('No News')){
alert("No news");
}else{
alert("News");
}
var marquee = "<span class='glyphicon glyphicon-forward'>";
marquee += " No notices ";
marquee += "<span class='glyphicon glyphicon-forward'>";
$("#newsMarquee").empty();
$('#newsMarquee').append(marquee);
})
.done(function(responseJson1a){
// JSON response to populate the activities table
dataType: "json";
//alert(JSON.stringify(responseJson1a));
//do stuff
})
The servlet return is:
if (newsList == null || newsList.isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No News.");
} else {
String json = new Gson().toJson(newsList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
You can pass your error message as well in JSON format to your ajax call . So , generate your json then pass it like below :
if (newsList == null || newsList.isEmpty()) {
String json = new Gson().toJson(yourjson);
} else {
String json = new Gson().toJson(newsList);
}
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Then , check in your ajax code if the response has the key or not i.e : error and change your ajax logic accordingly.

How to get the raw content of an outlook email message with Office JS API?

I'm trying to check if the sender used a proxy email address. Comparing the from and sender properties isn't enough, so I thought of checking the raw message source itself.
How do you get the raw message source with Office JS API?
If you're just looking for a prebuilt solution to see and analyze message headers in Outlook and OWA, you can use Message Header Analyzer. If you're building your own add-in, you can borrow source from there.
Basically, you have two options:
EWS
Rest
In both cases, what you want to retrieve is PR_TRANSPORT_MESSAGE_HEADER, aka 0x007D. The EWS request will look something like this:
function getHeadersRequest(id) {
// Return a GetItem EWS operation request for the headers of the specified item.
return "<GetItem xmlns='http://schemas.microsoft.com/exchange/services/2006/messages'>" +
" <ItemShape>" +
" <t:BaseShape>IdOnly</t:BaseShape>" +
" <t:BodyType>Text</t:BodyType>" +
" <t:AdditionalProperties>" +
// PR_TRANSPORT_MESSAGE_HEADERS
" <t:ExtendedFieldURI PropertyTag='0x007D' PropertyType='String' />" +
" </t:AdditionalProperties>" +
" </ItemShape>" +
" <ItemIds><t:ItemId Id='" + id + "'/></ItemIds>" +
"</GetItem>";
}
And you'll submit it through a call to makeEwsRequestAsync
var mailbox = Office.context.mailbox;
var request = getHeadersRequest(mailbox.item.itemId);
var envelope = getSoapEnvelope(request);
mailbox.makeEwsRequestAsync(envelope, function (asyncResult) {
callbackEws(asyncResult, headersLoadedCallback);
});
To do the same from rest, you first need to get the rest ID for the item:
function getItemRestId() {
if (Office.context.mailbox.diagnostics.hostName === "OutlookIOS") {
// itemId is already REST-formatted
return Office.context.mailbox.item.itemId;
} else {
// Convert to an item ID for API v2.0
return Office.context.mailbox.convertToRestId(
Office.context.mailbox.item.itemId,
Office.MailboxEnums.RestVersion.v2_0
);
}
And then send the request through AJAX:
var getMessageUrl = getRestUrl(accessToken) +
"/api/v2.0/me/messages/" +
itemId +
// PR_TRANSPORT_MESSAGE_HEADERS
"?$select=SingleValueExtendedProperties&$expand=SingleValueExtendedProperties($filter=PropertyId eq 'String 0x007D')";
$.ajax({
url: getMessageUrl,
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken,
"Accept": "application/json; odata.metadata=none"
}
}).done(function (item) {
The MHA source gives more context.

Getting UserID from the Session In Extjs in some other js files of same App

In other way I want to access
(One functions Variable in another function in some other file of same application)
I'm trying to retrieve the UserID i got it from the session in some other .js files of a same application, How will I be able to do it?
This is my
session.js
function SessRequest() {
};
SessRequest.prototype.get = function (url, params, payload, session, cb, scope) {
var data = {};
if (payload) {
data.payload = payload;
}
if (url.indexOf('?') > -1) {
url = url + '&logonID=' + session.user.userID;
} else {
url = url + '?logonID=' + session.user.userID;
}
cb.call(scope, result.message, resp);
});
SessRequest.prototype.post = function (url, params, payload, session, cb, scope) {
params.logonID = session.user.userID;
rest.post(url, {data: params}).on('complete', function (data) {
cb.call(scope, 0, data);
});
};
Now This session.user.userID, I want this value to retrieve in a grid.js file of the same application, Can anyone help me in this ?
say me how to retrieve it and print it on console? If possible.
Please ask for any extra thing if My question is not clear?
thanks in advance
You could create a singleton class which holds the userid information.
Ext.define('APP.SessionInformation', {
singleton: true,
userid: null
});
When you retrived the information after successful login, you set it in the singleton.
APP.SessionInformation.userid = session.user.userID;
Now you are able to access it everywhere in you application by APP.SessionInformation.userid.

Parse.com: Retrieving object by objectId does not work. Why? It is very simple query

I got an error with message "101 Object not found."
The below code is just copy from the official guide. And I changed the class name and the objectId.
I know this is very simple query but I don't know why? Help me how to debug in this case...
This code is in cloud code. I set up "applicationId" and "masterKey" in global.json.
Thanks..
require('cloud/app.js');
Parse.Cloud.define("sample", function(request, response) {
var GameScore = Parse.Object.extend("Item");
var query = new Parse.Query(GameScore);
query.get("XXXXXX", {
success: function(gameScore) {
},
error: function(object, error) {
console.error("error: " + error.code + " " + error.message);
}
});
});
I tend to use the promise method and I'd possibly rewrite it like this...
Parse.Cloud.define("sample", function(request, response) {
var query = new Parse.Query("Item");
// put this in as a debug message.
console.log("Just checking I'm here!");
query.get("XXXXXX").then (function(item) {
response.success(item);
}, function(error) {
console.error("error: " + error.code + " " + error.message);
response.error(error);
});
});
But it should work as it is. Odd. Are you sure the error message is coming from your code?
Try adding a log before it.
EDIT
It seems that permissions were not set properly on your item object.
With iOS you can specify a default ACL for objects at create time. You can also create a custom ACL object and pass it to the object when saving it.

jQuery AJAX post data gets lost

I'm trying to post data with AJAX and insert it into a database table.
The problem is, half of the data is missing and I don't know why. I have checked all the names of parameters etc. because it seemed I had a typo somewhere (I was missing some characters but I fixed that) but still it won't work.
Even console.log() and alerts give me the full data I want to post but it never arrives, the php outputs empty parameters. When deactivating the JavaScript or removing "return false;" the php script is opened as expected and works perfectly well, no data is lost (as expected).
Maybe I'm really just missing one single character somewhere ...
I also tried escaping (escape()) the strings but it didn't change anything.
Here's the code and some logs/alerts/echos
$("#itemspeichern").click(function(){
setVisible("#item-process");
var itemname = escape($("#itemname").val());
if ($("#itemneu").is(":checked")) {
var itemneu = $("#itemneu").val();
} else {
var itemneu = 0;
}
var itembild = escape($("#itembild").val());
var itemkurzb = escape($("#itemkurzb").val());
var theset = escape($("#theset").val());
console.log("itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset);
$.ajax({
url: "<?php actualPath(); ?>save-admin-action.php",
type: "POST",
data: "itemname=" + itemname + "&itemneu=" + itemneu + "&itembild" + itembild + "&itemkurzb" + itemkurzb + "&theset=" + theset,
success: function(result){
alert("itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset);
document.getElementById("item-process").innerHTML = result;
}
});
return false;
});
What this does is:
- output the data of all fields on the console
- showing all the data in the alert
but when it is done saving it the database is missing the values of itembild and itemkurzb. Getting the query as response from the php file showed that indeed the parameters are empty for those fields. Here's what I did in php (I shortened it a bit, don't comment on SQL injection and stuff :P)
$ergebnis = mysql_query("INSERT INTO mk7_items(id, de, neu, kurzbeschreibung, bild) VALUES(DEFAULT, '".$_POST["itemname"]."', ".$_POST["itemneu"].", '".$_POST["itemkurzb"]."', '".$_POST["itembild"]."')");
the last two fields are empty when I get the response and nothing is saved into the db.
As I said, setting JS to OFF and running it on php only works perfectly well.
Any ideas? Any stupid mistakes I did there?
You're missing a couple = in your data, it should be this:
data: "itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset,
Or better, stop using escape (which is deprecated in favor or encodeURIComponent due to escape not handling non-ASCII data very well) and use an object for your data parameter:
var itemname = $("#itemname").val();
//...
$.ajax({
url: "<?php actualPath(); ?>save-admin-action.php",
type: "POST",
data: {
itemname: itemname,
itemneu: itemneu,
itembild: itembild,
itemkurzb: itemkurzb,
theset: theset
},
//...
});
That way $.ajax will take care of converting your data to the proper POST (or GET or ...) format and you don't have to worry about the details.
try this in your $.ajax call instead of your selfmade query string:
data: {
itemname: itemname,
itemneu: itemneu,
itembild: itembild,
itemkurzb: itemkurzb,
theset: theset
}
By passing the data as Object, jQuery will escape the values for you :)
Edit:
You could also serialize the complete form like this:
data: $('#yourform').serialize()
if you use special characters in posted items, you use this function before every vars...
sample :
var txt = encodeURIComponent(document.getElementById('txt1').value);

Resources