jquery ajax call return error same service works on local and other server - asp.net

I am getting an error from a service which works on local system and on other domains (uploaded separately on each domain.) It returns the error:
"SyntaxError: JSON.parse: unexpected character"
The same service with same methods works on other domains.
Is there any issue regarding folder rights? If yes, can anyone tell what to change?
It is not a cross-browser issue as it is uploaded on same server from where I am accessing.
If I call this service from code behind by addding web reference then it works fine.
function GetHints(keyword, domain_id) {
var dataString = "{keyword: '" + keyword + "',domain_id: '" + domain_id + "'}";
$.ajax({
type: "POST",
url: "/test.asmx/GetKeywordSearch?" + (new Date()).getTime() + "",
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function (msg) {
var str = msg.d;
alert(str);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("An error has occurred making the request: " + errorThrown);
}
});
}

The Reason that service was not working is web.config. i Was missing web.config service settings. Handlers for service that are mostly added by Visual studio. But it missed that. After addition of handlers it works fine

Related

Getting error 500 while using an ajax call in a published web application hosted on iis

I have a website that is fully working in visual studio and also in a hosted server that I bought.
But now for the sake of trying and learning IIS, I am trying to host this website in on my own computer using IIS.My website works ok except that in one of them I connect to an asmx service via jquery ajax
here's my code:
$.ajax({
type: "POST",
url: "/WebServices/RequestHandler.asmx/GetConsultant",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id : '" + $(this).attr('data-id').toString() + "'}",
success: function (data) {
setTimeout(function () {
modalWindowContent.find('.main').hide().html(data.d).slideDown(500);
}, 1000);
modalWindowContent.find('.main').getNiceScroll().remove();
},
error: function (xhr, textStatus, thrownerror) {
alert("something went wrong");
console.log(xhr.status);
console.log(xhr.responseText);
console.log(thrownerror);
},
complete: function () {
modalWindowContent.find('.main').niceScroll({ scrollspeed: 300, mousescrollstep: 10 });
}
});
don't mind about the code much, but as you can see, it uses an asmx service and passes it some data using json format.
it all worked well in visual studio and the hosted server, but in IIS I get error 500 saying:
Request format is invalid: application/json; charset=UTF-8
in chrome's console
what do you think is the problem?

Passing multiple parameters with Ajax

I have a function in my .aspx page where I collect the first name and last name from the user and would like it to pass back to the server side code(c#). Ajax is being used and runs fine when one parameter is passed, although when a second parameter is passed I receive an error : can someone shed a little light, thanks
ERROR:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
POST http://ingleParam.aspx/GetCurrentTime 500 (Internal Server Error) jquery-.11.1.min.js:4
send jquery-1.11.1.min.js:4
m.extend.ajax jquery-1.11.1.min.js:4
ShowCurrentTime SingleParam.aspx:12
onclick
.ASPX Code
function ShowCurrentTime() {
$.ajax({
type: "Post",
url: "SingleParam.aspx/GetCurrentTime",
data: { name: $("#<%=txtUserName.ClientID%>").val(),
lastName: $("#<%=txtLastName.ClientID%>").val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
alert(response.d);
}
Server Side Code:
[WebMethod]
public static string GetCurrentTime(string name, string lastname) {
return "Hello " + name + Environment.NewLine + "The current time is " + DateTime.Now.ToString();
}
I've had issues with sending json objects to webmethods. I've had success when I stringify the data being sent across. Like so:
data: JSON.stringify({name: $("#<%=txtUserName.ClientID%>").val(),
lastName: $("#<%=txtLastName.ClientID%>").val()}),
Give that a try and see if it helps.

401 Unauthorized when creating request using Jquery

I am facing an error when requesting to WEBPageMethod using jquery and get 401 Unauthorized response and here is code for that
function SaveFile(type) {
var prmList = '';
prmList += '{"Title":"' + $("#txtTitleAudio").val() + '",';
prmList += '"Tag":"' + $("#txtAudioTag").val() + '",';
prmList += '"IsEnable":"' + $('input[name=chkrepost]').is(':checked') + '"}';
$.ajax({
type: "POST",
url: "AudioDairy.aspx/SaveAudio",
data: prmList,
contentType: "application/json",
dataType: "json",
success: function (msg) {
},
error: AjaxFailed
});
}
and Server Side Code Is
[WebMethod]
public string SaveAudios(string Title, string Tag, string IsEnable)
{
//lblSelectedDate.Text = DateTime.Now.ToShortDateString();
return "try Later.";
// }
}
So Please do the needful.
This seems like a security/authentication issue with your ASP.NET App. Check out these tips from the ASP.NET Forum
There are several things you need to verify.
Does the web service you are trying to access allow Anonymous
Access? Authentication can be tricky
for web-to-web calls
What is the web application running under, IWAM_xxx or IUSR_xxx?
Or are you using an
application pool running under a specific identity?
You may want to make sure your web application server's ASPNET or NETWORK
SERVICE
accounts can access your web service server.
Hope that helps...

Lost connection does not return error with jQuery AJAX on live site but on dev?

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

403 Forbidden Error

When I'm accessing web service from jquery, I'm getting the 403 forbidden error.. I published and created in the virtual directory too. Wat's the cause of this error and how to rectify it? I've added the webservice in the same solution.. This is my following code..
$(document).ready(function() {
$("#sayHelloButton").click(function(event){
$.ajax({
type: "POST",
url: "App_Code/DummyWebService.asmx/HelloToYou",
data: "{'name': '" + $('#name').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
I suppose using that url path for webservice is wrong.. I used the path 'DummyWebservice.asmx'. There I'm getting the 500 internal server error.
IIS and the dev server prevent access to your App_Code folder.
This is where you should store your class files but your asmx needs to be in a publicly visible location.
Move your asmx into the root of your site but leave your asmx.cs in the App_Code so it is compiled.
Then obviously change the path in your JavaScript and give it a try.

Resources