How to check for json results before passing on? - javascript

i have this function to retrieve json data from yql query
function link(b){
var jsonURI = "http://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent("select href,alt,content from html where url='"+b+"' and xpath='//a[#id=\"download\"] |//img[#class=\"dvLinkOverlayFill\"] |//meta[#name=\"title\"]'")+"&format=json&diagnostics=true&_maxage=86400&callback=callback&jsoncallback=?";
jQuery.ajaxSetup({cache: true});
jQuery.getJSON(jsonURI,callback);
}
What i want is to check if the data is null or not before passing on to the callback, if its null, it runs again the link() function, if not it passes on, i have tried
if (jQuery.query.results == null){link(b);}
but no luck, any advice or guide?
EDIT: Got it working, part of it, by using
if (o.query.results == null) { link(b); }
inside the callback function
callback(o){
if (o.query.results == null) { link(b); }
However i can't pass the "b" from the link function to the callback function, it's the only thing that is left for this to work, something like callback(o,b) that could be passed on in here jQuery.getJSON(jsonURI,callback);
since this one is sending the "o", how to make it send the "b" aswell? something like
jQuery.getJSON(jsonURI,callback(o,b));

EDIT updated question answer:
function link(b){
var jsonURI = "http://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent("select href,alt,content from html where url='"+b+"' and xpath='//a[#id=\"download\"] |//img[#class=\"dvLinkOverlayFill\"] |//meta[#name=\"title\"]'")+"&format=json&diagnostics=true&_maxage=86400&callback=callback&jsoncallback=?";
jQuery.ajaxSetup({cache: true});
jQuery.getJSON(jsonURI,function(data, status, xhr){
callback(data, status, xhr,b);
});
}
So you got ur b object in arguments[3]

Couldn't you just simplify that?
if (!jQuery.query.results) { link(b); }

Related

JqGrid fires 'aftersavefunc' & 'successfunc' before 'saveRow'

I'm trying to reload the grid after saving a row to be able to get the Id of the row for logging purposes but somehow 'aftersavefunc' and 'successfunc' fires 'reloadGrid('#telephoneGrid')' before saving. It seems that 'aftersavefunc' and 'successfunc' is identical. Now I can't add nor edit any row.
var lastSel;
function onTelephoneSelect(id, status, e) {
if ($(e.target).hasClass('edit')) {
var editParameters = getEditParameters();
if (id && id !== lastSel) {
jQuery('#telephoneGrid').saveRow(lastSel);
}
jQuery("#telephoneGrid").jqGrid('editRow', id, editParameters);
lastSel = id;
}
}
function getEditParameters() {
return {
"keys": true,
"oneditfunc": null,
"successfunc": null,
"url": '#Url.Action("SaveTelephoneEntry","TelephoneEntry")?customerId=' + $('#SelectCompany').val(),
"extraparam": {},
"aftersavefunc": reloadGrid('#telephoneGrid'),
"errorfunc": null,
"afterrestorefunc": null,
"restoreAfterError": true,
"mtype": "POST"
}
}
I'm pretty desperate now and couldn't figure out any working solution.
Could someone please assist me here or has already faced the same issue and figured out a working solution?
Many thanks in advance.
'aftersavefunc' and 'successfunc' are callbacks but it appears you're trying to set the function directly, so they're getting called before you intend.
Using the proper callback signature it should look something like this:
"aftersavefunc": function (rowid, response, options) {
reloadGrid('#telephoneGrid');
},
Not sure why you need getter for EditParameters (instead of just defining the object and using it directly), but have you checked the values for editParameters whether they get set properly, just before firing:
jQuery("#telephoneGrid").jqGrid('editRow', id, editParameters);
Your getter is inside .hasClass('edit') so you might try to use your getter before going to edit-sub, right after function onTelephoneSelect(id, status, e) { To see if it makes any difference. (Just because we do not know where/when you call onTelephoneSelect).

Word add-in: Get whole document but File.getSliceAsync method not returning

I'm creating an Office Add-in and am having trouble with the javascript file.getFileAsync method in Word Online (Word 2013 desktop is fine).
I'm using sample code from github...
https://github.com/OfficeDev/office-js-docs/blob/master/docs/word/get-the-whole-document-from-an-add-in-for-powerpoint-or-word.md
My code looks like this...
function getFile() {
Office.context.document.getFileAsync(Office.FileType.Text,
{ sliceSize: 65536},
function (result) {
if (result.status == Office.AsyncResultStatus.Succeeded) {
// Get the File object from the result.
var myFile = result.value;
var state = {
file: myFile,
counter: 0,
sliceCount: myFile.sliceCount
};
getSlice(state);
}
});
}
function getSlice(state) {
state.file.getSliceAsync(state.counter, function (result) {
if (result.status == Office.AsyncResultStatus.Succeeded) {
sendSlice(result.value, state);
state.file.closeAsync();
}
else if(result.status == 'failed')
state.file.closeAsync();
});
}
Before calling file.getSliceAsync the data looks good - myFile.sliceCount is 1. The result function is never called and no errors are thrown in the console.
Thanks for any help you can provide!
UPDATE: this issue is fixed and live. Please try it again it must work now.
thanks!
---------------- ORIGINAL ANSWER JUST FOR REFERENCE ----------------------------
Yes, there is a regression right now in Word Online preventing the code to run successfully. The specific issue is that the file.getSliceAsync method is never calling the call-back function. This only happens with the TEXT type, if you want to get the docx or pdf this should work ok. This issue will be fixed in a couple of weeks.
You have an alternative if you want to get the text of the document you can use the new APIs for Word check out this sample:
Word.run(function(context) {
var myBody = context.document.body;
context.load(myBody);
return context.sync()
.then(function(){
console.log(myBody.text);
});
});
Hope this helps!
Thanks for reporting this issue!
Juan.

How to access HTML of a specific element returned by jQuery.post

I have a web page in which when a user clicks on a specific element, a javascript function is triggered which uses $.post() (i.e. jquery) to send the user's data to a PHP script which modifies a database.
On success, the PHP page simply prints
<p id='success'>Yay!</p>
On fail, it prints:
<p id='failure'>$some_error_message</p>
The callback part of the $.post then checks which of these exists. On success, it simply shows an existing (currently hidden) element. On failure, I want to grab the $some_error_message bit, and put it on my page.
I've found a way to do this (as below) but it's clunky - I am sure I shouldn't be having to use an ".each" function when I only want to access a single element. Is there a better way of doing this?
$.post('myURL.php', myData, function(retData)
{
if ( $(retData).filter('#success') )
{
$('#mySuccessDiv').show(200);
}
else if ($(retData).filter('#failure') )
{
$(retData).filter('#failure').each(function()
{
$('#myErrorDiv').html($(this).html());
});
}
else
$('#myErrorDiv').html("Unspecified Error");
}, "html");
As I say, the use of .each seems wasteful, but I can't simply use
$('#myErrorDiv').html($(retData).filter('#failure').html());
because .filter returns a series of objects. But equally, I can't work out how to access only element 0 (since I'm filtering on ID, there can only be one match). I tried:
$('#myErrorDiv').html($(retData).filter('#failure')[0].html());
but it didn't like that.
Am I forced to use .each, or am I being really obtuse?
.filter() will return a jQuery object(with or without any element), so it will always be truthy, to see whether it returned any element you need to check the length of the returned jQuery object
$.post('myURL.php', myData, function (retData) {
var $obj = $(retData);
if ($obj.filter('#success').length) {
$('#mySuccessDiv').show(200);
} else if ($obj.filter('#failure').length) {
$('#myErrorDiv').html($obj.html());
} else {
$('#myErrorDiv').html("Unspecified Error");
}
}, "html");
Another solution is to use .is()
$.post('myURL.php', myData, function (retData) {
var $obj = $(retData);
if ($obj.is('#success')) {
$('#mySuccessDiv').show(200);
} else if ($obj.is('#failure')) {
$('#myErrorDiv').html($obj.html());
} else {
$('#myErrorDiv').html("Unspecified Error");
}
}, "html");

Backbone - Check if Record Already Exists - Is there a better way than this?

In Backbone, I need to check if a model record already exists. Right now, I am doing it by fetching the model by id, and seeing if its "created_at" attribute is undefined. This feels brittle to me. Does anyone have any better recommendations?
var dealProgram = new WhiteDeals.Models.DealProgram({id: servant_id});
dealProgram.fetch({
success: function() {
var program = dealProgram.toJSON();
var datecheck = program.created_at
if(typeof datecheck === 'undefined'){
dealPrograms.create({
title: "",
servant_id: servant.servant_id,
servant_name: servant.name,
servant_master: servant.master
},
{
success: function () {
self.manageServants(servants);
}
}); // End of dealPrograms.create
} else if (datecheck !== undefined) {
console.log("is defined, success!")
self.manageServants(servants);
}; // End of if statement for non-existant dealPrograms
} // End of success
}); // End of dealProgram.fetch
You'll obviously have to check by using a request (whatever the form of the request, you'll have a low amount of data anyway). Guess you should still wonder if it wouldn't be worth fetching all your models at once in a collection so you can make the check client-side (or only the id if it'd be too big to fetch everything).

JS: Using variable names to call function

Im working with jQuery. I have an app that makes ajax requests to server that responds with JSON.
in some cases the response from the server will indicate the name of a JS function to be called
{"responseType":"callback", "callback":"STUFF.TestCallback","callbackData":"this is in the callback"}
If the responseType is "callback" as above the JSON is passed to a function to handle this response type. (the var "response" contains the JSON above)
STUFF.callback = function(response){
if(typeof response.callback =='function'){
console.log("All Good")
response.callback(response);
}else{
console.log("Hmm... Cant find function",response.callback );
}
}
STUFF.TestCallBack = function(data){
alert("it worked");
}
But when I do this I get the error "response.callback is not a function".
Any comments on why this is not working and how to do this properly would be greatly appreciated.
A String is a String, not a Function.
response.callback() doesn't work because it is the same as "STUFF.TestCallback"() not STUFF.TestCallback()
You probably want to have the data structured something more like "callback": "TestCallback" then then do:
STUFF[response.callback](response);
Here you use the String to access a property of STUFF. (foo.bar and foo['bar'] being equivalent.)
You could transform that "namespace.func" into a call like this:
STUFF.callback = function(response) {
var fn = response.callback.split("."), func = window;
while(func && fn.length) { func = func[fn.shift()]; }
if(typeof func == 'function') {
console.log("All Good")
func(response);
} else{
console.log("Hmm... Cant find function", response.callback);
}
}
What this does it grab the function by getting window["STUFF"] then window["STUFF"]["TestCallback"] as it loops, checking if each level is defined as it goes to prevent error. Note that this works for any level function as well, for example "STUFF.One.Two.func" will work as well.
You propably could do
var myfunction = eval(response.callback);
myfunction(response);
although using eval() is considered as a bad style by some javascript developers.

Categories

Resources