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
Related
$('#save').click(function() {
var loopvalue = "<?php echo $count; ?>"
var datajson = '[';
//alert(loopvalue + "length of array")
for (i = 1; i < loopvalue; i++) {
var fetchid = '.A' + i;
var fetchid_code = '.C' + i;
datajson = datajson + "{" + "maincode :" + $('#company').val() + ",acode : " + $(fetchid_code).text() +
" , Amount :" + $(fetchid).val() + ", periodfrom :" + $('#dFrom').val() +
", periodto : " + $('#dTo').val() + ", danounc : " + $('#dano').val() +
", period : " + $('#period').val() + ", fyear : " + $('#fyear').val() +
", frequency : " + $('#freq').val() + ", stype : " + $('#stype').val() +
", sseq : " + $('#sseq').val() + " }, "
}
datajson = datajson + ']'
//console.log(datajson);
$.ajax({
type: 'POST',
url: 'jsondecode.php',
data: {
datajson: JSON.stringify(datajson)
},
//data:postArray,
dataType: "json",
success: function(data) {
console.log("success:", data);
},
failure: function(errMsg) {
console.error("error:", errMsg);
}
});
});
first i remove last comma in json object and second when i am calling ajax page but it is displaying NULL value in jsonencode.php page how can I solve this problem any can suggest me this is my server site script now
<?php
header('Content-Type: application/json');
$data = json_decode($_POST["datajson"]);
// will echo the JSON.stringified - string:
echo $_POST["datajson"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach ($data as $Object) {
echo "maincode: " . $Object->maincode . ", Acode: " . $Object->acode . "<br/>";
}
?>
Or maybe you should use actual object instead of string-concatenation
Try this
var datajson = [];
for (i = 1; i < loopvalue ; i++)
{
var fetchid = '.A' + i;
var fetchid_code = '.C' + i;
var obj = {
maincode : $('#company').val(),
acode : $(fetchid_code).text(),
Amount : $(fetchid).val(),
periodfrom : $('#dFrom').val(),
periodto : $('#dTo').val(),
danounc : $('#dano').val(),
period : $('#period').val(),
fyear : $('#fyear').val(),
frequency : $('#freq').val(),
stype : $('#stype').val(),
sseq : $('#sseq').val()
}
datajson.push( obj );
}
datajson = JSON.stringify( datajson ); //converting to string here
Before you append ] to datajson, substring that value to remove last ,. That is.
datajson = datajson.toString().subString(0, datajson.toString().length - 1);
Then Append ]
It is not needed to use JSON.stringify(datajson) in data attribute of $.ajax because you are sending the json string. not json object.
Hope this helps
Write the single elements of your look into an array and then join the elements.
See here: javascript join
But of course building JSON yourself is not necessary. Use JSON.stringify for that.
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>
I'm trying to add a simple 'wait box' on a javascript function, like this:
function caricaElenco(indice) {
(...)
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
(...)
$("[id*=Wait1_WaitBox]").hide();
}
And it's working good on Firefox, but not on Internet Explorer 11, that's not showing it. The HTML is:
<div id="ctl00_Wait1_WaitBox" class="updateProgress">
Attendere...<br />
<img src="../Images/wait.gif" align="middle" />
</div>
The weirdest thing is that I try this, for a simple check:
function caricaElenco(indice) {
(...)
alert($("[id*=Wait1_WaitBox]").css('display'))
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
alert($("[id*=Wait1_WaitBox]").css('display'))
(...)
$("[id*=Wait1_WaitBox]").hide();
}
And it's working, I mean that it's showing the alert with 'none' and after 'block'... And it's showing the box too! But not without the alert... Why?
UPDATE:
Tried with [id*="Wait1_WaitBox"], but it's the same. jQuery version is 1.8.2.
With
it's working only with the alert
I mean that if I do:
function caricaElenco(indice) {
(...)
alert('whatever');
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
alert('whatever');
(...)
$("[id*=Wait1_WaitBox]").hide();
}
It's showing the box, but if I do:
function caricaElenco(indice) {
(...)
$("[id*=Wait1_WaitBox]").show(); // Visualizzo 'rotella' caricamento
(...)
$("[id*=Wait1_WaitBox]").hide();
}
It's not working (I mean not showing the 'wait box', but doing all the other stuff the function has to do in (...) correctly—load a gridview with an AJAX call) on Internet Explorer 11, in Firefox are both working. No JavaScript error.
UPDATE 2:
Almost entire javascript function:
// Fill part of gridView
function loadList(index) {
index = parseInt(index);
buffer = 100; // Number of rows to load
$("[id*=divGrid]").unbind('scroll');
$('[id*="Wait1_WaitBox"]').show(); // Show loading 'wheel'
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "PageName.aspx/webMethodName",
data: '{id:' + $("[id*=hdnID]").val() + ', index:' + index + '}',
dataType: "json",
async: false,
success: function (response) {
if (index == 0) {
(...)
$("[id*=grid] tr:last-child").remove();
var row = "<tr class='" + response.d[index].State + "'>";
row += "<td class="Column1"></td>";
(...)
row += "<td class="DateColumn"></td>";
(...)
row += "<td class='columnN'></td></tr>";
$("[id*=grid]").append(row);
}
row = $("[id*=grid] tr:last-child").clone(true);
$("[id*=grid] tr:last-child").remove();
if (index <= response.d.length) {
if (index + buffer > response.d.length)
var stop = response.d.length;
else
var stop = index + buffer;
(...)
for (var i = index; i < stop; i++) {
var j = 0;
(...)
$("td", row).eq(j).html("<span id='lblCodeNumber" + i + "' >" + response.d[i].CodeNumber + "</span>"); j++;
(...)
var effectDate = new Date(parseInt(response.d[i].effectDate.substr(6)));
$("td", row).eq(j).html(effectDate.getDate() + '/' + (effectDate.getMonth() + 1) + '/' + effectDate.getFullYear()); j++;
}
(...)
var toBeCounted = "";
var checked = "";
if (response.d[i].ToBeCounted != null)
toBeCounted = response.d[i].ToBeCounted .toString();
else
toBeCounted = "true";
if (toBeCounted == "true")
checked = "checked = 'checked'";
else
checked = "";
var rdToBeCounted = "<span><input type='radio' class='radio' " + checked + " name='ToBeCounted" + i + "' value='s' id='sToBeCounted" + i + "' />";
rdToBeCounted += "<label for='s" + i + "'>YES</label>";
if (toBeCounted == "false")
checked = "checked = 'checked'";
else
checked = "";
toBeCounted += "<input type='radio' class='radio' " + checked + " name='ToBeCounted" + i + "' value='n' id='nToBeCounted" + i + "' />";
rdToBeCounted += "<label for='n" + i + "'>NO</label></span>";
$("td", row).eq(j).html(rdToBeCounted);
$("[id*=grid]").append(riga);
(...)
riga = $("[id*=grid] tr:last-child").clone(true);
}
if (stop < response.d.length) {
$("[id*=divGrid]").scroll(function (e) {
if (element_in_scroll(".congruenti tbody tr:last")) {
loadList($(".congruenti tbody tr:last td:last").html());
};
});
}
$('[id*="Wait1_WaitBox"]').hide();
}
},
error: function (result) {
alert("Error! " + result.status + " - " + result.statusText);
}
});
}
At the end you seem to be hiding it again $("[id*=Wait1_WaitBox]").hide();.
You need to show what goes in between these two lines.
It works with alert because the execution of the script is frozen until you close the alert (and that final line is not executed yet).
EDIT: It's telling me that my li is an illegal token. Still not sure what to do about this as I thought I was appending inside a ul
So I have to fetch a JSON array of some public Github repos and append the title, link, description, and basic information from the first 10 commits of each repo to the page. I already have the title, link and description working, but I'm lost when it comes to bringing in the commits. They're located at a different address than the initial information, so I made a second ajax request inside my first one to the commits address, but nothing is working. It may just be a syntax error or something as I've found from extensive searching that it is possible to nest ajax requests.
Here's my code, chopped up into each separate function (I've replaced the org name with 'name' for anonymity's sake):
main function:
function main() {
$.ajax({
type: 'GET',
url: 'https://api.github.com/orgs/name/repos',
error: function(xhr, status, error){
//var err = eval("(" + xhr.responseText + ")");
var err = JSON.parse(xhr.responseText);
alert(err.Message);
},
complete: function(data){
display_content(data);
}
});
}
main();
content display function:
function display_content(_data){
for (var i = 0; i < _data.responseJSON.length; i++) {
$("#listing").append(
"<h2>" +
"" + _data.responseJSON[i].full_name + "</h2>" +
"<p>" + _data.responseJSON[i].description +
"<h3>Latest Commits</h3>" +
"<ul id= \"" + _data.responseJSON[i].name + "commits\">"
);
commits(_data.responseJSON[i].name);
$('#listing').append(
"</ul>" +
"</p>" +
"<br/>"
);
}
}
commit information function:
function commits(repo){
$('#listing').find('h3').text("Latest Commits to user/" + repo);
return $.ajax({
type: 'GET',
url: 'https://api.github.com/repos/user/' + repo + '/commits',
error: function(xhr, status, error){
//var err = eval("(" + xhr.responseText + ")");
var err = JSON.parse(xhr.responseText);
alert(err.Message);
},
complete: function(commit_data){
for(var i = 0; i < 10; i++){
$('#listing').append(
"<li>
<div>
<img src=\"" + commit_data.responseJSON[i].author.avatar_url + "\">
<a href=\"https://github.com/" + commit_data.responseJSON[i].author.login + "\">
<b>" + commit_data.responseJSON[i].author.login + "</b>
</a>
<b>" + ($.timeago(commit_data.responseJSON[i].commit.committer.date)) + "</b><br />
<i>SHA: " + commit_data.responseJSON[i].sha + "</i>
</div>
<a href=\"https://github.com/user/" + repo + "/commit/" + commit_data.responseJSON[i].sha +
"\" target=\"_blank\">" + commit_data.responseJSON[i].commit.message +
"</a>
</li>"
);
}
}
});
}
I know it's a lot of code, I apologize in advance. I know the problem lies somewhere in the last two functions but I wanted to include everything to be sure.
If anyone has any experience with grabbing and parsing Git repo info I would really appreciate any advice on this. I'm willing to scrap everything and start over if need be to make this work, but I would like to avoid using any libraries aside from jQuery.
Thank you to anyone who helps! I appreciate it.
It's telling me that my li is an illegal token. Still not sure what to do about this as I thought I was appending inside a ul
You are using multi-line string literal for adding html. The line breaks need to be escaped, and this can be done via a backslash.
Change to
function commits(repo){
$('#listing').find('h3').text("Latest Commits to user/" + repo);
return $.ajax({
type: 'GET',
url: 'https://api.github.com/repos/user/' + repo + '/commits',
error: function(xhr, status, error){
//var err = eval("(" + xhr.responseText + ")");
var err = JSON.parse(xhr.responseText);
alert(err.Message);
},
complete: function(commit_data){
for(var i = 0; i < 10; i++){
$('#listing').append(
"<li>"+
"<div>"+
"<img src=\"" + commit_data.responseJSON[i].author.avatar_url + "\">"+
"<a href=\"https://github.com/" + commit_data.responseJSON[i].author.login + "\">"+
"<b>" + commit_data.responseJSON[i].author.login + "</b>"+
"</a>"+
"<b>" + ($.timeago(commit_data.responseJSON[i].commit.committer.date)) + "</b><br />"+
"<i>SHA: " + commit_data.responseJSON[i].sha + "</i>"+
"</div>"+
"<a href=\"https://github.com/user/" + repo + "/commit/" + commit_data.responseJSON[i].sha +
"\" target=\"_blank\">" + commit_data.responseJSON[i].commit.message +
"</a>"+
"</li>"
);
}
}
});
}
I've been trying to get this right for quite some time, I'm trying to append the object from the first ajax call after the second ajax call. But the for loop seems to iterate the changing of the value to the last result before appending the information, having the last post appended every time.
var scribjson =
{
"user_id" : localStorage.viewing,
};
scribjs = JSON.stringify(scribjson);
var scrib = {json:scribjs};
$.ajax({
type: "POST",
url: "getScribbles.php",
data: scrib,
success: function(result)
{
var obj = jQuery.parseJSON(result);
for(var i = 0; i < obj.length; i+=1)
{
var userjson =
{
"user_id" : obj[i].user_id
};
userjs = JSON.stringify(userjson);
var user = {json:userjs};
localStorage.post = obj[i].post;
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
}
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
Since ajax calls It looks like the all success functions of the inner ajax call are being called after the loop has ended, so i will always be the last iterated value.
Try this:
(function(i)
{
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
})(i);
This will create a closure on i, which will give each ajax call its own copy of the current value.
Use an IIFE:
success: (function(i){return function(result) {
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
}})(i),
etc. Currently your loop generated ajax success handlers contain a direct reference to the counter itself, which (by the time they are called) has reached its final value.