Using Ajax/jsonp to receive data from Web Api - asp.net-mvc

I've built a simple web service using the Web Api and I want to consume it from a simple mVC view using jQuery. I'm developing on localhost and consuming the service from Azure, which is why I'm using jsonp.
When I run my jQuery I view in Fiddler and the request is successful and json sent back but the .Ajax function returns these errors:
NaN, parsererror, and callback was not called
<script>
$(function () {
var callback = function(data) {
alert(data);
};
$.ajax({
url: 'http://itjobsdirect.azurewebsites.net/api/values/getbytitle?title=developer',
type: 'GET',
dataType: 'jsonp',
jsonpCallback: 'callback',
success: function (data) {
$('#main').text(data);
},
error: function(jqXHR, textStatus, error) {
alert(jqXHR.status + jqXHR.message);
alert(textStatus);
alert(error);
}
});
});
</script>
I found this question: JsonP with Web Api is it still relevant?
Thanks for your help!

Yes, the link to that question you have there is still relevant.
ASP.NET Webapi doesn't ship with a default formatter that understands the dataType of 'jsonp' and so the solution here is to add a custom JsonpMediaTypeFormatter (as shown in the answer for the questions you have linked).

Related

Multiple AJAX in one window.onload

I'm sure this question must have been asked before but I'm really struggling
to find the answer anywhere so have finally given up and will consult
the stackoverflow community - hopefully there's someone out there who's seen
it all before and can help me out!
I have a webpage which needs to make some function calls as the page loads. It is an ajax method which calls the Json method from the controller which supplies the data that will be used to draw the chart.
I've successfully displayed one chart on my page but still need to display two more charts. Is it possible to have multiple ajax methods on window.onload function?
Here is my code so far.
window.onload = function () {
$.ajax(
{
datatype: "json",
type: "POST",
url: "/CRM/GetIndustryTypeData",
data: JSON,
success: function (data) {
IndTypePieChart(data);
},
error: function () { alert("Error"); }
});
}
Stephen Muecke's answer will work 100%. Get rid of window.onload = function(){ and have any number of $.ajax() calls - positioned at the bottom of the page or wrapped in $(document).ready(){
}).

Rails Active Model Serializers conflict with Ajax?

When I use gem "active_model_serializers", my all Ajax can't work, my code like following:
$(document).on('change','#brand_id_dropdown', function () {
var request = "/beacons/find_beacon_uuid_given_brand_id?brand_id="
+ $('#brand_id_dropdown').val();
var aj = $.ajax({
url: request,
type: 'get',
data: $(this).serialize()
}).done(function (data) {
change_uuids(data);//modify the majors' dropdown
}).fail(function (data) {
console.log('AJAX request has FAILED');
});
});
I tried change to
data: { get_param: 'value' },
dataType: 'json'
still conflict, whenever I gem serializer and start rails server, all Ajax fail. how can I fix that?
I can't comment because I don't have enough rep. But you need to supply a little more information.
What's the failure message in the rails server logs? Check the rails server output and copy paste the errors into your question. Also, open your browser console and paste the "console" or "network" errors (in chrome: OPTION+CMD+I to show console). Lastly, throw a debugger; statement into your ajax call and play around with the variables.

RESTFul web service from html on IOS

Following is the technologies that I have used:
HTML 5, JS, JQuery, AJAX, RESTFul POST web service, IOS
Problem Statement:
I have created an iOS native application and placed certain HTML and JS files in my application. On starting the application on simulator I open my HTML file in web view and on click of a button I hit a web service that is deployed on my local windows machine.
However, I am not able to hit my web service. I am able to perform the same activity from Android emulator and from my local client test program.
Request you to please help me with this issue.
Below is the AJAX code that hits the service:
var jsonObject = new Object();
jsonObject.passengers= 4;
jsonObject.country= "India";
jsonObject.state= "Maharashtra";
var url = "http://<HOST>:<POST>/JerseyTest/services/emanual/demo";
$.ajax({
url: url,
type: "post",
data: inputJsonString,
success: function(data, status){
alert("success");
alert("In Success: " + JSON.stringify(status));
alert("In Success: " + JSON.stringify(data));
//$("#result").html('Submitted successfully');
},
error:function(data, status){
alert("failure");
alert("In Error: " + JSON.stringify(status));
alert("In Error: " + JSON.stringify(data));
//$("#result").html('There is error while submit');
}
});
This code works on from standalone HTML file, from Android Emulator.
Is there any extra configuration that I need to do on iOS machine or for simulator?
Any help is highly appreciated.
Regards,
Vineet
Make sure jQuery is loaded by putting an alert("jQuery is loaded") inside
$(function(){
alert("jQuery is loaded")
});
If jQuery isn't loaded, check in XCode if the jQuery source file is inside the Compile Sources which is under the Build Phases tab in the project Target. If it is, remove it and add it to Copy Bundle Resources.
Also, try formatting the AJAX like this,
$.ajax({
url:url,
type: 'post',
beforeSend: function(xhr, status, error){
xhr.overrideMimeType("application/json; charset=UTF-8");
},
data: {key: "value"},
error: function(data) {
alert("Error");
console.log("Error");
},
success: function(data, textStatus, jqXHR) {
alert("Success");
}
});
Sounds like a CORS issue. Make sure your REST service headers include:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Credentials: true

JQuery Mobile & URL Parameters white flash on reload

I am using query mobile for a phonegap application, I am passing through parameters through the url to the next page.
For example:
main.html?id=1, menu.html?id=2 etc
To allow this I have to turn ajaxEnabled to false to allow it to pass through the information I need. In doing so I am unable to use transitions from page to page which means I get a white flash as the page reloads.
I am generating these links dynamically.
$.ajax({
url: 'URLTO WEBSERVER',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var list = '<li><a href="menu.html?idcat='+item.id_cat+'">'+item.category_cat+'</li>'
output.append(list);
});
},
error: function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
output.text('There was an error loading the data.')
}
});
Is there a solution?
you can use method jquery serialize data for your paramater.
via changePage method in jquery
I hope solved :D
I think he is concerned about the "white plash page" that happens after the request is completed from server and then he calls changePage.
He is not worried about how to send parameters to server etc. This is assuming all that is working fine.

Try to post JSON.stringify object to aspnet mvc controller - bad request

I'm trying to post a JS Object stored in a hidden field:
$("#hdnArr").val(JSON.stringify(arr));
<pre>
$.ajax({
url: form.action,
type: 'POST',
data: $(form).serialize(),
success: function (result) {
//
},
error: function (xhr, textStatus, exceptionThrown) {
//
}
});
</pre>
Locally it is working fine, but in a production server (windows 2012 server with IIS 8), it is returng a Bad Request Error. With Firebug I checked that my hidden value is like this:
hdnArr=%5B%7B%22Type%22%3A%22%22%2C%22TypeB%22%3A%22%22%2C%22TypeC%22%3A%22%22%2C%22TypeD%22%3A%22%22%7D%5D
This problem is basically the % character. How can I enable my server to accept this char?
Ok, I could solve this problem just switching the Managed Pipeline from App Pool to Classic Mode.

Resources