I have been trying for few hours to debug a Post Ajax call to my server.
I have 2 POST methods: HelloWorld and HelloYou.
Same code, the only difference is that HelloYou takes a string as parameter:
namespace WebService
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
public string HelloWorld()
{
return "Hello World";
}
[OperationContract]
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
public string HelloYou(string name)
{
return string.Format("Hello {0}",name);
}
}
}
The HTML client looks like that:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>My Application</title>
<script type="text/javascript" src="/Scripts/jquery-2.1.1.min.js"</script>
<script type="text/javascript" src="/Scripts/ajax.js"> </script>
<script type="text/javascript" src="/Scripts/events.js"> </script>
</head>
<body>
<button id="world">HelloWorld</button>
<button id="you">HelloYou</button>
</body>
</html>
and the Ajax calls:
$(document).ready(function () {
$('#world').click(function () {
HelloWorld();
});
$('#you').click(function () {
HelloYou();
});
});
baseAddress = "http://localhost:53016/Service.svc/ajax/";
function GetURL(method) {
return baseAddress + method;
}
function HelloWorld() {
$.ajax({
async: false,
url: GetURL("HelloWorld"),
dataType: 'json',
type: 'POST',
data: null ,
processdata: true,
contentType: "application/json;charset-uf8"
})
.done(function(data) {
alert(data.d);
})
.fail(function (xhr, status, errorThrown) {
alert(status + errorThrown);
});
}
function HelloYou() {
$.ajax({
async: false,
url: GetURL("HelloYou"),
dataType: 'json',
type: 'POST',
data: JSON.stringify('{"name": "Chris"}'),
processdata: true,
contentType: "application/json;charset-uf8"
})
.done(function (data) {
alert(data.d);
})
.fail(function (xhr, status, errorThrown) {
alert(status + errorThrown);
});
}
I have tried few different ways to pass the parameter to the Ajax call:
data: JSON.stringify('{"name": "Chris"}'),
data: '{"name": "Chris"}',
data: '{name: "Chris"}',
var name ="Chris"
data: '{name: ' + JSON.stringify(name) + '}',
Every time, I get an error Bad Request 400. The same function HelloWorld with no parameter works fine.
I am lost.
I checked with Fidler the HTML Request/Response:
POST /Service.svc/ajax/HelloYou HTTP/1.1
HTTP/1.1 400 Bad Request
Thanks all
Isidore
I found a way to make it work. I changed the method from POST to GET.
For the data, I looked on JQuery API Documentation:
data: { name: "John"},
and it works. I am surprised, I thought GET wouldn't let me push data to the server.
Cheers
Isidore
Related
I had read a lot of questions here on Stackoverflow about AJAX calls to WebMethods, and I tried a lot of things and nothing works.
My AJAX method doesnt call the WebMethod on server side but returns success and the entire HTML of the page.
This is the AJAX:
$("[id*=butLogin]").click(function () {
var obj = {};
obj.pEmail = "EMAIL"; //$.trim($("[id*=txtName]").val());
obj.pPassword = "PASSWORD"; //$.trim($("[id*=txtAge]").val());
$.ajax({
type: "POST",
url: "login.aspx/logOn",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
failure: function (msg) {
alert(msg.d);
},
error: function (msg, merr, derr) {
alert(msg.d);
}
});
return false;
});
And this is the WebMethod:
[System.Web.Services.WebMethod]
public static string logOn(string pEmail, string pPassword)
{
return "logged";
}
I believe is a simples mistake.
Thanks for your help.
With my code i get a internal Server error:
#using (Html.BeginForm("", "Manage", FormMethod.Post, new { role = "form"}))
{
#Html.AntiForgeryToken()
}
<script>
function Like(id) {
var requestData = {
profileId: id,
__RequestVerificationToken: $('[name=__RequestVerificationToken]').val(),
};
$.ajax({
url: '/Manage/Like',
type: 'POST',
data: JSON.stringify(requestData),
dataType: "json",
contentType: 'application/json; charset=utf-8',
error: function (xhr) { alert('Error: ' + xhr.statusText); },
success: function (result) {},
async: true,
processData: false
});
}
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Like(string profileId)
{ ... }
If i remove [ValidateAntiForgeryToken] everything works fine, but i lose the sercurity. How can i fix the internal server error?
I see in fiddler SyntaxView 2 requests:
/Manage/Like
{"profileId":13,"__RequestVerificationToken":"jH2ofYlcTiHl8lixW_ANEHOg5KgwRh5Xl43lQfGkDFh55jX-x5cmz4RfPtbDfu92oQsTM7zsop83ldfbxMdIIELYZ0kfByFcXjUp-5mwyKZcQzjXP2gy6qW0iQOtLsqaDjFSzoxnyqM2MD42CbItzw2"}
/Manage
__RequestVerificationToken=MNiKOJHZg7BGaTNccOjrR2Obf_nPhKfcwIPZVBUl53G368n5euzB4y1htH47VKg3V3mHfxkjYZDz6iPepQ7jpeXGARtlj6vV74B8zQbp4by9JR4Rcz4sHANm3WHb6WAXaLcsnFvWJth_8c98XKda5w2
Taking this from a sim. question here include antiforgerytoken in ajax post ASP.NET MVC
function Like(id) {
var form = $('form');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: '/Manage/Like',
type: 'POST',
data: { __RequestVerificationToken: token, profileID: id },
error: function (xhr) { alert('Error: ' + xhr.statusText); },
success: function (result) {},
async: true,
processData: false
});
}
I'm trying to post some data using the fetch() api and I keep receiving a "400 - Bad Request" error.
I don't have any problem using the jQuery's $.ajax() method and I'm wondering what am I doing wrong:
data
let obj = {
id_user: 57,
id_category: 60,
note: 'test'
}
Using jQuery (working)
$.ajax({
url: 'http://localhost:3001/api/devices',
type: 'post',
data: obj
}).fail(function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
})
Using fetch() (not working)
fetch('http://localhost:3001/api/devices', {
method: 'post',
body: JSON.stringify(obj)
}).then(function(response){
console.log(response)
}).catch(function(error) {
console.log(error)
})
Response
Response {type: "basic", url: "http://localhost:3001/api/devices", redirected: false, status: 400, ok: falseā¦}
Am I missing something?
Here is how to use the fetch API:
namespace WebApi.Controllers
{
public class obj
{
public int id_user { get; set; }
public int id_category { get; set; }
public string note { get; set; }
}
public class devicesController : ApiController
{
public string Post([FromBody]obj value)
{
//use newtonsoft json
string json = JsonConvert.SerializeObject(value);
return json;
}
}
}
View:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#callAjax").click(function () {
let obj = {
id_user: 57,
id_category: 60,
note: 'test'
}
//this worked for me, FYI, I USE different port than you
//$.ajax({
// url: 'http://localhost:53110/api/devices',
// type: 'post',
// data: obj
//}).done(function (data, textStatus, jqXHR) {
// alert(data);
//}).fail(function (xhr, status, errorThrown) {
// alert("Sorry, there was a problem!");
// console.log("Error: " + errorThrown);
// console.log("Status: " + status);
// console.dir(xhr);
//})
//https://davidwalsh.name/fetch - does not work in ie11
//https://stackoverflow.com/questions/11492325/post-json-fails-with-415-unsupported-media-type-spring-3-mvc
fetch('http://localhost:53110/api/devices', {
//I HAD TO add this headers because 415 unsupported media type
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'post',
body: JSON.stringify(obj)
}).then(function (response) {
//alert(response)
//ADDED THIS https://developers.google.com/web/updates/2015/03/introduction-to-fetch
response.json().then(function (data) {
alert(data);
});
}).catch(function (error) {
alert(error)
})
})
})
</script>
</head>
<body>
<div>
<input type="button" value="callAjax" id="callAjax" />
</div>
</body>
</html>
I am using spring MVC and JQuery ajax. In one of my ajax call it returns large amount of data it nearly takes 5 minutes.
In Ajax method shows error even though the response came i checked it through firebug.
my ajax coding is
jQuery(document).ready(function () {
jQuery("sampleSearch").click(function () {
jQuery("body").addClass("loading");
var formValues = jQuery('#sample-search-form').find(':input[value][value!=""]').serialize();
jQuery.ajax({
type: "GET",
url: "/sample/user-byName",
data: formValues,
dataType: 'json',
success: function (data) {
jQuery('#json').val(JSON.stringify(data)).trigger('change');
jQuery('body').removeClass("loading");
},
error: function (e) {
alert('Error while request..' + e.toLocaleString());
jQuery('body').removeClass("loading");
}
});
});
});
and in my controller
#RequestMapping(value = "/user-byName", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public
#ResponseBody
String getUserByName(HttpServletRequest request) {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
Integer page = Integer.parseInt(request.getParameter("page"));
String resultJson = getUserByName(firstName, lastName, page);
return resultJson;
}
You need to increase the timeout for the request.
jQuery.ajax({
type: "GET",
url: "/sample/user-byName",
data: formValues,
dataType: 'json',
timeout: 600000,
success: function (data) {
jQuery('#json').val(JSON.stringify(data)).trigger('change');
jQuery('body').removeClass("loading");
},
error: function (e) {
alert('Error while request..' + e.toLocaleString());
jQuery('body').removeClass("loading");
}
});
read more in the .ajax() documentation
I am in the process of learning how to convert MVC Ajax to jquery ajax so I can do more.
This is the old ajax, I took out the loading stuff
#Ajax.ActionLink("Update Tweets", "Index", "Home",
new AjaxOptions
{
UpdateTargetId = "TweetBox",
InsertionMode = InsertionMode.InsertBefore,
HttpMethod = "Get",
})
I need to convert this to jquery ajax. It seems to be working lets see the code
<script>
$(document).ready(function () {
$("#StartLabel").click(function (e) {
$.ajax({
type: "Get",
url: '/Home/Index',
// data: "X-Requested-With=XMLHttpRequest",
// contentType: "application/text; charset=utf-8",
dataType: "text",
async: true,
// cache: false,
success: function (data) {
$('#TweetBox').prepend(data);
alert('Load was performed.');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
});
});
</script>
In the microsoft ajax it sets XML Request in the headers. Do I need to add that too? I am just paging my controller that performs a query to twitter and appends the data to the top.
I am using fiddler to see how the requests are different but the results are the same.
I also noticed if i put the text in the data: object its puts it in the header. i dont think that is right by any means.
You could define a normal anchor:
#Html.ActionLink("Update Tweets", "Index", "Home", null, new { id = "mylink" })
And then unobtrusively AJAXify it:
$(document).ready(function () {
$("#mylink").click(function (e) {
$.ajax({
type: "GET",
url: this.href,
success: function (data) {
$('#TweetBox').prepend(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
complete: function (resp) {
alert(resp.getAllResponseHeaders());
}
});
return false;
});
});
Notice that I return false from the click handler in order to cancel the default action. Also notice that I am using the anchor's href property instead of hardcoding it.
The 2 AJAX requests should be identical.
Here is simple example using Ajax with Jason data
// Post JSON data
[HttpPost]
public JsonResult JsonFullName(string fname, string lastname)
{
var data = "{ \"fname\" : \"" + fname + " \" , \"lastname\" : \"" + lastname + "\" }";
return Json(data, JsonRequestBehavior.AllowGet);
}
in the view add a reference to the query as following
#section Scripts{
<script src="~/Scripts/modernizr-2.6.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.intellisense.js"></script>
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
}
in the view add the js
note: (jsonGetfullname).on is a button
<script type="text/javascript">
$("#jsonGetfullname").on("click", function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#(Url.Action("JsonFullName", "Home"))",
data: "{ \"fname\" : \"modey\" , \"lastname\" : \"sayed\" }",
dataType: "json",
success: function (data) {
var res = $.parseJSON(data);
$("#myform").html("<h3>Json data: <h3>" + res.fname + ", " + res.lastname)
},
error: function (xhr, err) {
alert("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
alert("responseText: " + xhr.responseText);
}
})
});
</script>
you can also use (POST\GET) as following:
[HttpPost]
public string Contact(string message)
{
return "<h1>Hi,</h1>we got your message, <br />" + message + " <br />Thanks a lot";
}
in the view add the js
note: (send).on is a button
$("#send").on("click", function () {
$.post('', { message: $('#msg').val() })
.done(function (response) {
setTimeout(function () { $("#myform").html(response) }, 2000);
})
.error(function () { alert('Error') })
.success(function () { alert('OK') })
return false;
});