I'm using ASP MVC and I'm trying to call a service that's on another one of my MVC websites.
I'm trying to use the following Ajax call.
function SomeFunction(decision) {
if (decision == false)
decision = "no";
else
decision = "yes";
var input = {
LogEventType:"PageView",
CurrentPage: "invitation/?decision=" + decision + "&id=" + 32323,
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "https://somewebsite.com/api/ClickStream/LogWebEvent/",
data: JSON.stringify(input),
crossDomain: true,
dataType: 'jsonp',
headers: {
'Access-Control-Allow-Origin': '*'
},
success: function (data) {
alert("We're awesome")
},
error: function () { console.log("Call to SomeFunction failed.") }
});
}
I don't get any visible errors and I also put breakpoints on the service and inside of the success/error function of the ajax call but it never reaches any of them.
Anyone see where I messed up?
EDIT:
Here is the Web Apis function I'm trying to access
[ActionName("LogWebEvent")]
[HttpPost]
public void LogWebEvent(ClickStreamEventDto data)
{
try
{
_clickstreamLogger.LogWebEvent(data);
}
catch (Exception ex)
{
}
}
Where ClickStreamEventDto is
public class ClickStreamEventDto: Analytics.IAnalyticEventDto
{
public string LogEventType { get; set; }
public string CurrentPage { get; set; }
}
When hitting cross domain sites, with either CORS or JSONP, make sure they are both HTTP or both HTTPS.
Make sure that when HTTPS is involved, that both site's certificates have been accepted. You may need to hit the HTTPS site in another window, and accept the certificate if there is no trust relationship to the issuer.
Related
After 3 hours browsing on stackoverflow I don't find solution of my problem.
So I suspect something in my project is special.
I have a ASP.NET Core (2.0) WebApplications Project on Visual Studios 2017. I try to make a ajax call from my Kalender.cshtml file:
return $.ajax({
type: 'GET',
url: myurl,
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { //REQUEST SUCCESS
alert(result);
},
with myurl:
var myurl = '#Url.Action("EventsRead","Kalender")';
but I recognize that alert(myurl) return an empty string. So the ajax call must fail. I guess the url should something like:
/Kalender/EventsRead
but if I use this, ajax return 404 Not found.
My Kalender.cshtml.cs Action looks like:
[HttpGet]
public IActionResult EventsRead()
{
//DATABASE READOUT
var events = DataBase.Events.ToList();
return new JsonResult(events);
}
And the class of the PageModel looks like:
public class KalenderModel : PageModel
Here is everything auto generated. I try about 100 different version but never get a breakpoint into the EventsRead() action.
SIDE INFORMATION:
In my Startup.cs I suppress AntiforgeryToken:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
});
I really need some help before I get insane, thankful for any response.
Martin
Everybody who interested into the solution:
I changed in Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//ROUTES DEFAULT SETTINGS
app.UseMvc();
}
to:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//ROUTES CUSTOM SETTINGS
app.UseMvcWithDefaultRoute();
}
after this
'#Url.Action("TestGet","Kalender")'
will return correkt path.
Now I go to my bed and cry.
Your Controller setup looks just fine. When you used /Kalender/EventsRead as url and have a response 404 because of your data field. You've put curly braces as string. Try this in your ajax call
return $.ajax({
type: 'GET',
url: '/Kalender/EventsRead',
data:{},
success: function (result) { //REQUEST SUCCESS
console.log(result);
},
error: function (response){
console.log(response)
});
This may help you.
I am using jquery to make an API call to an Entity Framework API Controller and I am trying to call the Put Method:
[ResponseType(typeof(void))]
public IHttpActionResult PutProfileIDClass(int id, ProfileIDClass profileIDClass)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != profileIDClass.id)
{
return BadRequest();
}
db.Entry(profileIDClass).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProfileIDClassExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
But when I make the API call via jQuery I get this error: 405 (Method Not Allowed)
What Am I doing wrong?
Here is my API call
var data = {
id: result.data[0].id,
profileID: result.data[0].profileID,
taken: 'true'
};
var json = JSON.stringify(data);
$.ajax({
url: '/api/ProfileIDAPI?id=' + result.data[0].id,
type: 'PUT',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});
If you want to do a PUT request you should use the method: 'PUT' as part of your $.ajax call:
$.ajax({
url: '/api/ProfileIDAPI?id=' + result.data[0].id,
method: 'PUT',
contentType: "application/json; charset=utf-8",
data: json,
success: function (results) {
}
});
Do you have it installed on IIS? In that case, you have to configure it to handle your "PUT" request.
Right click on your website in the sidebar and go to properties.
Go to the "Home Directory" Tab
In the "applications settings", click on the "configuration" button
In the "Applications configuration" Window, there should be a Mappings Tab
Simply choose which file extensions you want to have mapped (in my case i wanted ASP to map GET, PUT, POST & DELETE), comma delimited. And thats it, not even a restart required.
Hope this helps
I have a web service created by Asp API, and i am trying to consume it by javascript ajax caller .. it works fine with GET & POST .. but when i tried to call DELETE function it returns message [The requested resource does not support http method 'DELETE'.]
and this is my code
Server code (API C#)
[HttpDelete]
public bool Delete(int id)
{
try
{
var model = db.PostsLikes.First(f => f.PostLikeID == id);
db.PostsLikes.Remove(model);
db.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
Client code (Javascript)
function (postLikeid) {
var result = $.ajax({
url: "/api/PostsLikes/",
type: "DELETE",
async: false,
data: postLikeid ,
contentType:"application/json"
}).responseText;
return result;
}
Problem is your IIS configuration is not accepting DELETE verbs. In the Handler Mappings section of IIS you can add the Delete verb.
Add it in delete method.
[HttpDelete]
[Route("api/PostsLikes/{id}")]
function DeleteFruitRecord(FruitID) {
var del = confirm("Are you sure you want to delete this recored?");
if (del) {
$.ajax({
type: "DELETE",
url: "api/FruitRec/DeleteFruit" + FruitID,
contentType: "json",
dataType: "json",
success: function (data) {
alert("Successsfully deleted…. " + FruitID);
GelAllEmployees();
},
error: function (error) {
alert(error.responseText);
}
});
}
Here is the Code for my WebService,
[WebService(Namespace = "http://mydomain.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class VBRService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string callJson(string x)
{
return "Worked =" + x;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void callJson2(string x, string callback)
{
StringBuilder sb = new StringBuilder();
sb.Append(callback + "(");
var json = new JavaScriptSerializer().Serialize("aString");
sb.Append(json);
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
}
Here is the JavaScript Code,
$.ajax({
crossDomain: true,
contentType: "application/json; charset=utf-8",
url: "http://localhost:31310/VBRService.asmx/callJson2",
data: { x:"someDataPassed", callback:onDataReceived },
dataType: "jsonp",
error: function (data){
alert(data.d);
}
});
function onDataReceived(data) {
alert(data.d);
// ^ Here is where the data comes back as undefined.
}
The JavaScript fires off and hits the onDataReceived function. I'm not really sure as to if this is how you respond from a webService to perform a callback as there are not any examples of server side code to call to.
However, the object data is undefined when it calls back. This is cross domain by the way so that's why I'm trying to figure out how to use jsonp.
Thanks in advance!
This is the correct way to send a jsonp request. You're overcomplicating it.
$.ajax({
url: "http://localhost:31310/VBRService.asmx/callJson2?callback=?",
dataType: "jsonp",
data: {x: "somedata"},
success: function(data){
console.log(data);
}
});
Alternative:
$.getJSON("http://localhost:31310/VBRService.asmx/callJson2?callback=?",{x: "somedata"},function(data){
console.log(data);
});
I'm trying to call a web service with ajax. The service is up, and it can shows the result on the RestClient on firefox, but, in mi application call, gives me Status error "Pending".
This is my simple web service.
#Controller
#RequestMapping("/hello")
public class HelloWs {
#RequestMapping(value= "/helloWorld", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public #ResponseBody String HelloWorld() {
return "Hello Worldssss¡¡";
}
And this is my ajax call.
function hellowsfunction() {
$.ajax({
type: "GET",
url:"http://localhost:8080/ehCS-ui/rest/hello/helloWorld",
crossDomain: true,
dataType: "JSON",
headers : {Accept : "applicationjson","Access-Control-Allow-Origin" : "*"},
success: function(msg) {
var returnedData = jQuery.parseJSON(msg);
$("#lblResult")
.text(result)
.slideUp("hide", function() { $(this).slideDown("slow") });
},
error: function (e) {
$("#lblResult").removeClass("loading");
alert('failed:'+e);
console.log(e);
}
});
what is wrong? Ideas?¿ please help.
Thanks
Your #RequestMapping is wrong... you should not map based on Accept header like this. Instead you should use produces parameter.
#RequestMapping(value="/helloWorld", method=RequestMethod.GET,
produces={"application/xml", "application/json"})
Also your header in the JS is incorrect. Just remove their specification completely.