Calling REST Api with JSONP & JQuery - c#

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.

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.

The resource cannot be found AJAX MVC 4 (WebApi)

var url = '#Url.Action("UploadFilesToDropBox", "Home")';
$.ajax({
type: "POST",
url: url,
data: postData,
success: function (result) {
if (result == "Success")
{
AfterCreationOfFiles(selected,SelectedFormat);
}
}, dataType: "json",
traditional: true
});
I am using above function to call an ActionResult, On localhost my function runs smoothly. But when i runs it on Server, it gives me the following Error:
The resource cannot be found.
i accidentally added WebApi, May be that is causing the Error?

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.

AJAX GET REQUESTS

Please help, I'm stuck here. I have a problem with passing input parameter to my C# controller. I tried really a lot of things I found here, but still there's some mistake.
Here is code:
var a = $.ajax({
type:"GET",
url: "/Weather1/Weather_get",
data: "location=Paris%",
contentType: 'application/json; charset=utf-8',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;
And here is controller:
[HttpGet]
public JsonResult Weather_get(String location) etc etc...
Everything I tried gives me input location NULL. I know my controller is working fine because I get data from it, but I really need that data to be for specific location, so that's why I need it like this. Also don't want to change it to POST because this is homework problem so I have to have both HttpPost and HttpGet in my controller.
Try this
var place="Paris%";
var a = $.ajax({
type:"GET",
url: '#Url.Action("Weather_get","Weather1")',
data: '{ "location":"' + place+ '"}',
dataType: 'json',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;
just include the parameter name in your controller and the value you want to pass like this.
$.ajax({
type:"GET",
url: '#Url.Action("Weather_get","Weather1")',
data: { location:paris},
dataType: 'json',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;
The way ASP.Net binds the HTTP request URL to the model used by your controller is controlled in part by the routing engine.
If you navigate to
/Weather1/Weather_get/Paris
do you see the data from Paris?
If so, you could modify your AJAX this way
$.ajax({
type:"GET",
url: "/Weather1/Weather_get/Paris"
(etc.)
})
You should probably use JSON.stringify.
something like this:
var data = {
location: "Paris%"
};
var a = $.ajax({
type:"GET",
url: "/Weather1/Weather_get",
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json',
cache: false,
success: function (data) {
console.log(data);
}, //succes
error: function (data) {
console.log(data);
}//error
}) //ajax;

Server response from json to javascript alert

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

Categories