My application runs on jQuery and Spring MVC.
I have a grid which contains a hyperlink on reference number which is unique.
On clicking reference number, an ajax request is sent to the spring controller with reference number as the request parameter.
When an user clicks on two reference number quickly, two ajax requests are submitted to the server which results in the first request being aborted with status code 0 and second request is processed successfully.
The same happens for extreme slow network also.
When user clicks on two reference number after a certain interval, both the requests are processed successfully.
Can anyone please explain why the first request among the two gets aborted in slow network?
Below is the spring controller code
#RequestMapping(value = "/details/{ReferenceNo}", method=RequestMethod.GET)
public String getDetails(#PathVariable String ReferenceNo,ModelMap map) {
//server side stuffs
}
The client side code:
var $target = jQuery(e.target);
var href = application_path + $target.attr('href');
$.ajax({
url:href,
type:GET,
success:function(content){
//open the details
}
});
Related
I have a request map which returns list from database in json. Is it possible if visitor enters the exact url in browser, the page will be empty?
#RequestMapping(value = "/pics/{profileId}", method = RequestMethod.GET, headers = "Accept=application/json")
#ResponseBody
public List<ProfilePic> getProfilePics(#PathVariable("profileId") BigInteger profileId) {
return practiceServices.getProfilePics(profileId);
}
if visitor enters the url http://localhost:8080/practiceProject/pics/10, the page will show the list, but I don't want visitors to see it. I want the browser to show an empty page. Is it possible?
If you just want a quick solution check a header that will be sent within your AJAX requests. If this is not available just return null or whatever. You can also return a ResponseEntity<List<ProfilePic>> and in case the header is not present respond with a different HTTP status or just with an empty body or 204 (no content) using the ResponseEntity static methods / builder.
For example you can check if the header X-Requested-With is available with the value XMLHttpRequest. That is one of the default headers that will be sent when AJAX is used (but not always; I don't know exactly when it is sent and when not - maybe it depends on the used javascript library).
But keep in mind: This is nothing secure, someone can fake those headers and access the page anyway.
If you want such a behaviour for your complete API try it within a filter which checks this header and if available proceed with doFilter, otherwise stop and respond nothing.
You are returning the list on body of request, if you don't like to do it you should create a ModelAndView object and add the object list to it.
Example:
`#RequestMapping(value = "/pics/{profileId}", method = RequestMethod.GET, headers = "Accept=application/json")
public ModelAndView getProfilePics(#PathVariable("profileId") BigInteger profileId) {
ModelAndView view = new ModelAndView("html_to_be_returned");
view.addObject("list", practiceServices.getProfilePics(profileId));
return view
}'
PS: I have not test this code so it can have same issue.`
411 Length Required
The request did not specify the length of its content, which is required by the requested resource.
I have the following code:
[HttpPost]
[Route("UploadFileAsync/{RequestID}")]
public async Task<HttpResponseMessage> UploadFileAsync(int RequestID)
{
SetUser();
long maxAllowedFileSize = 9999999;
long? contentLenght = Request.Content.Headers.ContentLength;
if (!contentLenght.HasValue || contentLenght.Value > maxAllowedFileSize)
{
return Request.CreateErrorResponse(HttpStatusCode.LengthRequired, "Please set content lenght and file size should be less than 10 Mb");
}
It works and return 411 status code when size of request is more than 9999999.
But I would like to validate it before uploading the whole request to server (as I understand, sense of this 411 status code to prevent uploading big files if server can't process it). How can I reject request and send 411 status code before sending the whole request to server?
If you want to to validate the size before sending the request to Web API, then you need to do it at Web API client level.
However if you want to perform the validation before the Action in your web api controller is executed, you can use Action Filters. Typically, following steps are involved.
Create custom action filter for the Web API by inherting ActionFilterAttribute class.
Override OnActionExecuting method and write the code to check the content length and return appropriate error code within the method definition.
Register the custom filter in WebApiConfig file.
Decorate the action for which you want to apply this filter with your custom attribute
Refer to this link for step by step implementation.
I am attempting to write an Angular page to communicate with my Nodejs server, but I have ran into a snag.
I need to use multiple Ajax requests that rely on the data from previous ajax requests to work.
So Ajax request #1 provides data that is used by all other Ajax requests, and Ajax request #2 uses data from ajax request #1 to get the data that Ajax request #3 needs.
Since Angular is asynchronous, how can I make my script wait for the data from the first one before making the next ajax call.
id = ajax()
Wait for data
token = ajax(id)
wait for data
gametoken = ajax(id, token)
wait for data
Chandermani is correct, just remember to make sure to make the variables you need available in the scope that you need it.
var id,token,gametoken;
$http.get('http://host.com/first')
.then(function(result){
id=result;
return $http.get('http://host.com/second/'+id);
}
.then(function(result){
token = result
return $http.get('http://host.com/third'+id+'/'+token);
}
.then(function(result){
gametoken = result;
//Do other code here that requires id,token and gametoken
}
EDIT:
You don't have to chain the promises. If you want to make a call at a later date and you want to make sure the promises have resolved you can use $q.all();
var id,token,gametoken;
var p1 = $http.get('http://host.com/first')
.then(function(result){
id=result;
}
// Later on to make your new second call
$q.all([p1]).then(function(){
//Make second call knowing that the first has finished.
}
$q.all() takes an array so you can put in multiple promises if you want and it will wait until they have all resolved.
I have created a Spring MVC web app.
The app makes a few calls to the controller. These calls are close/open/end game.
I make these calls using Ajax, so I can handle a response on the top of the page.
ajaxPost = function (url, action, id, onSuccess, onError) {
$.ajax({
type: "POST",
url: url + "?" + action + "=" + id,
success: function(response) {
if(onSuccess !== null) {
onSuccess(response);
}
},
error: function(e) {
if(onError !== null) {
onError(e);
}
}
});
};
The question I have is that I'm using 'POST' for the Ajax request, is that correct, or should it be 'PUT'?
My controller has a default URL, and I'm using the param attribute to decide which method to call, as I have many buttons on the page.
#RequestMapping(params = "open", method = RequestMethod.POST)
#RequestMapping(params = "close", method = RequestMethod.POST)
It doesn't sit well with me that I'm using 'POST' for these calls. Maybe it should be 'PUT'...
Any suggestions? Does it matter?
It depends on what your request should do. So there's no general rule that you should use one over the other, they have different use cases.
POST for creating a record.
PUT for updating an existing record (or putting a record at a specified location/id).
See this wikipedia article for the definitions.
One thing to note is that PUT should be idempotent, doing the same PUT request multiple times should ideally produce the same result as doing a single PUT request. However, POST is not idempotent, so doing several POST requests should (or will) create multiple new records.
So after having read this you should check what your method does, and select the corresponding request method.
Both PUT and POST may create a new record; PUT may also update/change an existing record.
The difference between POST and PUT is that PUT is expected to address the record with it's ID, so that the server knows what ID to use when creating (or updating) the record, while POST expects the server to generate an ID for the record and return it to the client after the record has been created.
Thus, a POST is addressed to the resource as a collection: POST /resource, while PUT is addressed to a single item in the collection: PUT /resource/1
Use POST. Always use POST, unless you're absolutely rock-solid certain that PUT is properly supported by your hosting system.
Not sure if SFDebug is any help in this situation. I am making an ajax post using jQuery. Which retrieves JSON data in my action URL and then makes a call to the Model method that executes the action. The part until my action URL, and the jQuery call to it work fine. With the data transmitted from the client to the server well received and no errors being made.
It is the part where it calls the method on the Model that is failing. My jQuery method looks like this:
$.post(url, jsonData, function(servermsg) { console.log(servermsg); }) ;
My server action is like this
public function executeMyAjaxRequest(sfWebRequest $request)
{
if($request->isXmlHttpRequest())
{
// process whatever
$servermsg = Doctrine_Core::getTable('table')->addDataToTable($dataArray);
return $this->renderText($servermsg);
}
return false;
}
The method of concern in the Table.class.php file looks like this:
public function addDataToTable($dataArray)
{
// process $dataArray and retrieve the necessary data
$data = new Data();
$data->field = $dataArray['field'];
.
.
.
$data->save();
return $data->id ;
}
The method fails up here in the model, when renderText in the action is returned and logged into the console, it returns the HTMl for SFDEBUG. Which indicates that it failed.
If this was not an Ajax call, I could debug it by seeing what the model method spat out, but this is a little tedious with Ajax in the mix.
Not looking for exact answers here, but more on how I can approach debugging ajax requests in a symfony environment, so if there are suggestions on how I can debug this, that would be great.
You must send cookie with session ide key via ajax
(Assuming you have XDEBUG configured on the server)
In order to trigger a debug session by an AJAX request you have to somehow make that request to send additional URL parameter XDEBUG_SESSION_START=1. For your example:
$.post(url + '?XDEBUG_SESSION_START=1', jsonData, function(servermsg) { console.log(servermsg); }) ;
You can also trigger it via cookie, but appending URL parameter usually easier.