I have a javascript table that is displaying data that is store in a parse.com server, i also have a iOS App that is also getting the same data from the same place on the iOS App it is every for row that has been selected in the table to store the object id in an NSString to be used in other like adding it a favourite column etc however on the javascript side i have not been very successful at this can one help?
iOS
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{[tableView deselectRowAtIndexPath:indexPath animated:YES];
PFObject *tempObject = [HomeArray objectAtIndex:indexPath.row];
NSLog(#"%#", tempObject.objectId);
_NameOfGame.text = [tempObject objectForKey:#"NameGame"];
_Items.text = [tempObject objectForKey:#"item"];
_Des.text = [tempObject objectForKey:#"des"];
userFirstname = [tempObject objectForKey:#"FirstName"];
group = [tempObject objectForKey:#"group"];
device = [tempObject objectForKey:#"Device"];
together = [NSString stringWithFormat:#"Uploaded by %# from %# on a %#", userFirstname, group, device];
PFFile *video = [tempObject objectForKey:#"Video"];
_videoUrl = video.url;
NSLog(#"got a video %#", _videoUrl);
_deleteObjectID = [HomeArray objectAtIndex:indexPath.row];
NSLog(#"%#", _deleteObjectID);
[self animateDetailView];}
Javascript
var GameScore = Parse.Object.extend("games");
var query = new Parse.Query(GameScore);
query.equalTo("group", strUser)
query.find(
{
success: function(results)
{
for (var i = 0; i < results.length; i++)
{
var object = results[i];
(function($) {
$("#first-team-results-table").append("<tr><td>"
+"<input type='checkbox' data-id='" + object.id + "'/>" $(checkBox).appendTo("#modifiersDiv")
+ "</td><td>"
+ object.get("NameGame")
+ "</td><td>"
+ object.get("item")
+ "</td><td>"
+ object.get("des")
+ "</td></tr>");
})(jQuery);
}
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
})
});
I have try with checkboxes in javascript but no luck
In which way aren't you successful? What doesn't work?
Do you get the correct result at all? If not change this line
query.equalTo("group", strUser) && query.equalTo("month", res);
to
query.equalTo("group", strUser);
query.equalTo("month", res);
------------------------------------ EDIT -------------------------
I would rewrite it like this:
var GameScore = Parse.Object.extend("games"),
query = new Parse.Query(GameScore),
$table = $("#first-team-results-table"),
tableString;
appendToTable = function (object) {
tableString = "<tr><td><input type='checkbox' data-id='"+object.id+"'</td><td>"+object.get("NameGame")+"</td><td>"+object.get("item")+"</td><td>"+object.get("des")+"</td></tr>";
$table.append(tableString);
$(checkBox).appendTo("#modifiersDiv"); // I don't know what the checkbox-variable represents... anyway use this line to do something with it ;)
};
query.equalTo("group", strUser)
query.find({
success: function(results){
var object;
for (var i = results.length - 1; i >= 0; i--) {
object = results[i];
appendToTable(object);
};
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
I'm not sure what you are doing here
$(checkBox).appendTo("#modifiersDiv")
but I hope it gets you in the right direction...
------------------------------------ EDIT -------------------------
okay retry, still not sure if I get what you're trying to do. The following will first display the table after fetching stuff from Parse.com and putting it to the #objectBox-div when clicking the 'more'-button
HTML
<div id="buttonShow"> <input type="submit" id="uploadPaid" value="More"/><input type="text" id="gotObject" class="textFields"/> </div>
<table id="first-team-results-table"></table>
<div id="objectBox"></div>
JS
(function() {
var GameScore = Parse.Object.extend("games"),
query = new Parse.Query(GameScore),
$table = $("#first-team-results-table"),
$objectBox = $('#objectBox'),
tableString,
divString,
ParseGames;
appendToTable = function (object) {
tableString = "<tr><td><input class='check' type='checkbox' data-id='"+object.id+"'</td><td>"+object.get('NameGame')+"</td><td>"+object.get('item')+"</td><td>"+object.get('des')+"</td></tr>";
$table.prepend(tableString);
};
appendToDiv = function (object) {
divString = "<p><span>"+object.get('NameGame')+"</span> <span>"+object.get('item')+"</span> <span>"+object.get('des')+"</span></p>";
$objectBox.append(divString);
};
query.equalTo("group", strUser)
query.find({
success: function(results){
ParseGames = results;
for (var i = results.length - 1; i >= 0; i--) {
appendToTable(results[i]);
};
},
error: function (error) {
alert("Error: " + error.code + " " + error.message);
}
});
$("#uploadPaid").on('click', function (e) {
e.preventDefault();
$objectBox.html('');
$('.check').each(function(index) {
console.log($(this).is(':checked'));
if ($(this).is(':checked')) {
appendToDiv(ParseGames[index]);
};
});
});
})();
good luck ;)
After a couple of days look through website and trying lots of code i have finally got an answer to my question.
<table id="first-team-results-table" class="table1" border="1xp" style="width:100%">
<col width="80">
<col width="80">
<col width="5">
<col width="300">
<col width="100">
<tbody>
<tr>
<th>Name Of Game</th>
<th>Item</th>
<th>Video</th>
<th>Description</th>
<th>Group</th>
</tr>
</tbody>
</table>
<script type="text/javascript">
Parse.initialize("API1", "API2" );
var firstTeamResults = Parse.Object.extend("ukgames");
var query = new Parse.Query(firstTeamResults);
//query.equalTo("favs", id);
//"group" , group
query.descending("updateAt");
query.find({success: function(results){
for (var i = 0; i < results.length; i++)
{
var object = results[i];
(function($) {
$("#first-team-results-table").append("<tr><td>"
+ "<input type='checkbox' class='chkNumber' value='"+object.id+"'/>"
+ "</td><td>"
+ object.get("NameGame")
+ "</td><td>"
+ object.get("item")
+ "</td><td>"
+ object.get("des")
+ "</td><td>"
+ object.get("group")
+"</td></tr>");
})(jQuery);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
</script>
<div id="buttonShow">
<input type="button" class="btnGetAll" value="More"/>
<input type="text" id="gotObject" class="textFields"/>
</div>
<script type="text/javascript">
$(function () {
$('.btnGetAll').click(function () {
if ($('.chkNumber:checked').length) {
var chkId = '';
$('.chkNumber:checked').each(function () {
chkId += $(this).val() + ",";
});
chkId = chkId.slice(0, -1);
alert(chkId);
}
else {
alert('Nothing Selected');
}
});
$('.chkSelectAll').click(function () {
$('.chkNumber').prop('checked', $(this).is(':checked'));
});
$('.chkNumber').click(function () {
if ($('.chkNumber:checked').length == $('.chkNumber').length) {
$('.chkSelectAll').prop('checked', true);
}
else {
$('.chkSelectAll').prop('checked', false);
}
});
});
</script>
Related
So this weird thing with Visual studio code started happening with JS files, I'm getting random errors even in code that is commented out? not sure if this is a bug or my doing. I had someone open the folder from their computer and everything ran fine with no errors. The code on my computer runs fine as well, it's just these errors are annoying me and I wouldn't know if I'm actually doing something wrong in the future.
Here's an example file
$(document).ready(function () {
// Declare Global Variable
let admin = new Admin();
let student = new Student();
let inbox = new Inbox();
let sentbox = new Sentbox();
let v = new Validate();
// Register Admin
$("#regadminform").submit(function (e) {
e.preventDefault();
const firstName = $("#firstName").val();
const lastName = $("#lastName").val();
const email = $("#adminEmail").val();
admin.create(firstName, lastName, email).then(function (result) {
if (!result.err) {
// Sets user email
localStorage.setItem("adminEmail", result.data.email);
adminExist();
$("#regadmin").modal("hide");
} else {
//error message
alert(result);
}
});
});
// Get Selected User for 'To' Field
$("#formTo").submit(function (e) {
e.preventDefault();
var radioValue = $("input[name='to']:checked").val();
$("#to").val(radioValue);
$(".close").click();
});
$("#inboxTable").submit(function (e) {
e.preventDefault();
location.replace("../adminView.html");
});
// Get Selected User for 'CC' Field
$("#formCC").submit(function (e) {
e.preventDefault();
var radioValue = $("input[name='cc']:checked").val();
$("#cc").val(radioValue);
$(".close").click();
});
// Compose Email
$("#composeForm").submit(function (e) {
e.preventDefault();
e.stopPropagation();
const from = localStorage.getItem("adminEmail");
const to = $("#to").val();
const cc = $("#cc").val();
const subject = $("#subject").val();
const body = $("#body").val();
if (!v.isEmpty(cc, "CC")) {
if (!v.isEmpty(subject, "Subject")) {
if (!v.isEmpty(body, "Body")) {
data = {
from: from,
to: to,
cc: cc,
subject: subject,
body: body,
viewed: false,
};
inbox.storeEmail(to, data).then(function (result) {
if (!result.err) {
sentbox.storeEmail(from, data).then(function (result) {
if (!result.err) {
//result.message
window.location.replace("sentbox.html");
} else {
//sentbox error message
}
});
} else {
//inbox error message
}
});
}
}
}
});
// Add a Admin
$("#addadminform").submit(function (e) {
e.preventDefault();
const firstName = $("#first").val();
const lastName = $("#last").val();
const email = $("#email").val();
admin.create(firstName, lastName, email).then(function (result) {
if (!result.err) {
$("#adminTable tbody").append(
"<tr data-id=" +
result.data._id +
"><td >" +
result.data.firstName +
" " +
result.data.lastName +
"</td><td >" +
result.data.email +
"</td><td><i class='fa fa-times' id='close' aria-hidden='true'></i></td></tr>"
);
$("#first").val("");
$("#last").val("");
$("#email").val("");
} else {
//error message
}
});
$(".close").click();
});
// Load 'To' table for admin selection
$("#to").click(function (e) {
// Empty Table
$("#studentTo tbody").empty();
// Load Table
setTimeout(function () {
student.getAll().then(function (result) {
if (!result.err) {
for (var i = 0; i < result.data.length; i++) {
$("#studentTo tbody").append(
"<tr><td>" +
result.data[i].firstName +
" " +
result.data[i].lastName +
"</td><td>" +
result.data[i].email +
'</td><td><input type="radio" name="to" class="to" value="' +
result.data[i].email +
'" required></td>'
);
}
} else {
//error message
}
});
}, 1000);
});
// Load 'CC' table for admin selection
$("#cc").click(function (e) {
// Empty Table
$("#adminCC tbody").empty();
// Load Table
setTimeout(function () {
admin.getAll().then(function (result) {
if (!result.err) {
for (var i = 0; i < result.data.length; i++) {
$("#adminCC tbody").append(
"<tr><td>" +
result.data[i].firstName +
" " +
result.data[i].lastName +
"</td><td>" +
result.data[i].email +
'</td><td><input type="radio" name="cc" class="cc" value="' +
result.data[i].email +
'" required></td>'
);
}
} else {
//error message
}
});
}, 1000);
});
// Get id of the email in the inbox and store it in localStorage
$("#inboxTable tbody tr").click(function (e) {
e.stopPropagation();
const emailID = $(this).attr("data-id");
localStorage.setItem("emailID", emailID);
window.location.replace("ViewingInboxItemsAdmin.html");
});
// Delete email in the inbox
$("#inboxTable tbody").on("click", ".fa-times", function (e) {
e.stopPropagation();
const emailID = $(this).parent().parent().attr("data-id");
const email = localStorage.getItem("adminEmail");
var r = confirm("Are you sure you want to delete this email?");
if (r == true) {
inbox.deleteEmail(emailID, email).then(function (result) {
if (!result.err) {
$("#inboxTable tbody tr[data-id='" + result.data._id + "']").remove();
} else {
//error message
}
});
}
});
// Get id of the email in the sentbox and store it in localStorage
$("#sentItemsTable tbody").on("click", "tr", function (e) {
e.stopPropagation();
const emailID = $(this).attr("data-id");
localStorage.setItem("emailID", emailID);
window.location.replace("ViewingSentItemsAdmin.html");
});
// Delete email in the sentbox
$("#sentItemsTable tbody").on("click", ".fa-times", function (e) {
e.stopPropagation();
const emailID = $(this).parent().parent().attr("data-id");
const email = localStorage.getItem("adminEmail");
var r = confirm("Are you sure you want to delete this email?");
if (r == true) {
sentbox.deleteEmail(emailID, email).then(function (result) {
if (!result.err) {
$(
"#sentItemsTable tbody tr[data-id='" + result.data._id + "']"
).remove();
} else {
//error message
}
});
}
});
});
// Load inbox
function loadInbox() {
let inbox = new Inbox();
const email = localStorage.getItem("adminEmail");
inbox.load(email).then(function (result) {
if (!result.err) {
for (var i = 0; i < result.data.length; i++) {
$("#inboxTable tbody").append(
"<tr data-id=" +
result.data[i]._id +
"><td >" +
result.data[i].email.from +
"</td><td >" +
result.data[i].email.subject +
"</td><td><i class='fa fa-times' id='close' aria-hidden='true'></i></td></tr>"
);
}
} else {
//error message
}
});
}
// View an email in the inbox
function viewInboxEmail() {
let inbox = new Inbox();
const emailID = localStorage.getItem("emailID");
const email = localStorage.getItem("adminEmail");
inbox.viewEmail(emailID, email).then(function (result) {
if (!result.err) {
$("#From").val(result.data.from);
$("#Cc").val(result.data.cc);
$("#Subject").val(result.data.subject);
$("#BodyText").val(result.data.body);
} else {
//error message
}
});
}
// Load the sentbox
function loadSentbox() {
let sentbox = new Sentbox();
const email = localStorage.getItem("adminEmail");
sentbox.load(email).then(function (result) {
if (!result.err) {
for (var i = 0; i < result.data.length; i++) {
$("#sentItemsTable tbody").append(
"<tr data-id=" +
result.data[i]._id +
"><td >" +
result.data[i].email.from +
"</td><td >" +
result.data[i].email.subject +
"</td><td><i class='fa fa-times' id='close' aria-hidden='true'></i></td></tr>"
);
}
} else {
//error message
}
});
}
// View an email in the sentbox
function viewSentboxEmail() {
let sentbox = new Sentbox();
const emailID = localStorage.getItem("emailID");
const email = localStorage.getItem("adminEmail");
sentbox.viewEmail(emailID, email).then(function (result) {
if (!result.err) {
$("#To").val(result.data.to);
$("#From").val(result.data.from);
$("#Cc").val(result.data.cc);
$("#Subject").val(result.data.subject);
$("#BodyText").val(result.data.body);
} else {
//error message
}
});
}
// List all the Students
function listAllStudents() {
let student = new Student();
student.getAll().then(function (result) {
if (!result.err) {
for (var i = 0; i < result.data.length; i++) {
$("#studentTable tbody").append(
"<tr data-id=" +
result.data[i]._id +
"><td >" +
result.data[i].firstName +
" " +
result.data[i].lastName +
"</td><td >" +
result.data[i].email +
"</td><td><i class='fa fa-times' id='close' aria-hidden='true'></i></td></tr>"
);
}
} else {
//error message
}
});
}
// List all the Admins
function listAllAdmins() {
let admin = new Admin();
admin.getAll().then(function (result) {
if (!result.err) {
for (var i = 0; i < result.data.length; i++) {
$("#adminTable tbody").append(
"<tr data-id=" +
result.data[i]._id +
"><td >" +
result.data[i].firstName +
" " +
result.data[i].lastName +
"</td><td >" +
result.data[i].email +
"</td><td><i class='fa fa-times' id='close' aria-hidden='true'></i></td></tr>"
);
}
} else {
//error message
}
});
}
// Check to see if Admin is stored in local storage
function adminExist() {
const email = localStorage.getItem("adminEmail");
let inbox = new Inbox();
let sentbox = new Sentbox();
if (email == null || email == "") {
$("#regadmin").modal("show");
} else {
// Gets user email
$("#userEmail").text(email);
inbox.count(email).then(function (result) {
console.log(result);
if (!result.err) {
$("#adminInboxBadge").text(result.data.length);
} else {
//error message
}
});
sentbox.count(email).then(function (result) {
console.log(result);
if (!result.err) {
$("#adminSentboxBadge").text(result.data.length);
} else {
//error message
}
});
}
}
Picture of errors
Here is a picture of errors in comments
It is clearly something to do with Visual Studio code (or so i think) has anyone had the same problem?
Go into the visual studio settings. Disable the ES-lint if you are using that.
Because you use jQuery in a browser you don't import it in the .js file.
You add a script tag in the HTML above it for jQuery.
The linter does only static analysis and has no knowledge of the script tags already executed.
The $ variable is created in the jQuery JavaScript file. So is unknown to the linter.
If it annoys you a lot you can, like Sudarshan` mentions disable ES-lint for this project or globally.
I'm trying to retrieve images on Facebook Parse SDK, and I can't because of this error. And I don't know what i'm doing wrong because I use a conditional in order to no not to create a new variable if this is empty or undefined. This is the code (the console log points the error in the line where i'm creating the var ImageFl):
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
if (!object.get('ImageFile') || object.get('ImageFile') !== '' || typeof object.get('ImageFile') !== 'undefined') {
var imageFl = object.get('ImageFile');
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
var object = results[i];
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
The object wasn't being set before the if statement. update, added code from comments
var Encharcamientos1 = Parse.Object.extend("Report");
var query = new Parse.Query(Inundaciones1);
query.equalTo("Tipo_Reporte", "Encharcamientos");
query.find({
success: function(results) {
// Do something with the returned Parse.Object values
for (var i = 0; i < results.length; i++) {
var object = results[i]; // <-- THIS NEEDS TO BE BEFORE IF STATEMENT
var imageFl = object.get('ImageFile');
alert(imageFl);
if (imageFl !== '' && typeof imageFl !== 'undefined') {
var imageURL = imageFl.url();
$('.imagen')[0].src = imageURL;
}
L.marker([object.get('Latitud'),object.get('Longitud') ], {icon: EncharcamientosIcon}).bindPopup(' <p><span class="grande"> ' + object.get('Tipo_Reporte') + ' </span></p><p>Fecha: ' + object.get('Fecha') + ' </p><p>Hora: ' + object.get('Hora') + '<div class="imagen"></div>' + '</p><p>Comentarios:<br /> ' + noundefined(object.get('Comentario')) + '</p>').addTo(Encharcamientos).addTo(todos);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
I am attempting to do a small PoC with PDFs and have run into an issue. I am looking to post a message to a PDF and have the PDF post a message to the browser.
The deets:
I am viewing the PDF in an "object" element in IE9. I am using itextsharp to prefill a pdf template on the server, inject some app level javascript (post message and on message stuff) and then serve that up to the browser via a filestreamresult. I am using Reader 10 to view the PDF in IE9.
What works:
So far, everything works except for the PDF posting a message to the browser. I can post a message to the PDF, from the browser, no problem and all of the fields are prefilled as desired.
What doesn't work:
When I try using this.hostContainer.postMessage(["something","somethingmore"]) I get an Acrobat Escript window that says "hostContainer is not defined". I have also tried using "event.target.hostContainer" but I get "event.target is not defined". I am at a loss of what to do and any insight would be super helpful.
Reference links:
Acrobat Javascript API
Stackoverflow How-To on this topic
Original guide I used
The code:
My form view:
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
My custom javascript string method:
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(doc.xfa);" +
"console.println('Doc xfa value = ' + doc.xfa);" +
// "event.target.hostContainer.postMessage(['hello from pdf!']);" +
// "this.hostContainer.postMessage(['hello from pdf!']);"+
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}
My method for filling and sending the form to the browser:
public MemoryStream GetFilledRequestForm(string fileDirectory, User user, FormView formView)
{
var pdfStream = new MemoryStream();
var templateFilePath = GetRequestTypeTemplateFilePath(fileDirectory, _requestModule.FormTemplateFileName);
var pdfReader = new PdfReader(templateFilePath);
// pdfReader.RemoveUsageRights();
var stamper = new PdfStamper(pdfReader, pdfStream);
var formFields = GetFormFields(user, formView, pdfReader);
foreach (var field in formFields.Where(f => f.Value != null))
{
stamper.AcroFields.SetField(field.Name, field.Value);
}
stamper.FormFlattening = false;
var newJs = GetCustomJavascript(stamper.Reader.JavaScript);
stamper.AddJavaScript("newJs", newJs);
stamper.Close();
byte[] byteInfo = pdfStream.ToArray();
var outputStream = new MemoryStream();
outputStream.Write(byteInfo, 0, byteInfo.Length);
outputStream.Position = 0;
return outputStream;
}
Ok, so I have resolved it, with some help of course. I found the key at this stack overflow post. I needed to wait for the object to load before assigning the message handler. Additionally, I needed a global variable in the pdf javascript to be able to post the message.
Html/Javascript: (the key here is the loadListener() function)
#model WebModel.FormView
<object id="pdfFrame" style="width:100%;height: 100%;" data="#Url.Action("LoadForm")">No luck :(</object>
<input id="buttonPost" type="button" value="post to pdf"/>
<script type="text/javascript">
var PDFObject = document.getElementById("pdfFrame");
function loadListener() {
if (typeof PDFObject.readyState === 'undefined') { // ready state only works for IE, which is good because we only need to do this for IE because IE sucks in the first place
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
return;
}
if (PDFObject.readyState == 4) {
debugger;
PDFObject.messageHandler = { onMessage: messageFunc };
} else {
setTimeout(loadListener, 500);
}
}
function messageFunc(data) {
debugger;
var messagedata = data;
alert('finally!!');
}
function sendToPdf() {
if(PDFObject!= null){
PDFObject.postMessage(
["a", "b"]);
}
}
$('#pdfFrame').ready(function() {
loadListener();
$('#buttonPost').on('click', function() {
sendToPdf();
});
});
</script>
My new function to create the javascript: (the key here is var appHostContainer)
private static string GetCustomJavascript(string existingJavaScript)
{
const string newJs =
"this.disclosed = true; " +
"var appHostContainer = this.hostContainer;" +
"if (this.external && this.hostContainer) { " +
"function onMessageFunc( stringArray ) { " +
// "var name = this.myDoc.getField(personal.name); " +
// "var login = this.myDoc.getField(personal.loginname); " +
"try{" +
"app.alert(stringArray);" +
"appHostContainer.postMessage(['hello from pdf!']);" +
// "name.value = stringArray[0]; " +
// "login.value = stringArray[1]; " +
"} catch(e){ onErrorFunc(e); } " +
"} " +
"function onErrorFunc( e ) { " +
"console.show(); " +
"console.println(e.toString()); " +
"} " +
"try {" +
"if(!this.hostContainer.messageHandler) { " +
"this.hostContainer.messageHandler = new Object(); " +
"this.hostContainer.messageHandler.myDoc = this; " +
"this.hostContainer.messageHandler.onMessage = onMessageFunc; " +
"this.hostContainer.messageHandler.onError = onErrorFunc; " +
"this.hostContainer.messageHandler.onDisclose = function(){ return true; }; " +
"}" +
"} catch(e){onErrorFunc(e);}" +
"}";
var jsToReturn = existingJavaScript + newJs;
return jsToReturn;
}
Is there an alternative to using .load to refresh the contents of a Div? Bascially I'm using .load below to reload the div after an object has been removed. But at the moment this is'nt working correctly.
.load is returning a div without results, even though there should be objects within it. When I refresh the page manually the correct results show.
Therefore, Could I just remove the object from view the user has clicked on instead?
/////////////////////SECTION 1 - This code block returns the current users friends to the page. THIS IS NOT USED IN THE FILTER//////
$('#containerFriends').empty();
$('#friendsProfile').hide();
$('#container').empty();
$('#containerFriendsConnected').empty();
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var queryOne = new Parse.Query(FriendRequest);
queryOne.equalTo("toUser", currentUser);
var queryTwo = new Parse.Query(FriendRequest);
queryTwo.equalTo("fromUser", currentUser);
var mainQuery = Parse.Query.or(queryOne, queryTwo);
mainQuery.include('toUser');
mainQuery.include('fromUser');
mainQuery.equalTo("status", "Connected");
mainQuery.find({
success: function(results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
imageURL: results[i].get('toUser').get('pic'),
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').id,
status: results[i].get('status'),
// Saves the object so that it can be used below to change the status//
fetchedObject: results[i]
});
}
var select = document.getElementById("FriendsConnected");
$.each(friends, function(i, v) {
var opt = v.username;
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
})
$('#containerFriends').empty();
$('#containerFriendsConnected').empty();
_.each(friends, function(item) {
var wrapper = $('<div class="portfolio-item-thumb one-third"></div>');
wrapper.append('<img class="responsive-image friendImgOutline" src="' + item.imageURL + '" />' + '<br>');
wrapper.append('<div class="tag">' + item.username + '</div>');
wrapper.append('<div type="button" class="btn btn-danger mrs decline">' + 'Unfriend' + '</div>');
$('#containerFriends').append(wrapper);
//The following lets the user accept or decline a friend request by changing the status the status from Pending to Declined/////
wrapper.children('.decline').click(function() {
$(".decline").click(function() {
item.fetchedObject.set("status", "Rejected");
$( "#containerFriends" ).load("friends.html #containerFriends" );
item.fetchedObject.save(null, {
success: function(results) {
console.log("REJECTED");
},
error: function(contact, error) {
// The save failed.
// error is a Parse.Error with an error code and description.
alert("Error: " + error.code + " " + error.message);
}
});
});
});
});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
var channelsArray = [];
var percentArray= [];
var valueArray= [];
var jsonData,canvas,context;
var colorArray=["#ECD078","#D95B43","#C02942","#542437","#53777A"];
var posX=220;
var posY=60;
var width=55;
var graph=false;
//Webservice Request and Response begins.......................................
$.ajax({
type: "POST",
url: "http://localhost/WebSite1/myservice.asmx/GetData",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg) {
if(localStorage.getItem("channels")==null){
jsonData =jQuery.parseJSON(msg.d);
jsonToLocal();
}
var strDisplay = " <table cellspacing='0' id='myTable' " +
" <tr>" +
" <th > Channels </th>" +
" <th> Percentage</th>" +
" <th> Value</th>" +
" </tr>";
for (var i = 0; i < colorArray.length; i++) {
strDisplay = strDisplay +
" <tr style='cursor:pointer;' onclick='javascript:rotateChart("+i+")'>" +
" <td>" + channelsArray[i] + "</a> </td>" +
" <td> " + percentArray[i] + " </td>" +
" <td> " + valueArray[i] + " </td>" +
" </tr>";
}
strDisplay = strDisplay + "</table>";
document.getElementById('DynamicGridLoading').innerHTML = strDisplay;
document.getElementById('myTable').setAttribute("class","datatable");
},
error:function(xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
}
});
//Webservice Request and Response ends........................
//converting json data into local storage....
function jsonToLocal(){
for(i=0;i<jsonData.Table.length;i++){
percentArray.push(jsonData.Table[i].toString());
channelsArray.push(jsonData.Table[i].Channels);
valueArray.push(jsonData.Table[i].Value);
}
try {
localStorage.setItem("percentage", percentArray.join(","));
localStorage.setItem("channels",channelsArray .join(","));
localStorage.setItem("value",valueArray.join(","));
}
catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert("Quota exceeded!");
}
}
}
this is my almost entire code...am getting this 'uncaught' error in function jsontolocal at percentArray....if i remove this line..other two work fine.. all these arrays are pushing string values inside dem..
You have a typo :
myfucntion()
should be
myfunction();
this code works (i put the function call beneath the function because otherwise in the global scope (i tested it in firebug console) the function wasn't recognized):
var myArray=[];
function myfunction(){
myArray.push('s'); //at this point..my global array is not recognized.
}
myfunction();
alert(myArray[0]);//alert s
fiddle http://jsfiddle.net/GrpJw/1/
my problem was nothing but random and unknown behavior of javascript.. To ensure that this never happens..i found out to follow following things while writing a javascript code -:
use === to compare with a null value and 0
provide radix while using parseInt..ie..parseInt(string,radix);
always declare variables like for(var i=0;...and not for(i=0;........
these were the mistakes i was making..sometimes it would run..sometimes it would show a random behavior..anyways..my problem is solved