I am having following ajax call in javascript
$.ajax({
type: "Post",
url: '../WebService/LoginService.asmx/LoginCheck',
data: jsondata,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (resp) {
if (resp.d == true) {
window.location.replace("../Admin/DashBoard.aspx");
return;
}
jQuery("#lblex").css("display", "block");
},
error: function (response) {
alert(response.responseText);
}
});
This works fine at local when i test, but when i hosted this on my production server, it says service not found.
But i am able to browse till the path
../WebService/LoginService.asmx
and if i change the url to
../WebService/LoginService.asmx?op = LoginCheck
it works there also.
Can anybody please let me know what configuration change i need to do at my local or at production server to get both of them working in same fashion
If this script is inside a WebForm I would recommend you using the ResolveUrl method to ensure that proper url is generated no matter where your application is hosted:
url: '<%= ResolveUrl("~/WebService/LoginService.asmx/LoginCheck")',
If the script is not inside a WebForm but in a separate javascript file where you cannot use server side functions you could define a global javascript variable in your WebForm:
<script type="text/javascript">
var serviceUrl = '<%= ResolveUrl("~/WebService/LoginService.asmx/LoginCheck")';
</script>
that you could later use in your separate js file:
url: serviceUrl,
Related
I would like consume cross-domain web-service from client with jquery.here is my code
function getId() {
var testid = ($('#<%=PreviousTest.ClientID %> OPTION:selected').val());
jQuery.support.cors = true;
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
}
my webservice returns values in this format
{"Table":[{"minlatency":16.0,"Time":"/Date(1328248782660+0530)/"},{"minlatency":7.0,"Time":"/Date(1328248784677+0530)/"},{"minlatency":13.0,"Time":"/Date(1328248786690+0530)/"},{"minlatency":6.0,"Time":"/Date(1328248788690+0530)/"},{"minlatency":20.0,"Time":"/Date(1328248790707+0530)/"},{"minlatency":12.0,"Time":"/Date(1328248792723+0530)/"},{"minlatency":26.0,"Time":"/Date(1328248794723+0530)/"},{"minlatency":18.0,"Time":"/Date(1328248796723+0530)/"}]}
Calls in cross-domain work in a different way. They create dynamic javascripts that are inserted to the page using a callback function. This function is used to handle the response from the service. The Jquery calls add a "?callback=?" to the URL of the service, where "callback" is the name of the function that will be inserted.
To call cross-domain services with JQuery you have to do the following:
jQuery.ajax({
type: "POST",
url: "../FalconWebService.asmx/minlatency",
data: "{'testId':" + testid + "}",
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //The data type that you must use is JSONP. Basically tells JQuery that the request is cross-domain
success: function (data) {
alert("catch");
var msg = jQuery.parseJSON(data.Table);
return msg;
},
Error: function () {
alert("error");
},
jsonpCallback: 'callback' //Dude to the fact that the JS is being generated dynamicaly, this tells JQuery to use the name "callback" for the function that will handle the result, as it adds "?callback=?" to the URL
});
You could also use "jsonp" instead of "jsonpCallback" if you want to "override the callback function name in a jsonp request" (from JQuery).
It worked for me (in WCF REST services which communicate with JSON messages, but it should work the same way in your case). This is all explained in the JQuery Ajax documentation.
Hope this helps.
I am trying to communicate to database from JavaScript using AJAX.
I have followed one article A beginner’s guide for consuming a WCF service in JavaScript using ASP.NET AJAX to understand about this functionality. I have done everything like exactly shown in the article. But, I couldn't understand how to set up the communication from JavaScript file.
Please note that as per my project requirement I can use only the second technique explained in the article: Using a Service Interface Defined in the Class Library.
Can anybody please suggest me how to do this?
Follow these steps
1) Creat a WCF service in your application.
2) Then add reference to your WCF Service.
3) Then add wcf service to the script manager control of your page
4) Now you can access the wcf service on your page.
Step by Step tutorial using VB.NET
http://v4.ajaxtutorials.com/tutorials/javascript/expose-wcf-service-to-javascript-in-asp-net-4-0-vb/
I used the following JavaScript code to get data from the database over AJAX:
$(function () {
var search = $("#<%=txtAccountNo.ClientID%>");
search.watermark('Enter Account No');
search.autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/") %>AutoCompleteService.asmx/GetAccountNo',
data: "{'prefixText':'" + search.val() + "','count':'10','contextKey':''}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
if (data.d != null) {
response($.map(data.d, function (item) {
return {
value: item
}
}))
}
},
error: function (XMLHttpRequest, textStatus, error) {
//alert(textStatus);
}
});
},
minLength: 1
});
});
I'm trying to send my form to a web method in asp.net page using jquery.forms plugin (primary reason for that is that I need to send files as well).
However, I can't make it work - it returns the whole page all the time.
I use the following client-side code:
<script type="text/javascript">
var ajaxUploadOptions = {
beforeSubmit: UploadFormValidate, // pre-submit callback
success: FormUploadSuccess, // post-submit callback
error: FormUploadFailure,
url: "Default.aspx/UploadFiles", // override for form's 'action' attribute
type: "POST", // 'get' or 'post', override for form's 'method' attribute
dataType: "json", // 'xml', 'script', or 'json' (expected server response type)
contentType: "application/json; charset=utf-8",
};
function FormUploadSuccess(response, statusText, xhr, jqForm) {
alert(response);
};
function FormUploadFailure(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
$("form[id $= 'form1']").ajaxForm(ajaxUploadOptions);
});
</script>
Code for the asp.net method just to return anything:
[WebMethod]
public static string UploadFiles()
{
return "Test";
}
I registered ScriptModule in web.config (also verified just calling regular jquery's $.ajax to make sure the method is available).
Any suggestions would be appreciated.
Thanks!
It seems I haven't read documentation/code carefully enough. Found out that when sending files, the forms plugin uses iframe and regular submit.
I am using the following code to post data from a asp.net 2.0 site to an asp.net 2.0 web service that post the data to a server:
$.ajax({
type: "POST",
url: "SynchroniseCustomers.asmx/synchroniseCustomers",
data: JSON.stringify(customerObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, status) {
// If not successfull
},
success: function (msg) {
deleteCustomer(customer.id);
}
});
I have a JavaScript function to check if I have connection or not, if I have I run the synchronisation (pulling data from web kit browser local database):
function checkConnection() {
var i = new Image();
i.onload = synchronise;
i.onerror = fail;
i.src = 'http://myurl.com/ping.gif?d=' + escape(Date());
setTimeout("checkConnection()", 60000); // Execute every minute
}
Thing is, if I run this locally and drop my internet connection the web service returns a 500 error (like I want it to do) and deleteCustomer(customer.id); is not called. However, on the live site if I drop my connection the web service does not return an error and deleteCustomer(customer.id); is called even if I don't have a connection to the internet (customer gets deleted from local database without being posted to the web server).
What's the reason for this? Please let me know if you need more code.
Thanks in advance.
You probably didn't wait a minute after dropping the connection.
There is a case that Ajax recall the cached data when you are ask for delete, and even if you are not connected to the net its get it from cache, so thats why its think that is all ok. The cache on jQuery Ajax is true by default.
So try with cache:false
$.ajax({
type: "POST",
url: "SynchroniseCustomers.asmx/synchroniseCustomers",
data: JSON.stringify(customerObj),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache:false,
error: function (xhr, status) {
// If not successfull
},
success: function (msg) {
deleteCustomer(customer.id);
}
});
For the image call, its better to use Interval and not create memory again and again.
<img id="PingerImg" width="1" height="1" src="/spacer.gif?" onload="synchronise" onerror="fail" />
<script language="javascript" type="text/javascript">
var myImg = document.getElementById("PingerImg");
if (myImg){
window.setInterval(function(){myImg.src = myImg.src.replace(/\?.*$/, '?' + Math.random());}, 60000);
}
</script>
Update
The other solution is to really get a confirmation code form the server that you have delete the user, and only if you read that code , proceed to delete the user on remote.
success: function (msg) {
if(msg.confirm = true)
{
deleteCustomer(customer.id);
}
else
{
alert('Fail to delete user.');
}
}
I am creating Menu in the master page using JQuery. i am passing the id of the link to jquery using $.ajax({});
Problem:
Getting failed: Showing error message in AjaxFailed(result) function.
Code:html[JQuery]
$.ajax({
type: "POST",
url: "Master.Master.cs/UserStatus",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
if (result.d.length != 0) {
for (var i = 0; i < result.d.length; i++) {
$(result.d[i]).hide();
}
}
}
function AjaxFailed(result) {
alert("Error");
}
c# Code:Codebehind
private static List<string> xx;
[WebMethod]
public static List<string> UserStatus()
{
return xx;
}
protected void Page_Load(object sender, EventArgs e)
{
xx = new List<string> {"#ll1", "#ll2" };
}
What the webmethod attribute does is to say that this method should respond to a certain url (a little bit like routing in asp.net mvc). As I don't use webforms I don't really know what logic it uses when it decides what url the method should respond to. But my guess is that the url should be something like "Master.cs/UserStatus" (not sure about the .cs extension). And that is of course a relative url, so you can try something like this: <%=ResolveUrl("~/Master.cs/UserStatus")%> (if the masterpage is in your root folder). Then your example should be something like this:
$.ajax({
type: "POST",
url: '<%=ResolveUrl("~/Master.cs/UserStatus")%>',
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
Update
The .cs extension is probably wrong. But I don't think you should have that in a master page anyway. You should probably have it in a web service or in a .ashx handler or something if you want to use ajax. But with you last comment it seems that you don't need to use ajax (and if you don't need that, you shouldn't). The problem in the code you wrote in the comment is probably that the id is wrong (remember that you need the client id in javascript).
But I would probably do it something like this:
<script type="text/javascript">
var statuses = [];
<%foreach(var status in UserStatus()) {%>
statuses.push(<%=status%>);
<%}%>
</script>
This will render this javascript in the browser:
<script type="text/javascript">
var statuses = [];
statuses.push("#ll1");
statuses.push("#ll2");
</script>
Then you will have your statuses in the statuses array.
Like Andre and Mattias mentioned, the .cs extension is not served, so you would have to use a .aspx extension to get to the WebMethod.
The problem I see in your example is that you are placing the method in the MasterPage (which would have a .master extension) which is also not served, so you can't call the web method from it.
A workaround you could use is to define it in a class that inherits from Page, and have all of your pages inherit from that class. Since its a public method, it will be public on all of your pages and therefore available. Basicly, a base page for your project's pages. In that case you would only need to use your current page's address to make the call. This is only usefull if it's something you will use on every page, like a menu.
A second workaround you can use is to define the WebMethod in a .asmx Webservice placed in the project. It would work like calling the WebMthod on a page, only you would have to use the .asmx Webservice's address instead of the page's to make the call.
If you've not done so you will need to add the [ScriptService] attribute to your webmethod as this
Indicates that a Web service can be
invoked from script
See ScriptServiceAttribute
I think that the problem is that you try to post to the .cs file. The extension .cs is not served by ISS due to security reasons. So even though your method lifes in the code behind file, you have to post to the .aspx file. ASP.NET will do the rest for your.
So try:
$.ajax({
type: "POST",
url: "/Master.Master.aspx/UserStatus",
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
if (result.d.length != 0) {
for (var i = 0; i < result.d.length; i++) {
$(result.d[i]).hide();
}
}
}
function AjaxFailed(result) {
alert("Error");
}