How can we call AJAX in Firefox - c#

I am making an AJAX call using the XMLHttpRequest.
It's working fine in IE7, but when i try the same in Firefox, I am not able to get it back thru the response.write
I am using the function below:
<script type="text/javascript">
function ddSelect_Change() {
var xmlhttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
}
}
}
xmlhttp.onreadystatechange = function () {
//alert(xmlhttp.responseText);
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
}
}
var url = "http://" + location.hostname + "Locationurl?Method=methodname";
xmlhttp.open("POST", url);
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send();
}
ADDED
I have two separate web application one is tridion web application and other is custom web application. and i am making interaction from tridion web application to custom web application. Both the url are having different domain.and state i am getting 0 in firefox, and for readystate i am not getting (3) in my alert.

The code you've shown so far should work in Firefox. Firefox support XHR.
This might be at help: https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
Update:
onreadystatechange is fired several times during an AJAX call, so you probably want to extend your callback to something like this:
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
alert(xmlhttp.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
xmlhttp.readyState === 4 verifies that the request has completed, so that you don't try to alert the response before you actually have it. xmlhttp.status === 200 verifies that you recieved a 200 OK from the server, to make sure that there were no server-side errors, or that the URL was incorrect.

Have you considered using a library like jQuery? It already has taken care of these issues for you.
If you are working on a SDL Tridion GUI extension, check out the PowerTools project for a ton of examples. (http://code.google.com/p/tridion-2011-power-tools/)

Related

Why does my function stop working without an alert?

So I've got this function right here in my view:
function izbrisi() {
var b = document.getElementById('proizvod').value;
{
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: { id: b }
}).done(function () {
alert('Izbrisan');
});
alert('Izbrisan'); #* bez ovoga se ne brise proizvod *#
}
}
The controller it's passed to:
public ActionResult izbrisiProizvod(int Id)
{
RadniProizvod.IzbrisiProizvod(Id);
return View();
}
And finally the "IzbrisiProizvod" method:
public void IzbrisiProizvod(int IdProizvoda)
{
Proizvod izbrisaniProizvod = azilEntities.Proizvods.FirstOrDefault(x => x.idProizvoda == IdProizvoda);
azilEntities.Proizvods.Remove(izbrisaniProizvod);
azilEntities.SaveChanges();
}
For whatever reason, if I don't add the final alert (the one where there's a comment), the code just will not work. Nothing gets deleted, nothing gets reported to the console. As soon as I add in the final alert, it will magically start working.
Can someone explain this magic to me?
Always write your jquery functions like this, as per documentation. (The always is optional)
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
So in your case:
function izbrisi() {
var b = document.getElementById('proizvod').value;
{
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: { id: b }
}).done(function () {
alert('Izbrisan');
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});
}
}
And maybe change alerts to console log or similar.
Try Network tool within your browser dev tools. For example for Firefox Dev Tools. When you click your element (let's say button) you should see new http request in the list of all request within Network tool. If you don't then your ajax call didn't happen at all or it was happen on previous page because you've experienced page reloading. Check if Proizvod actually deleted. If it is then your js function works but you don't see response. If there is s new http request within Network tool, inspect it a little bit to see what is happen (just click on it and in the right you will see details).
Also, you can open console and instead click the html element type in your console: izbrisi(). Function should execute and if it works you will see a new http request in Network tool and your alert for done will popup. If this is the case then your html element has default behavior on click event. So you should prevent it in order to prevent page reloading. Let say that you use a button for click on it. The button html should look like:
<button onclick="izbrisi(e)">Izbrisi</button>
And the js function:
function izbrisi(e) {
e.preventDefault();
// ... your code goes here
}
For whatever reason, if I don't add the final alert (the one where there's a comment), the code just will not work. Nothing gets deleted, nothing gets reported to the console. As soon as I add in the final alert, it will magically start working.
Your ajax only contains the .done() promise callback. This will only execute if the ajax request receives a 200 success code. You can add in the .fail() promise to with a unique alert to see what is happening.
In your code, the final alert is fired no matter what.
Try this to help see what is going on. Use this fiddle and open your console also. Note the different alert messages in the .done() and .fail() promises.
//var b = document.getElementById('proizvod')?.value;
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: {
id: 'someData'
}
}).done(function() {
alert('success');
}).fail(function() {
alert('error');
});
console.log('i fire no matter what');

Export iCal from database

I'm trying to figure out how to be able to export an iCal file from my calendar. I can't get it to work, it does not start to "download" the file.
Right now I just try to get one meeting, but later on I will make a for loop to get all the meetings in the database to the iCal file, but I just want to check if it works, but it does not.
This below is my method in the controller and later the jQuery to call the method.
[HttpPost]
public ActionResult AddToICalendar()
{
var ctx = new OruBloggenDbContext();
var meetings = ctx.Meetings.FirstOrDefault(u => u.MeetingID == 1);
var icalStringbuilder = new StringBuilder();
icalStringbuilder.AppendLine("BEGIN:VCALENDAR");
icalStringbuilder.AppendLine("PRODID:-//MyTestProject//EN");
icalStringbuilder.AppendLine("VERSION:2.0");
icalStringbuilder.AppendLine("BEGIN:VEVENT");
icalStringbuilder.AppendLine("SUMMARY;LANGUAGE=en-us:" + meetings.MeetingTitle);
icalStringbuilder.AppendLine("CLASS:PUBLIC");
icalStringbuilder.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
icalStringbuilder.AppendLine("DESCRIPTION:" + meetings.MeetingDesc);
icalStringbuilder.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", meetings.MeetingStartDate));
icalStringbuilder.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", meetings.MeetingEndDate));
icalStringbuilder.AppendLine("SEQUENCE:0");
icalStringbuilder.AppendLine("UID:" + Guid.NewGuid());
icalStringbuilder.AppendLine("END:VEVENT");
icalStringbuilder.AppendLine("END:VCALENDAR");
var bytes = Encoding.UTF8.GetBytes(icalStringbuilder.ToString());
return this.File(bytes, "text/calendar", "ical.ics");
}
Javascript:
<script>
$(function () {
$(document)
.on("click", "#icalBtn", function () {
exportiCal();
});
function exportiCal() {
$.ajax({
url: '/MeetingCalendar/AddToICalendar',
type: "POST",
//data: { downloadFileName = "thisEvent.ics" },
success: function (data) {
alert("hejejje");
}
});
}
});
</script>
The reason nothing downloads is because you can't download files via AJAX. Instead of being delivered to a file on your computer's disk, the downloaded content is going into the data variable in your "success" function.
To solve it, instead of using AJAX, make your action method accept GET requests and just user a regular hyperlink to link the user to it:
[HttpGet]
public ActionResult AddToICalendar()
{
//..etc
and
Download to iCalendar
You can remove all your jQuery code.
N.B. Logging that data value to the console (instead of just alerting meaningless junk) - or using your browser's network tools to see what is going on - would have let you see that, and you might have seen the problem sooner...maybe you need to do a bit more debugging in future.

getJSON breaks on page refresh (F5). How to fix?

I have an ajax call that fires every five seconds to update some data on the screen. It seems that the getJSON breaks after a page refresh. What appears to be happening is that if the page refreshes via F5 while the call is happening, the future calls won't work. They simply fail with no error message. The textStatus is error but errorthrown is empty. I'm calling into an Asp.Net MVC controller and no error is fired there. The subsequent getJSON calls never hit the server. It's pretty much hosed at this point until I start and stop my website again. No idea how to fix this as I can't stop the user from refreshing the page and it's a pain for me to test updates.
Here is my code:
var RealTimeActivity = (function () {
var realTimeActivity = {};
var timer = null;
var active = false;
realTimeActivity.LastUpdated = new Date();
function queueUpdate() {
timer = setTimeout("RealTimeActivity.Update();", 5000);
}
function reset() {
clearTimer();
queueUpdate();
}
function clearTimer() {
if (timer) {
clearTimeout(timer);
timer = null;
}
}
realTimeActivity.Update = function () {
try {
clearTimer();
if (active === true) {
$.getJSON("realTimeActivity/GetRealTimeData",
function (result) {
if (result.Success) {
// do stuff
} else {
// Other stuff
}
queueUpdate();
}
).fail(function (jqXHR, textStatus, errorThrown) {
console.log(textStatus + ": " + errorThrown);
reset();
})
}
} catch (ex) {
reset();
}
}
realTimeActivity.Start = function (i) {
active = true;
if (i) {
realTimeActivity.Update();
} else {
queueUpdate();
}
}
realTimeActivity.Stop = function () {
active = false;
clearTimer();
}
return realTimeActivity;
}());
EDIT:
This appears to only be reproducible in Chrome. A bug in chrome perhaps or am I missing something?
This appears to be a caching issue with Chrome and aborted requests. It will not allow me to send another request to the same URL once the request is aborted even after refreshing the page. I worked around it by making every request unique (via a timestamp).
postRequest('realTimeActivity/GetRealTimeData?u=' + (new Date).getTime(), null, function (response) {
Apparently you can also call $.ajax and just set cache to false as well which does the same thing behind the scenes.

Updating page content using JS during asynchronous operation

I am trying to solve an issue with webservice call in my MVC 4 project. What I am doing is that when user submits form on page, I call webservice and wait for result. Meanwhile server returns callbacks (it is returning strings containing finished steps of work on server side). What I would like to do is to display contents of "log" I am building from callback on the page and refresh it repeatedly to display the progress.
The issue I run into is, that either I will have asynchronous call of webservice in my controller in which case I am not waiting for result from webservice and that means that user will not stay on the page that should be displaying progress, or I will call it synchronously, in which case javascript on the page will not get response from controller until the final response arrives (so no updates are displayed).
My desired flow is:
User submits the form
Server is called in controller
Server sends callbacks, controller processess them by expanding "log" variable with whatever arrives
User still sees the same page, where "log" (contained in specific div) is being periodically refreshed by javascript while controller waits for final result from server
Server returns final result
Controller finishes its code and returns new view
This is my post method, which currently doesnt wait for the response and proceeds immediately further:
[HttpPost]
public async Task<ActionResult> SubmitDetails
(DocuLiveInstallationRequest submittedRequest, string command)
{
request = submittedRequest;
try
{
switch (command)
{
case "Test":
{
request.OnlyTest = true;
DocuLiveInstallationStatus installStatus
= await IsValidStatus();
if (installStatus == null)
{
ViewBag.Fail = Resources.AppStart.TestNoResult;
return View("SubmitDetails", request); ;
}
else
{
status = installStatus;
if (status.Result)
{
ViewBag.Success = Resources.AppStart.TestSucces;
ViewBag.Log = installLog;
}
TempData["installationStatus"] = installStatus;
return View("SubmitDetails", request);
}
}
case "Submit":
{
request.OnlyTest = false;
DocuLiveInstallationStatus installStatus = await Install();
if (installStatus == null)
{
ViewBag.Fail = Resources.AppStart.InstallationNoResult;
return View("SubmitDetails", request); ;
}
else
{
status = installStatus;
TempData["installationStatus"] = installStatus;
TempData["installLog"] = installLog;
return RedirectToAction("Login",controllerName:"Login");
}
}
}
ViewBag.TestFail = Resources.AppStart.SubmitFailure;
return View("SubmitDetails", request); ;
}
catch
{
return View();
}
}
this is javascript I prepared for the view:
<script type="text/javascript">
$(document).ready(function () {
//$("#submitDetails").click(function () {
var progress = 0;
//$("#submitDetails").attr('disabled', 'disabled');
var statusUpdate = setInterval(function () {
$.ajax({
type: 'GET',
url: "/AppStart/GetInstallProgress",
datatype: "application/html; charset=utf-8",
success: function (data) {
if (data && data != "") {
$("div.status-message").text(progress);
}
}
});
}, 2000);
//});
});
</script>
Currently I just display the log on the next page (at this stage of development server returns response very swiftly), but I need to call the server, display progress from callbacks while waiting for result and THEN navigate to another page (depending on the result). I feel like I am very close, but I can't get it working.
PS: I am open to other solutions than updating page content. I don't really mind how the goal will be accomplished, but updating the page is preferred by the customer.

Calling WebService from Ajax/Javascript

I am getting into a little jam here. I created a webservice using C#. When I Invoke the WebService it works fine. The Javascript seems to be hitting the webservice, breaking, and then follows through with the rest of the operation. I think this is a matter of me calling the WebService wrong. I've searched all over and have found tons of different examples, however, none of them seem to work.
If you go to http://success.darkslidedesign.com it triggers test.js which then calls my web service located here: http://www.darkslidedesign.com/services/ms_Alert.asmx
Here is the test.js code -
var xmlHttp;
setTimeout("sendMessage('rory#careercheatcode.com');", 2000);
function doUpdate()
{
if(xmlHttp.readyState===4){
alert("Worked");
}
else{
alert("Broke");
}
}
function sendMessage(strTo)
{
try{
// Opera 8.0+, Firefox, Safari
xmlHttp = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Ajax is not supported
return false;
}
}
}
xmlHttp.open("post", "http://www.darkslidedesign.com/services/ms_Alert.asmx", true);
var params = "op=Sending_Email&strEmailAddrFrom=rory#darkslidedesign.com&strEmailAddrTo=" + strTo;
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange=doUpdate;
xmlHttp.send(params);
return false;
}
You better start with jQuery $.ajax()
Here is one snippet that works for me to post comment from a textbox.
function Post() {
var ow = "username";
var cmt = $("#comment").val();
$.ajax(
{
type: "POST",
url: "/comment/Save",
dataType: "json",
data: "id=2332&author=" + ow + "&cmt=" + cmt,
success: function (result) {
if (result.status === "OK") {
alert('Comment posted');
}
else
alert("Post failed");
},
error: function (req, status, error) {
alert("Sorry! Post failed due to error");
}
});
}
Hope this will guide you.
Thanks
For web service calls from Javascript, I use two things:
jQuery, as pixelbobby mentioned. It is a walk in the park and makes everything super awesome-sauce!
I use the asp.net MVC framework. It is far too verbose for me to explain it here, but it is pretty easy to get it up and running. Basically, you create a controller class, create some methods, and return json-serialized values. You might also have to add some routes to your global.asax file.
I would definately recommend reading up on both of these things... They are both pretty awesome!

Categories