I am trying to call a WebMethod using AJAX POST but the browser keeps opening an 'authentication dialog'. I've not encountered this problem before using similar code detailed below.
In my search.aspx file I have the following:
HTML
<a href="javascript: ExpandChild('div4');" runat="server"> <img alt="Students" id="imgdiv4" src="images/arrow-right-b.png" />
</a>
JS
function ExpandChild(input)
{
//somethings are done here
LoadStudentData();
}
function LoadStudentData()
{
$.ajax({
type: "POST",
url: 'webmethods.aspx/TestCall',
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: 'json',
success: function (data) {
alert("ajax called");
},
error: function (result) {
alert("An unknown error occurred, please try again: " + result.responseText);
}
});
}
In my webmethods.aspx file I have the following:
[WebMethod()]
public static string TestCall()
{
return "it worked";
}
I know the code gets the to the LoadStudentData method but I have no idea why it is then opening an authentication dialog. Both the search.aspx page and the webmethods.aspx page are in the root of my project
I am using Visual Studio 2015 and this problem occurs in Chrome and Firefox when run on my local machine. When debugging the code it never gets to the TestCall method.
Any help much apprecciated.
Following this article
http://www.aspforums.net/Threads/105222/Error-SystemInvalidOperationException-Authentication-failed/
In the App_start/RouteConfig.cs I changed
settings.AutoRedirectMode = RedirectMode.Permanent;
To
settings.AutoRedirectMode = RedirectMode.Off;
Then the ajax post worked fine.
Related
The task is to get the value of some field from k2 with an ajax request. I Googled that it seems like a simple task and is solved by referring to the desired method in the controller
$.ajax({
type: "POST",
url: 'index.php?option=com_k2&task=photo',
dataType: 'json',
success: function (json) {
console.log('success '+json);
},
error: function (jqXHR, text, error) {
console.log('error '+text+' '+error);
}
});
in folder components/com_k2/controllers/item.php
i create function - public function photo(){return 1;} http://joxi.ru/a2XxYpJFwxvRV2
when trying to get my "1" :) I get "File Not Found" as soon as I did not try to access the k2 controller, everything is without success.
I am generating a excel file by using the Ajax call to my Action in my controller class in my ASP.net MVC application.Its working fine but the problem occures some time when my file is in downloading stage and the ajax call delete it.If there is any way without SetTimeout then please tell me.
Generate Excel File
$.ajax({
url: "#Url.Action("GenerateReport", "ClientAdmin")",
type: "POST",
data: { reportStart: reportStart, reportEnd: reportEnd},
dataType: "json",
traditional: true,
success: function (downloadUrl) {
//Download excel file
window.location = "/ClientAdmin/Download?file=" + downloadUrl;
//Delete excel file
$.ajax({
url: "#Url.Action("DeleteReportFile", "ClientAdmin")",
type: "POST",
data: { file: downloadUrl },
dataType: "json",
success: function (downloadUrl) {
},
error: function () {
AlertShow("Error!", "Oops! An error occured");
}
})
},
error: function () {
AlertShow("Error!", "Oops! An error occured");
}
})
I think you need jQuery "when".
http://api.jquery.com/jQuery.when/
$.when( $.ajax( "test.aspx" ) ).then(function( data, textStatus, jqXHR ) {
alert( jqXHR.status ); // Alerts 200
});
this is to force something to be synchronous.
(One can find the credited answer here)
EDIT
as I am not sure how to test your case I might suggest another solution.
Try handling "file downloaded" event somehow and then trigger the delete function.
Here is a possible useful answer and blog.
I am developing a dotnetnuke module and have lots of issues connecting to a webservice through javascript to retrieve data.
I have the folloiwng javascript:
function Test() {
$.ajax({
type: "POST",
url: 'http://localhost/DNN11/service1.asmx/TestMethod',
data: "{'data':'" + "abc" + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("success");
},
error: function(e) {
alert("error");
}
});
}
Then the following WebMethod in my webservice
[WebMethod]
public string TestMethod(String data)
{
return "Hello World";
}
However when the post is not being called successfully, I am not able to get through my webservice. It keeps giving me a 500 Internal Server error page.
What could be wrong please? Is there any other way I need to go about this?
Thanks
[Edit]
This is the entire code
<script type="text/javascript">
function Test() {
$.ajax({
type: "POST",
url: '<%=ResolveUrl("~/DesktopModules/ModuleTest/WebService1.asmx/TestMethod")%>',
data: '{ data: "test" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert("Success: " + msg);
},
error: function(msg) {
alert("Failed: " + msg.status + ": " + msg.statusText);
}
});
}
</script>
<div>
<input type="button" value="Load" onclick="Test(); return false;" />
</div>
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod()]
public string TestMethod(string data)
{
return "Hello World";
}
}
I have tried putting the Webservice in the DotNetNuke folder in a new folder and both in the local project.. I also put the ScriptMethod() Tag in the WebService which allows scripts to call it.. but still nothing
Looks like your problem is the cross domain calls. In case if your page hosted on the same server with the web service, your code should be fine. If you need to interact with the service from another domains you have to use jsonp requests. Look at this good step-by-step guide with the code example here.
UPDATE
In case if everything on the same app try to use relevant URL. Instead of url: '<%=ResolveUrl("~/DesktopModules/ModuleTest/WebService1.asmx/TestMethod")%>' try to url: '/DesktopModules/ModuleTest/WebService1.asmx/TestMethod'.
In order to post to a DNN webservice from the page you're going to have to pass in the Context of the module. I have some sample code that works against DNN6 at
http://slidepresentation.codeplex.com/SourceControl/changeset/view/69709#1181962
Mainly the
servicesFramework: $.ServicesFramework(<%=ModuleContext.ModuleId %>)
line
I haven't tested that against DNN7 though with the latest service framework WebAPI changes.
I have a problem to refresh a bloc in my page.
Here is the request:
> $("#pwd_lost_link").click(function(){
alert('1');
$.ajax({
type : 'POST',
url: 'test.php',
dataType: 'json',
data :{"nom" : "akbar"},
success : function(data){
$("#main_bloc").append(data.msg);
alert('2');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
alert(errorThrown); }
}); })
and here is the php file
<?php
$return['nom'] = "ffrfrfrfr";
echo json_encode($return)
?>
It doesn't work. It give me a status error ( 0 ) and the page is automatically reloaded
Thanks
Michaƫl
Confusing question Michael, not sure what you mean by "the page is automatically reloaded" but you should do 2 things:
In the $.ajax() method, make sure your success called back is handling the data correctly. You are looking for data.msg but I don't see where .msg comes from.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
url: url,
success: function(data) {
// parse data object so you can see what's being returned ex. alert(data) or alert(data[0]) or alert(data.nom)
},
error: function (xhr, status, error) {
// XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp
// check for errors ex. alert(xhr.statusText);
}
});
On the PHP side, you may want to debug there to see what is being received and what you are sending back.
Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful.
And on a final note, if pwd_lost_link is a link elment a id="pwd_lost_link" href="..." then you will have to stop the browser from following the link before you process the AJAX.
$("#pwd_lost_link").click(function(e) {
e.preventDefault();
alert('1');
$.ajax({
...
});
If you aren't seeing the '1' being alerted then that is definitely your first problem.
You're trying to access data.msg, but your PHP script is only creating data.nom. So data.msg doesn't exist. Try changing data.msg to data.nom and see if this does what you want.
I'm successfully posting to my controller with the following code, however, success is never being hit only error. What am I doing wrong?
JS:
$.ajax({
url: '/Home/Subscribe',
type: 'POST',
dataType: 'json',
data: { email: $('#sube').val() },
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
Controller:
[HttpPost]
public JsonResult Subscribe(string email)
{
return Json(new { foo = "bar", baz = "Blech" });
}
In IE, press F12 to open developer tools. Go to Network tab and click on Start Profiler. Send a request to your Subscribe action - in a list below you will see details of sent request and returned status code. Double click on request to see details - you can then see body of your response. If the request failed with a server error, you will see that error in a body of your response.
One wrong thing I see with your code is that you have hardcoded the url:
url: '/Home/Subscribe'
You should never do this. You should always use url helpers when generating urls in an ASP.NET MVC application:
url: '#Url.Action("Subscribe", "Home")'
Also you are saying that the error callback is always hit but you didn't say what you observed in FireBug or Chrome Developer toolbar when you tried to analyze the AJAX request. If you had done this you would have seen the exact cause of failure for the request because you would have seen what request is sent to the server and what response does the server sends back to the client.
The following is my jQuery ajax snippet that works. Your controller looks right. I assume you have verified it is actually getting called by using a breakpoint.
var p = {
email: $('#sube').val()
};
$.ajax({
url: '#Url.Action("Subscribe", "Home")'
type: 'POST',
data: JSON.stringify(p),
dataType: "text json",
contentType: "application/json",
success: function (data) {
// get the result and do some magic with it
alert(data.foo);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});