Trouble calling a javascript function inside $(document).ready() - javascript

I have some code:
$(document).ready(function(){
$(":button").click(function(){
alert("here");
getDetails();
});
});
Inside the getDetails() function, I get form data and do a $.post to get some data. I originally had all of the code that is currently in getDetails directly in the .click() event and it worked that way, but I need that code to be called by a couple of different things, so I need the post not bound to a specific event. The page is getting to the click() function, because my alert shows up, but it isn't getting to the getDetails function. Any ideas? No console errors or warnings when I do the button click.
The code inside getDetails():
function getDetails(){
alert("inside getDetails");
var field1 = document.getElementById('field1').value;
var oper1 = document.getElementById('oper1').value;
var value1 = document.getElementById('value1').value;
var field2 = document.getElementById('field2').value;
var oper2 = document.getElementById('oper2').value;
var value2 = document.getElementById('value2').value;
var field3 = document.getElementById('field3').value;
var oper3 = document.getElementById('oper3').value;
var value3 = document.getElementById('value3').value;
var rsCount = document.getElementById('resultSetCount');
var formData = {"field1":field1, "oper1":oper1, "value1":value1, "field2":field2, "oper2":oper2, "value2":value2, "field3":field3, "oper3":oper3, "value3":value3, "rsCount":rsCount};
$.post("<%=request.getRequestURL().toString()%>getInfo.jsp", formData, function(response){getXML(response)});
}

Related

javascript 'object object' from localstorage

I am getting an alert saying [object] object when I execute showlogsf function
var fdata = {fidval, fweightval, feggslaidval, fgraineatenval, fwaterval};
var fidval = document.getElementById('#fid');
var fweightval = document.getElementById('#fweight');
var feggslaidval = document.getElementById('#feggslaid');
var fgraineatenval = document.getElementById('#fgraineaten');
var fwaterval = document.getElementById('#fwater');
These are the two functions that could be triggered from button click
$('#submitf').click(function (){
localStorage.setItem ("fdatak", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload);
});
});
You're pushing an object as an alert. the HTML displays this as [object Object]. You have to address the actual properties of this object, so:
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload.fidval);
alert(fdataload.fweightval);
alert(fdataload.feggslaidval);
// etc etc...
});
EDIT: Seems like you're also saving the document element, rather than the value. I assume the fdataload.properties are actual values, you should either grab the raw HTML data or input value of this instead of the HTML element itself
I guess your fdata is an array right?.
Try this var fdata = [fidval, fweightval, feggslaidval, fgraineatenval, fwaterval];
I edited values of array as xxx.value instead of xxx
var fdata = new Array();
$('#submitf').click(function (){
var fidval = document.getElementById('fid');
var fweightval = document.getElementById('fweight');
var feggslaidval = document.getElementById('feggslaid');
var fgraineatenval = document.getElementById('fgraineaten');
var fwaterval = document.getElementById('fwater');
var fdata = [];
like this
fdata.push (fidval.value, fweightval.value, feggslaidval.value, fgraineatenval.value, fwaterval.value);
localStorage.setItem ("fdata", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem('fdata'));
document.getElementById("flogview").innerHTML = fdataload;
});
Now it saves but I have another problem, why it is replacing data every time I click showlogsf button??

how to get result of getjson promise inside $.when function?

using the following code i try to get data of 2 getjson calls into array only when both getjson called completed. The code give me this error:
resultFromUrl1.feed is undefined
var entry1 = resultFromUr11.feed.entry;
i looked at f12 i saw both getjson executed successfully but no data get put into the array! how to fix this error ? furthermor should i use $.when(url1Promise, url2Promise).then or $.when(url1Promise, url2Promise).done ?
<javascript>
var files = new Array();
function pushtoArray() {
//first getjson call
var url1 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
var url1Promise = $.getJSON(url1, function (data) {
console.log("url1 success");
});//end of ajax call
//second getjson call
var url2 = "https://spreadsheets.google.com/feeds/list/xxxxx/xxxxx/public/values?alt=json";
var url2Promise = $.getJSON(url2, function (data) {
console.log("url2 success");
});//end of function
$.when(url1Promise, url2Promise).then(function (resultFromUrl1, resultFromUrl2) {
var entry1 = resultFromUrl1.feed.entry;
var entry2 = resultFromUrl2.feed.entry;
var entry = entry1.concat(entry2);
$(entry).each(function () {
// Column names are name, age, etc.
count++;
files.push({ url: this.gsx$url.$t, filename: this.gsx$name.$t });
alert(files.length);
print_r(files);
console.log(files);
});
});
}//end of function
</javascript>
<body onload="pushtoArray()">
jQuery ajax functions are a bit of a pain to use with $.when(). What is is in resultFromURL1 is actually an array of three values like this: [data, textStatus, jqXHR].
So, you need to change to:
var entry1 = resultFromUrl1[0].feed.entry;
var entry2 = resultFromUrl2[0].feed.entry;
In addition, you should add an error handler to your $.when().then() construct so you can see if any errors occurred in your getJSON() calls.
I tried your example using this url: "https://spreadsheets.google.com/feeds/list/o13394135408524254648.240766968415752635/od6/public/values?alt=json"
It works fine..
You are receiving data. You can access the data by writing
resultFromUrl1[0].feed.entry
resultFromUrl2[0].feed.entry;

Unable to call function within same GAS script

I have two function, one reads the Cell value upon change.
And the second one makes a Request to a URL and gets the response.
function onEdit(e) {
var range = e.range;
var data = range.getValue();
Logger.log(data)
Logger.log(test());
}
function test() {
var url = 'apps.compete.com/sites/wholesalerhinestones.org/trended/UV/?apikey=[YOUR API KEY HERE]';
var response = UrlFetchApp.fetch(url);
Logger.log(response);
}
Problem is that, test() runs successfully and Logs the output to Console but upon Cell change event, cell's value is logged but test() is not called.
One of the issues here is you're not actually calling the function, nor are you returning anything should it be called.
It should look something like this:
function onEdit(e){
var range = e.range;
var data = range.getValue();
Logger.log(data)
var testedFunction = test();
Logger.log(testedFunction);
}
function test(){
var url = 'YOUR-URL-HERE';
var response = UrlFetchApp.fetch(url);
Logger.log('Response code: ' + response.getResponseCode());
return response
}
The second issue that you're having here is that your using a Simple trigger which does not allow you to access services which require authorization.
Instead using an Installable trigger for 'onEdit' might do the trick. (This is what I was using, but I was testing against 'Google.com'). It should look like this:

Why my multi javascript array can no pass the data throw ajax?

var model = new Array();
function saveItem(id){
var title = $("#inputTitle_"+id).val();
var url = $("#inputPicurl_"+id).val();
var content = $("#content-editor-"+id).html();
model[id] = new Array();
model[id]['inputTitle'] = $("#inputTitle_"+id).val();
model[id]['inputPicurl'] = $("#inputPicurl_"+id).val();
model[id]['author'] = $("#author_"+id).val();
model[id]['content'] = $("#content-editor-"+id).html();
$("#title_"+id).text(model[id]['inputTitle']);
console.log(model);
}
$("#submit_form").click(function(){
$.ajax({
url:'materials/addpics',
type:'post',
dataType:'json',
data:model,
traditional:'true',
success:function(data){
console.log(data)
}
});
});
when the saveItem() run,the console log is array[],but the data named model in ajax is NULL?
"when the saveItem() run, ..." saveItem is never run. You've defined the function, but you haven't called it anywhere in your code. You probably meant it to be the success handler, instead of the handler you've got that just logs data. (Except that the argument to saveItem doesn't seem to match the argument supplied to the handler.)

Removing Javascript alert line stops my append code working correctly

So, I've got the below code: -
function testing(results) {
$table = $('#formList')
for (var event in results) {
var formIDX = results[event]["forms_idx"]
var formID = results[event]["form_id"]
var eventIDX = results[event]["events_idx"]
var eventID = results[event]["event_id"]
var objID = results[event]["object_id"]
var testVal = results[event]["value"]
alert($table.find("#" + formIDX).find('td:eq(1)').find("div").find("table").html())
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url ="http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable.append(data);
}).done(function(){});
}
}
It basically takes a JSON file and then adds the data into the right sub tables within a main table via appends etc.
The oddity is during debug I had an alert in there to check the html of the table it was identifying (making sure it had found the right sub table etc) and all worked well. But if I remove that alert it then suddenly only appends all the data to the last sub table in the main table?! Any clues?
It's a classic JavaScript closure-loop problem. The variables defined in the for loop are being reassigned each time within the loop and responses from the AJAX requests(which are async) get appended to the last sub-table. It works when you have an alert because the variables have not been reassigned(as alert blocks the for loop execution) by the time AJAX request is completed.
You could handle this by having a function do the AJAX request and append. The variables are not reassigned within this function and hence should work.
function testing(results) {
$table = $('#formList')
function appendSubTable(formIDX, formID, eventIDX, eventID, objID, testVal){
alert($table.find("#" + formIDX).find('td:eq(1)').find("div").find("table").html())
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url ="http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable.append(data);
}).done(function(){});
}
for (var event in results) {
var formIDX = results[event]["forms_idx"]
var formID = results[event]["form_id"]
var eventIDX = results[event]["events_idx"]
var eventID = results[event]["event_id"]
var objID = results[event]["object_id"]
var testVal = results[event]["value"]
appendSubTable(formIDX, formID, eventIDX, eventID, objID, testVal);
}
}
Without seeing more of your code, I can't say for sure. But when I had a similar issue it was because I was using append outside of my $(document).ready(function(){ /*stuff here*/ })
Essentially the object I was appending to hadn't loaded yet.
in your Ajax call use its argument 'async';
it accepts Boolean value, pass the value 'false' in it.
Try it
Move
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
To your callback function:
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
$subTable.append(data);
}).done(function(){});

Categories

Resources