Jquery ajax goes to error even though result came - spring

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

Related

Why Is This AJAX Request Failing

this is my first time trying to implement AJAX and I haven't been able to figure out why its failing. Apologies, as it's probably easy enough spot for a seasoned AJAX user. I'd appreciate if you took a look.
JQuery File:
//declare variables
var friendSearch;
var csrfHeader = "[[${_csrf.headerName}]]";
var csrfToken = "[[${_csrf.token}]]";
$(document).ready(function(){
//give variables values
friendSearch = $("#friendSearchBox");
//call functions when
$(friendSearch).on('input', function(){
updateFriendsDisplay();
})
});
//functions
function updateFriendsDisplay(){
var jsonData = {searchString: friendSearch.val()}
$.ajax({
type: 'POST',
url: 'http://localhost:8080/friends/search',
beforeSend: function(xhr){
xhr.setRequestHeader(csrfHeader, csrfToken);
},
data: JSON.stringify(jsonData),
contentType: 'application/json'
}).done(function(data){
alert(data);
}).fail(function(){
alert("failed");
});
}
Controller:
#ResponseBody
#PostMapping("/search")
public List<UserAccount> getFriendsBySearch(#RequestParam("searchString") String text){
List<UserAccount> accountsList = uRepo.findByUserNamePortion(text);
return accountsList;
}

AJAX dont call WebMethod but returns HTML

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.

Passing more then 1 value to webmethod using FormData via Ajax

I'm trying to pass the uploaded image + two additional parameters to my web service using the FormData method from my Ajax method as shown here:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]);
formData.append('u', "test");
formData.append('s', "Testing");
My ajax call is outlined like so:
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
Which calls this webmethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string UploadImage()
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var t= System.Web.HttpContext.Current.Request.Files["s"];
var c= System.Web.HttpContext.Current.Request.Files["u"];
var p = System.Web.HttpContext.Current.Request.Files["file"];
}
else
{
return "Error";
}
return "Error";
}
The issue I'm having is the parameters 'u' and 's' are null yet when referencing file I'm able to get its value.
Whilst searching the web I was under the impression you can specify as many key/values are required when using this approach unless I have been misinformed? can someone please shed some light into why these two parameters are null? Thanks in advance.
This works for me:
JavaScript
var formData = new FormData();
formData.append("UserId", userId);
formData.append("RequestPhoto", imageFile);
formData.append("RequestVoiceRecord", voiceFile);
formData.append("Latitude", latitude);
formData.append("Longitude", longtitude);
$.ajax({
type: "POST",
url: "/User/CreateRequest",
data: formData,
contentType: false,
processData: false,
success: function () {
alert("OK");
},
error: function () {
alert("Error");
}
});
Controller:
public class UserController : ApiController
{
[HttpPost]
public int CreateRequest()
{
// HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
var req = new UserRequest
{
UserId = Guid.Parse(httpRequest.Form["UserId"]),
Photo = httpRequest.Files["RequestPhoto"],
VoiceRecord = httpRequest.Files["RequestVoiceRecord"]
Latitude = float.Parse(httpRequest.Form["Latitude"]),
Longitude = float.Parse(httpRequest.Form["Longitude"]),
};
You should create one json instead of create this stuff, add whatever keys you want to sent via ajax.
var formData = {'u':'value','s':'value'}
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: JDON.Stringify(formData),
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
try using this way.

Ajax post request return json data not updating

I am really new to Javascript, Ajax and JSON. I have the following code:
$(document).ready(setInterval(function () {
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("GetBase64Image","Home")',
contentType: 'application/json',
datatype: "json",
success: function(data)
{
alert(data.imagefilename);
displayImage(data);
}
})
},5000));
[HttpGet]
public ActionResult GetBase64Image()
{
if (ImageIndex==ImageData.Length) ImageIndex=0;
string fname = Path.GetFileName(ImageFileNames[ImageIndex]);
return Json(new { base64image = ImageData[ImageIndex++], imagefilename=fname }
, JsonRequestBehavior.AllowGet);
}
}
I do see the GetBase64Image is being called every 5 seconds but the alert only displays the value from first call to the method. What am I doing wrong.
Thanks.

Add Required Anti-Forgery Field Ajax Request on MVC

I'm trying to do an ajax post request on my MVC app, simply post data of form to server.
but I always get this error:
The required anti-forgery form field "__RequestVerificationToken" is not present.
This is my code for ajax request:
var reservationID = document.getElementById('ReservationID').value;
var arrival = document.getElementById('Arrival').value;
var departure = document.getElementById('Departure').value;
var noofrooms = document.getElementById('NoOfRooms').value;
var guestid = document.getElementById('GuestID').value;
var rateid = document.getElementById('RateID').value;
var agencyid = document.getElementById('AgencyID').value;
var sourceid = document.getElementById('SourceID').value;
var reservationtype = document.getElementById('ReservationType').value;
var reservation = { ReservationID: reservationID, Arrival: arrival, Departure: departure, NoOfRooms: noofrooms, GuestID: guestid, RateID: rateid, AgencyID: agencyid, SourceID: sourceid, ReservationTypeID: reservationtype };
var url = '/Reservations/Create';
$.ajax({
url: url,
type: "POST",
data : reservation,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
How can I add this anti-forgery field on my ajax?
For me this sollution works:
<script>
#functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
$.ajax("api/values", {
type: "post",
contentType: "application/json",
data: { }, // JSON data goes here
dataType: "json",
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
</script>
taken from:
Preventing Cross-Site Request Forgery (CSRF) Attacks in ASP.NET Web API

Resources