Uncaught ReferenceError: Error not defined - javascript

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);
});

Related

How to append an image to a specific class

I have multiple classes with the same tag (.offer) I am going through a loop and it adds the image to all my .offer divs. I just want to add the image specific to the user who posted. How can I do this? Assume the backend is working completely fine
jQuery (1st function)
function getOffers(key) {
dict = {
'key': key// pk value of post sent to retrieve offers to it
};
generateCSRFToken();
$.ajax({
url: "/retrieve_offers/",
method: "POST",
data: JSON.stringify(dict),
success: function (data) {
data = JSON.parse(data);
console.log(appendUserImage(38));
$("#offercontainer").empty();
$(".offer").empty();
for (var i = 0; i < data.length; i++) {
var string = data[i].fields.author_name;
$("#offercontainer").append(
"<div class='offer'>" +
"<p class=offername>" + string + "</p>" +
"<p class=offertext> offered his " + " " + data[i].fields.item_name + "</p>" +
"</div>"
);
appendUserImage(data[i].fields.author);
}
},
error: function () {
}
})
}
jQuery (2nd function)
function appendUserImage(key) {
dict = {
'key': key// pk value of post sent to retrieve offers to it
};
generateCSRFToken();
$.ajax({
url: "/get_user/",
method: "POST",
data: JSON.stringify(dict),
success: function (data) {
$('<img />', {
src: data["image"],
class: "offer_user_image"
}).appendTo($('.offer'))
},
error: function () {
}
});
}
I just want to append the image to its respective offer div pls help
you can pass to appendUserImage the div getOffers function creates or do something like this, add an unique key selector to the created .offer container and targeting it in the appendUserImage function.
in function getOffers(key) {
$("#offercontainer").append(
"<div class='offer' data-author-key='" + data[i].fields.author +"'>" +
"<p class=offername>" + string + "</p>" +
"<p class=offertext> offered his " + " " + data[i].fields.item_name + "</p>" +
"</div>");
appendUserImage(data[i].fields.author);
in function appendUserImage(key) {
$('<img />', {
src: data["image"],
class: "offer_user_image"
}).appendTo($('.offer[data-author-key="' + key + '"]'))
thanks for the people who tried answering I managed to fix my problem by using nth child and doing this:
for (var i = 0; i < data.length; i++) {
var string = data[i].fields.author_name;
$("#offercontainer").append(
"<div class='offer'>" +
"<p class=offername>" + string + "</p>" +
"<p class=offertext> offered his " + " " + data[i].fields.item_name + "</p>" +
"</div>"
);
appendUserImage(i,data[i].fields.author);
}
2nd function:
function appendUserImage(i,key) {
dict = {
'key': key// pk value of post sent to retrieve offers to it
};
generateCSRFToken();
$.ajax({
url: "/get_user/",
method: "POST",
data: JSON.stringify(dict),
success: function (data) {
$('<img />', {
src: data["image"],
class: "offer_user_image"
}).appendTo($('.offer:nth-child(' + (i+1) + ')'))
},
error: function () {
}
});
}

Incrementally load a webpage: Where can I put: $("#LoadingImage").Hide();

I am not very experienced with JavaScript. Please see the code below:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
}
}
}
}
window.onload = GetSQLTable
</script>
The code incrementally builds a webpage i.e. x number of HTML tables are obtained and displayed to the webpage as and when they become ready. This works.
The problem is I don't know how to remove the LoadingImage once the webpage is complete i.e. $("#LoadingImage").hide();. OnSuccess is called x number of times depending on how many tables are returned so I cannot put it in there.
One way would be to count the number of successful onSuccess() calls, and hide your loading image when they are all complete:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
var numSucceeded = 0;
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
numSucceeded++;
if (numSucceeded === totalrows) {
$("#LoadingImage").hide();
}
}
}
}
}
window.onload = GetSQLTable
</script>
Try using .when with an array of your ajax calls. Something like this (simplified to remove the irrelevant bits):
function GetSQLTable() {
//...
var calls = [];
for (var i = 0; i < res.length; i++) {
//..
calls.push($.ajax({
type: "POST",
//..
}));
}
$.when(calls).then(function(d) {
// all done!!!
});

JQuery access some JSON data

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() {.

Dynamic jquery AJAX upload form with text and file fields

I am trying to make a dynamic form wherein a single item has a file, text and select html input types and number of items can be dynamic. The problem is when doing AJAX using jquery, the Form wont serialize for the file input type. Please suggest any technique to do it. My code is below:
<form id="Form1" enctype="multipart/form-data">
<div id="divMain"></div>
<div>
<button id="Upload" type="button" value="Upload"><span>Upload</span></button>
<input id="Add" type="button" value="Add" />
</div>
</form>
<div id="status"></div>
<script type="text/javascript">
var counter = 0;
AddElements(); //add first element
$("#Add").click(function () {
AddElements();
});
function AddElements() {
counter++;
$("#divMain").append("<div><input id='Browse" + counter + "' name='Browse[]' type='file' value='Browse' data-target='#Name" + counter + "' />" +
"<input id='Name" + counter + "' name='Name[]' type='text'/>" +
"<select id='Type" + counter + "' name='Type[]'>" +
"<option>Option1</option>" +
"<option>Option2</option>" +
"</select></div>");
$("#Browse" + counter + "").change(function () {
var filename = $(this).val();
var textbox = $($(this).attr("data-target"));
var lastIndex = filename.lastIndexOf("\\");
var b = filename.lastIndexOf(".");
if ((b == -1) | (b < lastIndex))
filename = filename.substring(lastIndex + 1);
else
filename = filename.substring(lastIndex + 1, b - lastIndex - 1);
textbox.val(filename);
});
}
$("#Upload").click(function (e) {
e.preventDefault();
$("#status").html('Uploading....');
var ajaxData = $("#Form1").serialize();
$.ajax({
url: "AjaxPostDemo.aspx",
type: "POST",
data: ajaxData,
cache: false,
processData: false,
success: function (data) {
$("#status").html("success: " + data);
},
error: function (result) {
$("#status").html("error: " + result);
}
});
});
</script>
Change Your To script It Will Definately Work. :-)
<script type="text/javascript">
var counter = 0;
$(document).ready(function () {
AddElements(); //add first element
$("#Add").click(function () {
AddElements();
});
function AddElements() {
counter++;
$("#divMain").append("<div><input id='Browse" + counter + "' name='Browse[]' type='file' value='Browse' data-target='#Name" + counter + "' />" +
"<input id='Name" + counter + "' name='Name[]' type='text'/>" +
"<select id='Type" + counter + "' name='Type[]'>" +
"<option>Option1</option>" +
"<option>Option2</option>" +
"</select></div>");
$("#Browse" + counter + "").change(function () {
var filename = $(this).val();
var textbox = $($(this).attr("data-target"));
var lastIndex = filename.lastIndexOf("\\");
var b = filename.lastIndexOf(".");
if ((b == -1) | (b < lastIndex))
filename = filename.substring(lastIndex + 1);
else
filename = filename.substring(lastIndex + 1, b - lastIndex - 1);
textbox.val(filename);
});
}
});
$(document).ready(function () {
$("#Upload").click(function (e) {
e.preventDefault();
$("#status").html('Uploading....');
var ajaxData = $("#Form1").serialize();
$.ajax({
url: "AjaxPostDemo.aspx",
type: "POST",
data: ajaxData,
cache: false,
processData: false,
success: function (data) {
$("#status").html("success: " + data);
},
error: function (result) {
$("#status").html("error: " + result);
}
});
});
});
</script>
Second Option
http://www.uploadify.com/documentation/uploadify/multi/
Prefer This It will Uploaded Multifiles on one time with great UI. :-)

Jquery Ajax Call always returns error

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

Categories

Resources