I've been working on this for like an hour now, but can't seem to figure it out.
The JSON response:
{"lastDate":"2013-11-22 00:00:35",
"lastId":"42460",
"response":[
{
"class":"rowgreen",
"id":"42460","date":"22 November 2013, 00:00:35\\u0026nbsp;",
"player":"\\u003Ca href=\\u0027logpersonal.php?playerName=skiwi2\\u0027\\u003Eskiwi2\\u003C\/a\\u003E\\u0026nbsp;",
"target":"\\u003Ca href=\\u0027logpersonal.php?playerName=UnholiestElite\\u0027\\u003EUnholiestElite\\u003C\/a\\u003E\\u0026nbsp;",
"weapon":"M1014 (\\u003Cb\\u003EHeadshot\\u003C\/b\\u003E)\\u0026nbsp;",
"server":"Test\\u0026nbsp;"
}
]}
This seems to be correct, now the jquery:
function longPolling() {
if (!longPollingAllowed) {
return;
}
console.log("Long polling started.");
$.ajax({
url: "logpersonal_ajax.php",
data: {
serverId: serverId,
playerName: playerName,
lastDate: lastDate,
lastId: lastId
},
cache: false,
dataType: "json",
beforeSend: function() {
longPollingBusy = true;
},
success: function(json) {
console.log("success");
$(json).each(function() {
console.log("this.lastDate = " + this.lastDate);
console.log("this.lastId = " + this.lastId)
console.log("this.response = " + this.response);
console.log(this.response);
this.lastDate = this.lastDate;
this.lastId = this.lastId;
if (this.response != "") {
this.response.each(new function() {
console.log(this);
var clazz = this.class;
console.log("clazz = " + clazz);
var id = this.id;
var date = this.date;
var player = this.player;
var target = this.target;
var weapon = this.weapon;
var server = this.server;
var string = "\t\t\t<tr class='" + clazz + "' id='" + id + "'><td>" + date + "</td><td>" + player + "</td><td>" + target + "</td><td>" + weapon + "</td><td>" + server + "</td></tr>\n";
console.log("string = " + string);
$(string).insertBefore($("#list tr.header").next());
});
}
});
if (lastDate != "" && lastId != "") {
//longPolling(serverId, playerName, lastDate);
}
longPollingBusy = false;
},
error: function(json, message) {
console.log("fail: " + message);
longPollingBusy = false;
}
});
}
The console.log("this.lastDate = " + this.lastDate); works, so does the one for this.lastId. this.response also works and nicely shows an array starting with index 0 and when expanded it you can see all elements in the developer view.
Now comes the part I cannot seem to understand: At the foreach over this.response it does not print anything useful (except Prototype skeleton) for this.
How can I access the values?
this.response.each(new function() {
This line is wrong. It should be:
this.response.forEach(function() {
P.S. I suggest doing $.each(json, function(){ instead of $(json).each(function() {.
Related
I have this jqgrid code below and I have a picture inside it and at the same time its function that I am using. But clicking the button inside my jqgrid it says Uncaught ReferenceError: clickmeapproved is not defined. Is there anything wrong with my code or the way that I am using them?. Same error with the disapproved button.
afterInsertRow: function (rowid) {
var obj = jQuery("#FiTATimeCorrectionV2List").getRowData(rowid);
var FADTLSID = obj.FitaAssignDtlID;
if (FADTLSID !== undefined) {
if (FADTLSID !== "") {
var btnApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/check.png' style='height:20px;width:20px;' style ='width: 90px' id='btnApproved" + rowid + "' onclick='clickmeapproved(" + rowid + " )' />"
var btnDisApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/delete.png' style='height:20px;width:20px;' style ='width: 90px' id='btnDisApproved" + rowid + "' onclick='clickmedisapproved(" + rowid + " )' />"
jQuery("#FiTATimeCorrectionV2List").setRowData(rowid, { FitaCorForApproval: btnApprove });
jQuery("#FiTATimeCorrectionV2List").setRowData(rowid, { FitaCorForDisApproval: btnDisApprove });
var temp = obj.FitaStatus;
if (temp == "Approved") {
$("#btnApproved" + rowid).hide();
$("#btnDisApproved" + rowid).hide();
}
else if (temp == "Disapproved") {
$("#btnApproved" + rowid).hide();
$("#btnDisApproved" + rowid).hide();
} else {
$("#btnApproved" + rowid).show();
$("#btnDisApproved" + rowid).show();
}
}
}
},
function clickmeapproved(rowid) {
var ans = confirm("Are you sure you want to approve the request of "+ globalFitaCorName +"?");
if (ans) {
$.ajax({
type: "POST",
url: '../Request/SaveFitaApproval?FAID=' + rowid,
dataType: 'json',
success: function (response) {
alert("Successfully approve!");
$("#FiTATimeCorrectionV2List").trigger("reloadGrid");
FiTATimeCorrectionV2(0);
globalFitaCorName = "";
$("#loader").hide();
},
error: function (reponse) {
$("#FiTATimeCorrectionV2List").trigger("reloadGrid");
FiTATimeCorrectionV2(0);
globalFitaCorName = "";
$("#loader").hide();
}
});
}
}
Your "clickmeapproved" function does not have global scope. Check by typing "window.clickmeapproved" in the web inspector.
Here is the code that I use to solve my issue.
var btnApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/check.png' style='height:20px;width:20px;' style ='width: 90px' id='btnApproved" + rowid + "' />"
var btnDisApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/delete.png' style='height:20px;width:20px;' style ='width: 90px' id='btnDisApproved" + rowid + "' />"
I exclude the button click from it.
$("#btnApproved" + rowid + "").click(function(){
clickmeapproved(rowid);
});
$("#btnDisApproved" + rowid + "").click(function(){
clickmedisapproved(rowid);
});
I POST my table data using ajax in database. Now I want to get back when I give click the open button.
$.ajax({
type: "POST",
url: "http://localhost/./Service/GetPageInfo",
dataType: "json",
contentType: 'application/json',
data: JSON.stringify({
filename: filename
}),
success: function (data) {
debugger;
//var p = JSON.stringify('[' + data + ']');
// alert(p.GetPageInfoResult[0])
//var k = data.main[0];
//alert(data.length);
//var jsonObj = $.parseJSON('[' + data + ']');
//alert(JSON.parse(data));
var jsonPretty = JSON.stringify(JSON.parse(data), null, 2);
},
error: function () {
alert('Error');
When I give my file name I want to display my pageinfo. I get data like
[{"main":{"sub":[],"tittle":"oops","startvalue":"21","stopvalue":"45","status":"","accumalated":"","comment":""}}]
You have not cleared where you want place your resultant Json. Below is that Success result placed in div having table . It is just a sample you may change as per your requirement:
function OnSuccess(response) {
debugger;
var xmlDoc = $.parseXML(response.d);
var xml = $(xmlDoc);
var page = xml.find("Table");
var row = "";
$('#popupdiv tbody').html('');
page.each(function () {
var page = $(this);
row = " " + page.find("tittle").text() + " " + page.find("startvalue").text() +
" " + page.find("stopvalue").text() + " " + page.find("status").text() +
" " + page.find("accumalated").text() + " " + page.find("comment").text() + "";
$('#popupdiv tbody').append(row);
});
}
I am trying to set value of input hidden, but it returns me null or 0.
function addbettrack(odd){
if($(".leagues_arr").val()!='0' && $('.games_arr').val()!='0' && $('.bet_type').val()!='0' && $('.book').val()!='0'
&& $('.bet_venue').val()!='0'){
if(odd=='undefined') odd=0.00;
var datetime = $(".games_arr").children(":selected").data('value').DateTime;
var league = $(".leagues_arr").val();
var hometeam = $(".games_arr").children(":selected").data('value').HomeTeam;
var awayteam = $(".games_arr").children(":selected").data('value').AwayTeam;
var eventname = $(".games_arr").children(":selected").data('value').EventName;
var bettype = $(".bet_type").val();
var book = $('.book').children(":selected").data('book');
var bookid = $('.book').val();
var bet = $(".bet_venue").val();
//var odd = $(".odds").val();
var stake = 1;
var marked = '';
if (bet == "Visitor") {
marked = 'A';
} else if (bet == "Host") {
marked = 'H';
} else {
marked = '';
}
var source = 'bettrack';
var id = $('.hidden_id').val();
var mode = "insert";
if(id > 0){
mode = "edit";
}
console.log(id + " " + mode);
console.log(datetime + " " + league + " " + hometeam + " " + awayteam + " " + eventname + " " + bettype + " " + bet + " " + odd + " " + stake);
$.ajax({
type: "POST",
url: '/index.php?/bettrack/insert_bettip/'+id,
data: {
DateTime: datetime,
LeagueName: league,
HomeTeam: hometeam,
AwayTeam: awayteam,
EventName: eventname,
BetType: bettype,
Bet: bet,
Book: book,
BookID: bookid,
Odd: odd,
Stake: stake,
Marked: marked,
Source: source,
Id : id,
Mode : mode
},
dataType:"json",
success: function(data) {
console.log(data);
$('.hidden_id').attr('value',data.odd);
$('.hidden_id').val(data.odd);
alert($('.hidden_id').val()); //here returns nothing
},
error: function(xhr, textStatus, error) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
}
this function runs inside other function and ajax request:
function get_bettrack(eventname, bettype, betvenue, book, mode = "a", id = 0) {
console.log(eventname+" "+bettype+" "+betvenue + " " + book);
$.ajax({
type: "POST",
url: '/index.php?/bettrack/get_odds',
data: {
EventName: eventname,
BetType: bettype,
BetVenue: betvenue,
Book: book
},
dataType: 'json',
success: function(data) {
if (mode == "a") {
console.log(data.odd);
$(".odds").val(data.odd);
var stake = 1;
var towin = parseFloat(data.odd) * parseFloat(stake);
$(".towin").html(towin);
addbettrack(data.odd); //HEREEE <=====================
} else {
$(".myodd" + id).val(data.odd);
var stake = 1;
var towin = parseFloat(data.odd) * parseFloat(stake);
$(".towin" + id).html(towin);
}
},
error: function(xhr, textStatus, error) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
and also get_bettrack function runs inside an event inside ajax success:
$('.games_arr').change(function() {
var date = $(this).children(":selected").data('value').DateT;
var label = date;
$(".game_date").html(label);
if ($('.leagues_arr').val() != '0') {
$(".bet_type").val("ToWin");
$(".bet_venue").val("Host");
var eventname = $(".games_arr").children(":selected").data('value').EventName;
var betvenue = $(".bet_venue").val();
var bettype = $(".bet_type").val();
var book = $(".book").children(':selected').data('book');
load_book(eventname, bettype);
get_bettrack(eventname, bettype, betvenue, book);
}
});
<input type="hidden" class="hidden_id" value="0" />
I have a javascript code as below
var xReg = '<region><width>' + $("#txtWidth").val() + '</width> <height>' + $("#txtHeight").val() + '</height><float>' + $("#floats").val() + '</float><contenttype>' + $("#contenttype").val() + '</contenttype><style>' + rgnStyle + '</style></region>';
$.ajax({
type: "POST",
url: "myurl/addRegion",
data: "{pubId: '" + Number($("#pubs").val()) + "',section: '" + $("#sections option:selected").text() + "',layoutW: '" + Number($("#txtLayoutW").val()) + "',layoutH: '" + Number($("#txtLayoutH").val()) + "',bSubReg: '" + Boolean($("#chkSubRegion").is(':checked')) + "',parentRegId: '" + Number(parentRgn) + "',sXmlRegion: '" + xReg.toString() + "'}",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (result) {
document.body.style.cursor = 'pointer';
if (result.d == -1) {
$("#errMsg").text("Failed to create new region");
}
else {
if ($("#chkSubRegion").is(':checked')) {
$("#regions").append("<option class='ddindent' value='" + result.d + "'>REGION-" + result.d.toString() + "</option>");
} else {
$("#subregions").append("<option class='ddindent' value='" + result.d + "'>SUBREGION-" + result.d.toString() + "</option>");
}
}
},
error: function (result) {
if (result.status == 200 && result.statusText == 'OK') {
if ($("#chkSubRegion").is(':checked')) {
$("#regions").append("<option class='ddindent' value='" + result.d + "'>REGION-" + result.d.toString() + "</option>");
} else {
$("#subregions").append("<option class='ddindent' value='" + result.d + "'>SUBREGION-" + result.d.toString() + "</option>");
}
}
else {
alert("FAILED : " + result.status + ' ' + result.statusText);
}
},
async: true
});
Server code as below
[WebMethod]
public int addRegion(int pubId, string section, int layoutW, int layoutH, bool bSubReg, int parentRegId, string sXmlRegion)
{
string path = Server.MapPath("~");
path = Path.Combine(path, "Published");
path = Path.Combine(path, pubId.ToString());
path = Path.Combine(path, section);
XmlDocument doc = new XmlDocument();
int rgnCount = 0;
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
path = Path.Combine(path, "layout.xml");
if (!File.Exists(path))
{
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode templateNode = doc.CreateElement("layout");
doc.AppendChild(templateNode);
XmlNode xNodeW = doc.CreateElement("width");
xNodeW.AppendChild(doc.CreateTextNode(layoutW.ToString()));
XmlNode xNodeH = doc.CreateElement("height");
xNodeH.AppendChild(doc.CreateTextNode(layoutH.ToString()));
}
else
{
doc.Load(path);
doc.DocumentElement.SelectSingleNode("/layout/width").InnerText = layoutW.ToString();
doc.DocumentElement.SelectSingleNode("/layout/height").InnerText = layoutH.ToString();
}
XmlElement root = doc.DocumentElement;
XmlNode xParent = root;
if (bSubReg)
{
xParent = root.SelectSingleNode("/layout/region[id='" + parentRegId.ToString() + "']");
rgnCount = xParent.SelectNodes("/region").Count;
}
else
{
rgnCount = root.SelectNodes("/Layout/region").Count;
}
rgnCount++;
XmlDocumentFragment docFragment = doc.CreateDocumentFragment();
docFragment.InnerXml = sXmlRegion;
XmlNode xID = doc.CreateElement("id");
xID.AppendChild(doc.CreateTextNode(rgnCount.ToString()));
docFragment.FirstChild.AppendChild(xID);
xParent.AppendChild(docFragment);
doc.Save(path);
return rgnCount;
}
catch (Exception eX)
{
return -1;
}
}
The call is going to server from client. And no issues I could find in server code till last return statement while I debugged it. In the javascript debugging I found that after ajax call is always going to error callback function. Can anyone suggest whats wrong with the code.
Thanks & Appreciate Your Time.
I found the bug in my code there is issue with below lines of code
},
async: true
at the end of error: callback function
I removed the line async: true and it worked
This program right now reads in xml code, gets a stock abbreviation, alphabetically sorts them, and then prints them out in an uo list. If you hover over the abbreviations the color will change to red. The goal I'm having is when you hover over an abbreviation, it will show all the data from the xml data just for that company. I tried using the if statement saying if the symbol (abbreviation in xml file) is equivalent to the name (abbreviation in array) then it prints out all the junk for it. The line that prints everything out works correctly in the format I want. I just need to work on the if statement.
What I have figured out is I cannot compare two variables with the ==. Keep in mind symbol is an attribute as well, and name is from an array that stores the symbols. I also tried just saying - if(checkPassword(name, symbol)) - and print it all out as I did in the jQuery code below, but that did not work.
I put a comment next to the if statement I am working on, it's towards the bottom of the jQuery.
HTML:
<body onload="onBodyLoad()">
<div id="stockList"></div>
<br />
<br />
<br />
<div id="stockInfo"></div>
jQuery:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "stocks.xml",
dataType: "xml",
success: function (xml) {
var companyNames = [];
$(xml).find('Stock').each(function () {
var symbol = $(this).attr('symbol');
companyNames.push(symbol);
});
companyNames.sort();
$.each(companyNames, function (index, name) {
$('#stockList').append('<div><li>' + name + '</li></div>');
});
function CheckPassword(val, val2) {
var strInput = val.value;
var strInput2 = val2.value;
if (strInput != strInput2) {
val2.focus();
val2.select();
return false;
} else
return true;
}
$(xml).find('Stock').each(function () {
var company = $(this).find('Company').text();
var symbol = $(this).attr('symbol');
var market = $(this).find('Market').text();
var sector = $(this).find('Sector').text();
var price = $(this).find('Price').text();
var low = $(this).find('Low').text();
var high = $(this).find('High').text();
var amount = $(this).find('Amount').text();
var yieldx = $(this).find('Yield').text();
var frequency = $(this).find('Frequency').text();
$('*').mouseover(function () {
$('#stockList li').text($(this).attr('comparison'));
});
$('#stockList li').hover(
function () {
$(this).css({ color: 'red' }); //mouseover
if (name == symbol) { // THIS IS THE STATEMENT YOU'RE LOOKING FOR PROGRAMMING GODS
$('#stockInfo').append('<div><ol><li>' + "Company = " + company + '</li><br/><li>' + "Market = " + market + '</li><br/><li>' + "Sector = " + sector + '</li><br/><li>' + "Price = " + price + '</li><br/><li>' + "Year Range = " + low + " " + high + '</li></ol><br/>');
}
},
function () {
$(this).css({ color: 'navy' }); // mouseout
$('#stockInfo').empty();
}
);
});
}
});
});
XML sample:
<Products>
<Stock symbol="GOOG">
<Company>Google</Company>
<Market>NASDAQ</Market>
<Sector>Software</Sector>
<Price>$487.80</Price>
<YearRange>
<Low>$331.55</Low>
<High>$488.50</High>
</YearRange>
<Dividend available="false"/>
</Stock>
<Stock symbol="BA">
<Company>Boeing Company</Company>
<Market>NYSE</Market>
<Sector>Aerospace</Sector>
<Price>$79.05</Price>
<YearRange>
<Low>$63.70</Low>
<High>$89.58</High>
</YearRange>
<Dividend available="true">
<Amount>$1.20</Amount>
<Yield>$1.50</Yield>
<Frequency>QTR</Frequency>
</Dividend>
</Stock>
<Stock symbol="MO">
<Company>Altria Group</Company>
<Market>NYSE</Market>
<Sector>Comsumables</Sector>
<Price>$81.70</Price>
<YearRange>
<Low>$68.36</Low>
<High>$85.00</High>
</YearRange>
<Dividend available="true">
<Amount>$3.44</Amount>
<Yield>$4.2</Yield>
<Frequency>ANNUAL</Frequency>
</Dividend>
</Stock>
</Products>
var companyData = [];
$(xml).find('Stock').each(function () {
var symbol = $(this).attr('symbol');
companyNames.push(symbol);
companyData[symbol] = {
company: $(this).find('Company').text(),
symbol: $(this).attr('symbol'),
market: $(this).find('Market').text(),
sector: $(this).find('Sector').text(),
price: $(this).find('Price').text(),
low: $(this).find('Low').text(),
high: $(this).find('High').text(),
amount: $(this).find('Amount').text(),
yieldx: $(this).find('Yield').text(),
frequency: $(this).find('Frequency').text()
};
});
...
$("#stocklist li").hover(function() {
$(this).css({ color: 'red' }); //mouseover
var info = companyData[$(this).text()];
$('#stockInfo').append('<div><ol><li>' + "Company = " + info.company + '</li><br/><li>' + "Market = " + info.market + '</li><br/><li>' + "Sector = " + info.sector + '</li><br/><li>' + "Price = " + info.price + '</li><br/><li>' + "Year Range = " + info.low + " " + info.high + '</li></ol><br/>');
});