Calling ajax webservice from OnComplete of an ajax webservice call not firing OnComplete 2nd time - asp.net

I have an ajaxified .NET webservice that I call from javascript(mootools) on my ASP.NET content page with a Masterpage firstly to check if the user has associated journalists, secondly to delete the user if no journalists are associated.
Both calls to the webservice work, but the onComplete for the second does not in IE8.
Using FF 3.5.3 I get a "deleteUserInt is not defined" error in firebug.
I have read around that this can be a sytax error, but cannot seem to see it.
Please help.
var userId;
var siteName;
var siteFolder;
function userInternalHasUserExternals() {
siteName = document.location.href.split("/")[document.location.href.split("/").length - 1];
siteFolder = document.location.href.replace(siteName, "");
var jsonRequest = new Request.JSON({ url: siteFolder + "Service1.asmx/UserInternalHasUserExternals",
onComplete: onComplete,
onFailure: onError,
urlEncoded: false,
headers: { "Content-type": "application/json" }
});
userId = document.getElementById("<%= HiddenId.ClientID %>").innerText;
jsonRequest.send(JSON.encode({ 'userInternalId': userId }));
}
function onComplete(results) {
var fullname = document.getElementById("<%= fullnameTextBox.ClientID %>").value;
if (results != null && results["d"] != null && results["d"]) {
alert("Du kan ikke slette " + fullname + ". Kontoen har journalister tilknyttet.");
return false;
}
var deleteUser = confirm("Er du sikker på du vil slette " + fullname + "?");
if (deleteUser) {
deleteUserInt();
window.location = window.siteFolder + "CreateUserInternal.aspx?IsDeleted=true";
}
else
window.location = window.siteFolder + "EditUserInternal.aspx?UserInternalId=" + window.userId;
}
function deleteUserInt() {
var request;
request = new Request.JSON({ url: window.siteFolder + "Service1.asmx/DeleteUserInternal",
onComplete: onDeleted,
onFailure: onError,
urlEncoded: false,
headers: { "Content-type": "application/json" }
});
request.send(JSON.encode({ 'userInternalId': window.userId }));
}
function onDeleted(args) {
if (args != null && args["d"] != null && args["d"])
window.location = window.siteFolder + "CreateUserInternal.aspx?IsDeleted=true";
else
alert("Der skete en fejl. Kontakt venligst site administrator.");
}
function onError() {
alert("Something bad happened!");
}

This was "solved" after I moved my javascript out in a file and found an error using innerText instead of innerHTML.
The IE8 missing function being called also "fixed" itself after being moved.
Of course I had to pass the ClientIds, which I used in my aspx page as parameters to the new method, but that worked fine for me.
For some reason Firefox jumps the gun when I have 2 a confirm and then an alert.

Related

AEM Site search query builder URL is not returning a different json

Am using AEM Site search component from core components. query builder URL is not returning a different json.
Once after searching with a text, am getting a json. Thereafter doing any search with new search text, am getting only the same json, not a new json. Only old response am getting in all search.
var request = new XMLHttpRequest();
if (self._hasMoreResults) {
var response;
var url = self._action + "?" + serialize(self._elements.form) + "&" + PARAM_RESULTS_OFFSET + "=" + self._resultsOffset;
request.open("GET", url, true);
request.onload = function() {
setTimeout(function() {
toggleShow(self._elements.loadingIndicator, false);
toggleShow(self._elements.icon, true);
}, LOADING_DISPLAY_DELAY);
if (request.status == 200 ) {
debugger;
var data = JSON.parse(request.responseText);
if (data.length > 0) {
self._generateItems(data, self._elements.results);
self._markResults();
toggleShow(self._elements.results, true);
} else {
self._hasMoreResults = false;
}
if (self._elements.results.querySelectorAll(selectors.item.self).length % self._properties.resultsSize > 0) {
self._hasMoreResults = false;
}
} else {
// error status
}
};
toggleShow(self._elements.loadingIndicator, true);
toggleShow(self._elements.icon, false);
request.send('');
}
};

how to disable a linkButton in aspx when a certain condition is set

Let me explain my problem, I have a LinkButton:
<asp:LinkButton ID="ForceUpdate" runat="server" OnClick="ForceUpdateBtn_Click" Text="<%$ Resources:Resource1, ForceUpdate%>" />
when I click on this LinkButton I set a command and then I check with JQuery if the button is clicked to show a message to wait until the machine is online to get the updated data and then disable the button:
window.setInterval(function () {
$.ajax({
async: true,
type: 'POST',
url: "../../WS/IOT_WebService.asmx/GetUpdateStatusStats",
data: { mccid: <%=mccIdToJavascript%>, language: '<%=currentCulture%>' }, // mccid: ID machine
cache: false,
beforeSend: function () {
},
success: function (txt) {
var string = xmlToString(txt);
string = string.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("<string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("</string>", "");
console.log('check is ', <%=checkClick%>);
var check = <%=checkClick%>;
if (check) {
$('#status-force-update').text(string);
} else {
$('#status-force-update').text('----------');
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}, 3000);
Here's the method from the webservice where I check if in the db a certain data is set (CMD_Date_hour_Ok
!= null) to update the message that the machine is online and enable back the button.
[WebMethod]
public string GetUpdateStatusStats(string mccid, string language)
{
String strResponse = String.Empty;
CultureInfo currentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentCulture = currentCulture;
Thread.CurrentThread.CurrentUICulture = currentCulture;
try
{
MCC_Machine mcc = MCC_Machine.Retrieve(Convert.ToInt32(mccid));
CMD_Command cmd = CMD_Command.RetrieveByMCCType(mcc, 14); // 14 means that a ForceUpdate were launched
if (cmd == null)
{
cmd = CMD_Command.RetrieveByMCCType(mcc, 14);
}
if (cmd.CMD_Date_hour_Ok != null)
{
// machine is online
strResponse = Resources.Resource1.ForceUpdateStatsOnline.ToString();
}
else
{
// machine is offline
strResponse = Resources.Resource1.ForceUpdateStatsOffline.ToString();
}
}
catch
{
strResponse = Resources.Resource1.ForceUpdateStatsOffline.ToString();
}
return strResponse;
}
Now I need to disable the LinkButton and maybe change the color to grey to get the idea that it is disabled when I click it and enable it when the machine is online.
How can I do that?
Thank you
You need to change disabled attribute of ForceUpdate at every interval as following:
window.setInterval(function () {
$.ajax({
async: true,
type: 'POST',
url: "../../WS/IOT_WebService.asmx/GetUpdateStatusStats",
data: { mccid: <%=mccIdToJavascript%>, language: '<%=currentCulture%>' }, // mccid: ID machine
cache: false,
beforeSend: function () {
},
success: function (txt) {
var string = xmlToString(txt);
string = string.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("<string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("</string>", "");
console.log('check is ', <%=checkClick%>);
var check = <%=checkClick%>;
if (check) {
$('#status-force-update').text(string);
} else {
$('#status-force-update').text('----------');
}
if(string =="Online"){ //check is machine online then set disable false
$("#<%=ForceUpdate.ClientID %>").attr("disabled", false);
}else{ // else mean machine is offline
$("#<%=ForceUpdate.ClientID %>").attr("disabled", true);
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}, 3000);

Fullcalendar 4.x - Adding header "X-Requested-With: XMLHttpRequest"

Using Fullcalendar 4.x, is it possible to add the "X-Requested-With: XMLHttpRequest" header when fetching events ?
I'm setting up the event source in this way :
calendar.addEventSource({ url: ev_url, id: 'default' });
Everything works and the request is sent correctly, but the header i mentioned is missing (on server side we require that header to be present).
I tried adding the following to addEventSource:
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
Another thing i tried was to add this in the js file (probably pointless since Fullcalendar 4 is not using jquery anymore ?):
$.ajaxSetup({
beforeSend: function (xhr) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
}
});
Unfortunately neither solution worked.
In the past when using fullcalendar 3.x that header was present when requesting events. I guess that was because JQuery was adding it automatically.
I was looking for the answer to this as well. I modified the FullCalendar main.js file which is not ideal but does the trick!
I modified the file # around line 4242 here is the full source from that function:
/*! FullCalendar Core Package v4.3.1
function requestJson(method, url, params, successCallback, failureCallback) {
method = method.toUpperCase();
// Set Headers From Params to own varaible
var headers;
if(params.hasOwnProperty('headers') && Array.isArray(params.headers)){
headers = params.headers;
// Remove them from the params object
delete params.headers;
}
var body = null;
if (method === 'GET') {
url = injectQueryStringParams(url, params);
}
else {
body = encodeParams(params);
}
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
// Create Headers If Avaiable
if(typeof headers !== "undefined"){
for(var key in headers){
if (!headers.hasOwnProperty(key)) continue;
var obj = headers[key];
for(var prop in obj){
if (!obj.hasOwnProperty(prop)) continue;
xhr.setRequestHeader(prop, obj[prop]);
}
}
}
if (method !== 'GET') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.onload = function () {
if (xhr.status >= 200 && xhr.status < 400) {
try {
var res = JSON.parse(xhr.responseText);
successCallback(res, xhr);
}
catch (err) {
failureCallback('Failure parsing JSON', xhr);
}
}
else {
failureCallback('Request failed', xhr);
}
};
xhr.onerror = function () {
failureCallback('Request failed', xhr);
};
xhr.send(body);
}
To Use it I simply add a headers key to the extraParams object like so:
extraParams = {
action: 'get_event',
headers: [
{"X-Requested-With":"XMLHttpRequest"}
]
};
This way you can add as many extra headers as you need.

Consuming image from API and displaying it on browser in meteor

I have a API that returns image and want to display the image on the browser. I am using iron:router package. On the client side user click on a link which is a basically a server side iron:route. The route makes call to API and should display the response of API on the browser.
client js : -
Template.images.events({
'click .image': function (event, template) {
event.preventDefault();
var docId = $(event.target).attr('data-docId');
var imageType = "raw";
var param = {"docId":docId,"imageType":imageType};
params = 'width=' + window.innerWidth;
params += ', height=' + window.innerHeight;
params += ', top=0, left=0'
params += ', fullscreen=yes';
var win = window.open("/Image/?param=" + encodeURIComponent(Base64.encode(JSON.stringify(param))), "_blank", params);
}
});
Iron:route : -
Router.route('/checkImage', function () {
var decoded = Base64.decode(decodeURIComponent(this.params.query.param));
var param = JSON.parse(decoded);
var docId = param.docId;
var content="";
Meteor.call('imageApi', docId, imageType, function (error, result) {
if (error) {
content = "";
} else
content = new Buffer(result);
});
if (content == "") {
this.response.writeHeader('200', {
'Content-Type': 'image/jpeg',
'Content-Disposition': "inline",
'Access-Control-Allow-Origin': '*'
});
this.response.write('<html><body><p>No content for image found.</p></body></html>');
this.response.end();
}
else {
this.response.writeHeader('200', {
'Content-Type': 'image/jpeg'
'Content-Disposition': 'inline; filename=image.jpg'
});
this.response.write(content);
this.response.end();
}
}, {where: 'server'});
Server method : -
imageApi: function (docId, imageType) {
var url = "API url with the paramters ";
var response;
try{
response = HTTP.call('GET', url, {
headers: {"Content-Type": "image/jpeg"},
responseType: "buffer"
});
}catch (error) {
logger.error("imageApi - Exception in image API " + error);
return false;
}
if (response.statusCode == 200) {
return new Uint8Array(response.content);
}
else {
logger.error"imageApi - Response issue: " + response.statusCode);
return "";
}
return "";
}
I am not able to display the image data on the browser. Do you think something is wrong in this approach or else if there is another way to render image.

Message from webpage undefined

I am returning a simple string from a webmethod to a Javascript function.
I am using an AJAX enabled website in ASP.NET 2.0. I get the date in firefox but inside IE 8 it returns undefined.
Do I have to parse the string in the JSON format using some serialize class? In my webmethod, I am just using:
return DateTime.Now.ToString();
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=trgNo.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
$.ajax({
type: "POST",
url : pageUrl+ '/getDet',
data : '{categ: "' +trgId + '"}',
contentType:"application/json; charset=utf-8",
dataType:"json",
success:OnSuccess,
failure: function(msg){
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
alert('error fetching values from database');
}
});
});
function OnSuccess(msg)
{
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
alert(msg);
}
});
Edit
It seems the success function is firing the problem is with response 'alert(msg)' works in firefox but not in IE 8 with asp.net 2.0
Maybe you dont want to use this, but I´m very happy with the asp net ajax build in function, since it builds a header, that works properly on browsers.
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=trgNo.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
var proxy = Sys.Net.WebServiceProxy;
proxy.invoke("", // if current page "", if webservice "/srv.asmx"
"getDet", //method name
false, //post = true, get = false
{ categ : trgId }, //javascript object
OnSuccess, // Success Function
onError, // Error Function
{ yourOwn : userData } // Custom User Data to Handler
);
});
function OnSuccess(response, usercontext)
{
// usercontext.yourOwn === userData;
// response is sent WITHOUT "d", it is removed internally by the proxy
alert(response);
}
});
Dont forget to include the ScriptManager...

Resources