Server response from json to javascript alert - c#

I am using webrtc(javascript,json,ajax) client to send request and c#web service to validate on server. I am posting a json request and the result is being displayed as xml in the console of the browser. Is there a way to get the response as an alert or pop up message using javvascript?
jQuery.ajax({
url: urlPath,
type: "POST",
contentType: "application/jsonp; charset=utf-8",
data: jsond,
dataType: "jsonp",
success: function (response) {
alert("Details saved successfully!!!" + response);
alert(xhr.responseText);
},

According to http://api.jquery.com/jQuery.ajax/ the success: of ajax call is being passed three parameters
1. Data(plainObject)
2. TextStatus(string)
3. jqXHR object(typeof jqXHR)
To extract the serverResponse, write this in the "success" Callback
success: function (data,TextStatus, xhr) {
alert(xhr.responseText);
},
Or if you want to display the data(as returned from the server), then you need to parse your data like this.
success: function (data,TextStatus, xhr) {
var newData = JSON.parse(data)
alert(newData);
}

Related

How to know client URL name?

I have created web-api to provide service like pin-code, Bank IFSC Code and so on, from my website named as http://www.ajaxserver.com
My all api is hosted on my site and my all client access using my site.
web api code is
[Route("api/GetURLName/")]
[HttpGet]
public string GetURLName(HttpRequestMessage request)
{
return HttpContext.Current.Request.Url.AbsoluteUri ;
}
One of my client website name is http://www.clientwebsite.online
client is used jquery to retrieve info like below code.
$('#btnTestCore').click(function () {
$.ajax({
url: 'http://ajaxserver.com/api/GetURLName/',
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (data) {
alert('failed.');
}
});
});
Output comes:
"http://ajaxserver.com/api/GetURLName/".
Need Output:
"http://clientwebsite.online/api/GetURLName/"
You could append the output to your AJAX request:
$('#btnTestCore').click(function () {
var urlname = encodeURI("http://clientwebsite.online/api/GetURLName/")
$.ajax({
url: 'http://ajaxserver.com/api/GetURLName?urlname=' + urlname,
dataType: 'json',
type: 'GET',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
},
error: function (data) {
alert('failed.');
}
});
});
You will then, of course, have to read that querystring in your webAPI code
As far as the server of the ajax request knows; the "site" is itself, so http://www.ajaxserver.com. You could try to look at the referrer, but... that isn't reliable across all browsers and protocols.
So you have two choices:
have the client API tell you the calling site - note that it could trivially be spoofed by the client
do some non-trivial proxy (etc) configuration such that the ajax server's site responds on the client domain
Note that http://clientwebsite.online/api/GetURLName/ was not the actual URL and is not going to come from anywhere by itself.

Jquery ajax call - how to alert the value from the return object

My requirement is to get the proper value. I got the success alert. result set contains one and only one value. How can I show/alert that value in result?
$.ajax({
type: 'POST',
url: url,
data: getDatawithToken(params),
success: function (result)
{
alert("success");
if(result.d.length>0)
{
alert("success");
}
}
});
try
$.ajax({
type: 'POST',
url: url,
data: getDatawithToken(params),
dataType : 'json', // expecting json returned from server
success: function (result)
{
alert("success");
if(result.d.length>0)
{
// access first element
alert(result.d[0]);
}
}
});
Whenever you want to see the data in json, in jquery write console.log(result) and check what you want to retrieve in browser console. This is the best way to debug json.
By typeing alert(result) in you success function, result is the object returned by the ajax call
try this , you can explore result value in console.
$.ajax({
type: 'POST',
url: url,
data: getDatawithToken(params),
success: function (result)
{
alert("success");
if(result.d.length>0)
{
Console.log(result)
}
}
});
See console output (CTRL/CMD+SHITF+I) to degub, seeing what coming form server:
$.ajax({
type: 'POST',
url: url,
data: getDatawithToken(params),
success: function (result)
{
console.log(result);
}
});
I thing you have json string so please parse that to object.
Using JSON.parse(result.d);
$.ajax({
type: 'POST',
url: url,
data: getDatawithToken(params),
success: function (result)
{
alert("success");
var jsonObject=JSON.parse(result.d);
if(jsonObject.length>0)
{
Console.log(jsonObject[0].BlockRefHandle);
}
}
});

ASP.NET + jQuery AJAX - getting 500 server error

I want to call an ASP.NET function from jQuery by AJAX with response.
I have file Controll.aspx where is included javascript code. Next I have /Services/ControllService.asmx, where is the function, which I want call from js.
js code:
$(document).ready(function () {
$('#btn_start').on('click', function () {
$.ajax({
type: "POST",
url: "Services/ControllService.asmx/Start",
data: {},
dataType: "json",
async: true,
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response);
},
error: function (err) {
alert("Error:" + err.toString());
}
});
});
});
But I still getting the error 500.
POST http://localhost:56000/Services/ControllService.asmx/Start 500 (Internal Server Error)
k.cors.a.crossDomain.send
n.extend.ajax
Do you have any hints, what do I need to set e.g. in Web.config?
Many thanks.
SOLVED:
1 - I have defined Start function in ControllService.asmx.cs as static.
2 - I have badly configured data. It has to be named by the same way e.g. "sth".
In javascript it should be:
...
url: "Services/ControllService.asmx/Start",
data: JSON.stringify({ sth: "hahaha" }),
dataType: "json",
...
and in ControllService.asmx.cs -> method Start
public string Start(string sth){}
Many, many thanks for your hints.

Cannot get response in ajax success

My AJAX code is below. In this i cannot get the response from server side C# code. But there is no issues with my server side code ( I have checked it by debugging ). From server side i am returning string to this ajax.
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]' +"provider/GetState",
contentType: 'application/json',
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
}
});
Server side code is below
public string GetState(string CountryId)
{
int i= Convert.ToInt32(CountryId);
var Details = objUserAccount.SP_Getstate(i).ToList();
if(Details.Count>0)
{
return "Success";
}
else
{
return "False";
}
}
Add datatype in your ajax request like this, if datatype is not matched with received data from server then the ajax error will call instead of success
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]'+ NSSCTProvider/GetState",
contentType: 'application/json',
dataType: "json",
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
},
error: function(data){
alert("Error occured");
}
});
$.ajax({
type: "POST",
url: '#System.Web.Configuration.WebConfigurationManager.AppSettings["BaseURL"]'+ NSSCTProvider/GetState",
contentType: 'application/json',
data: {CountryId: Country_Id },
success: function (data) {
alert(data);
},
error: function(data){
alert("Error occured");
}
});
Either one of the success or failure call back will be initiated if the request is made from this snippet. Might be a server issue, most probably. And make sure that this is the code snippet getting executed. Happens to me all the time.

Calling REST Api with JSONP & JQuery

I have created REST API in MVC4, it is working fine when I compose request from fiddler. But in my application, I need to call through jsonp because it would cross domain request. But when I'm calling this service it gives me error as shown below:
Jquery JsonP Call ..
$.ajax({
type: "POST" ,
url: "http://127.0.0.1:81/api/sites/GetDomainAvailability?apikey=asfasfdsf&callback=?",
data: { SubDomain: subDomain, ParentDomain: parentDomain, ResellerId: resellerId },
cache: false,
contentType: "application/json; charset=utf-8",
success: function (response) {
if (callback)
callback(response.d);
},
error: function (response) {
if (callback)
error(response.d);
},
});
Error:
Right now you are not doing JSONP. It's still POST request. To make it JSONP you need simply to add dataType: "jsonp" to you $.ajax() call. You can also remove some other redundancy parameters like content-type and 'callback' param (but that's optional). So, your code should looke like:
$.ajax({
url: "http://127.0.0.1:81/api/sites/GetDomainAvailability?apikey=asfasfdsf",
data: { SubDomain: subDomain, ParentDomain: parentDomain, ResellerId: resellerId },
datatype: "jsonp",
cache: false,
success: function (response) { /* ... */ },
error: function (response) { /* ... */ },
});
Be also ready, that your request will be transformed to a GET one and will look like
/GetDomainAvailability?apikey=key&callback=jquery123&SubDomain=sss&ParentDomain=ppp&ResellerId=123&_=4398572349857
So, prepare your server-side code for that.

Categories