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

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.

Related

How to debug ajax response?

I am at lost with ways to debug my Ajax callback. I'm trying to print the response from the php file to see if the call is working but without success. While the call works, the response seem to return empty... Nothing shows in the console but the response in Network tab is 200 OK and I can see the data in the response header. However not able to print it back to the console. console.log(response) should print the table but meh. What are alternative ways to debug this? Any suggestion is welcome.
js
$.ajax({
type: 'POST',
dataType : 'json',
url: 'queries/getsocial.php',
data:nvalues,
success: function(response)
{
console.log(response);//does not print in the console
}
});
So here's the proof I get that it is working server side
After a much needed 10 hour break into the night, I solved the issue with a much clearer mind. I removed the dataType row and it worked for me.
As silly as it may sound, the table in the PHP page was not in JSON format, so when jQuery tries to parse it as such, it fails.
Hope it helps for you. If not, check out more suggestions here.
Before
$.ajax({
type: 'POST',
dataType : 'json',
url: 'queries/getsocial.php',
data:nvalues,
success: function(response)
{
console.log(response);//does not print in the console
}
});
After (Works now)
$.ajax({
type: 'POST',
url: 'queries/getsocial.php',
data:nvalues,
success: function(response)
{
console.log(response);//yes prints in the console
}
});
Can you add a photo of the console? When something like that happens to me, I usually print something console.log(“Response: “+ response). At least if you see the text at least you can be sure your function is getting executed.

RequestVerificationToken cookie is not being sent in Ajax POST requests

Here is the Ajax code:
var token = $('form input[name="__RequestVerificationToken"]').val();
var data = {};
data.Type = $(e.target).attr('type');
data.__RequestVerificationToken = token;
url = '#Url.Action("MyAction", "MyController")';
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: "html",
success: function (result) {
//do some stuff
},
error: function (err) {
//display error
}
})
In IE 11 Developer tools, during the initial load of the page (GET), I can see that the RequestVerificationToken cookie is being set. Also, the form element for RequestVerificationToken is being populated too. During the Ajax POST, however, the cookie is not part of the request.
Chrome works fine in both places, and during the Ajax POST, the cookie is present. IE 11 works locally (localhost), but this problem arises when IE 11 accesses the application on the server, and this error is returned:
The required anti-forgery cookie "__RequestVerificationToken_L1JldkNvbm5lY3Q1" is not present.
For some reason IE 11 doesn't include the cookie in the Ajax POST when the application is on the server. I can see that it is missing in the Network tab of IE Developer Tools. In the Network tab of Chrome Developer tools, the cookie is present, and the POSt works.
ASP.NET MVC 5

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

Using Ajax/jsonp to receive data from Web Api

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).

Resources