I am using Jquery form plugin to upload file in Ajax request.File is successfully sent to server but on response browser is asking to save response with following popup
Here is my HTML
<form:form name="newRequestForm" id="newRequestForm" modelAttribute="requestForm" method="POST">
<form:input path="mrnFile" type="file" size="40"/>
</form:form>
JS
// Initializing Jquery form
$(function() {
$('#newRequestForm').ajaxForm();
});
// This function is called on click event of submit button
function submitDataRequest(formAction) {
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse, // post-submit callback
url: formAction,
dataType: 'json'
};
$('#newRequestForm').ajaxSubmit(options);
}
function showRequest(formData, jqForm, options) {
alert('About to submit: ');
return true;
}
function showResponse(data, statusText, xhr, $form) {
Alert("In response..")
if (!data.actionPassed) {
showErrors(data.errors);
$("#hideOrShowErrors").show();
} else {
showConfirmation(data, confirmationMsg, formName, successFormAction);
}
}
showResponse is never invoked instead browser shows the popup.
I checked through Firebug, the response code is 200 still success callback is not executed.
After reading some similar question I think it has something to do with server response type. So I did following in my spring controller
public ResponseEntity<ResponseDTO> save(#ModelAttribute("dataRequestForm") DataRequestFormDTO dataRequestFormDTO, BindingResult result, SessionStatus status, Model model, HttpServletResponse response) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentType(MediaType.APPLICATION_JSON);
return new ResponseEntity<ResponseDTO>(responseDTO, responseHeaders, HttpStatus.CREATED);
}
On both side I have data type as json but still I am getting the popup.Am I making any blunder?
Thanks!
EDIT:
Updated JS
function submitDataRequest(formAction) {
var options = {
beforeSubmit: function(){
alert("Before submit");
}, // pre-submit callback
success: function(){
alert("On success");
}, // post-submit callback
url: formAction
}
$('#newRequestForm').ajaxSubmit(options);
}
Still I get the same popup and success callback is not fired.
Added initBinder in controller
#InitBinder
protected void initBinder(HttpServletRequest request,
ServletRequestDataBinder binder) throws ServletException {
binder.registerCustomEditor(CommonsMultipartFile.class,
new ByteArrayMultipartFileEditor());
}
After adding initBinder I got following error
No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer
This is a common issue with IE and iframe (used by jquery form plugin to upload files with ajax).
I solved in two steps:
1) Server Side: remove headers, send back just the content.
2) Client-Side: do not set the ajax request dataType parameter and on success use the following code to extract json:
success: function(data)
{
try{
jsonData = jQuery.parseJSON(data);
// continue process with json encoded data
}
catch(e)
{
// handle parsing error
}
}
Related
Does anyone know why I am getting 500 internal error when I try to call an Ajax function? I tried to send the response from view.py to Ajax function in 2 ways: JsonResponse (see else from view.py) and also with HttpResponse (see if from View.py).
My Hmtl form does have a csrf_token, so I added the header in ajax function, but still got 500 internal erorr. The data is saved into database but the response is not sent to ajax function.
View.py
## Ajax
#login_required
def SubmitModal(request):
if request.method == 'POST':
text = request.POST['Text']
date = request.POST['DatePicker']
time = request.POST['TimePicker']
T = SText()
T.User = request.user
T.Text = text
T.STime = date + ' ' + time
T.save()
return HttpResponse(json.dumps({'success': True}), content_type="application/json")
else:
return JsonResponse({'success': False})
file that contains ajax
$(document).ready(function () {
// Show the modal window when a button is clicked
$('#open-modal').click(function () {
$('#modal').modal('show');
});
// Close the modal window when a button is clicked
$('.close-modal').click(function () {
$('#modal').modal('hide');
});
// Handle the form submission
$('#modal-form').submit(function (event) {
event.preventDefault(); // Prevent the form from being submitted
var formData = $(this).serialize(); // Get the form data
// Submit the form data to the server using an AJAX request
$.ajax({
type: 'POST',
url: '/submit/',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: formData,
dataType: "json",
success: function (response) {
if (response.success) {
$('#success-message').show();
} else {
$('#error-message').show();
}
},
error: function (xhr, status, error) {
console.log(error);
}
});
$(".textarea-input")[0].value = '';
$(".date-input")[0].value = '';
$(".time-input")[0].value = '';
});
});
If you're reproducing this in a non-production environment, you can set DEBUG=True in the settings file. Then when you make the call from your browser, the response will include details about what the issue is. You can also set the ADMINS variable to send exception tracebacks to the specified emails when they're encountered. More details here.
You can view the data being sent and received in the developer tools of the browser you are using.
AJAX error is being returned as Success. How to return JSON error from ASP.NET MVC? Could you tell me what I'm doing wrong? Thank you.
[HttpPost]
public JsonResult Register(int EventID)
{
try
{
// code
return Json(new { success = true, message = "Thank you for registering!" });
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message });
}
}
$.ajax({
url: "#Url.Action("Register", "Home")",
type: "post",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(postData),
success: function(data) {
},
error: function (data) {
}
});
The error function gets executed only when the HTTP Response Code is not HTTP 200 Ready. You handle the error in the server-side and return proper response, which will be picked up by success function in the AJAX call. Instead, use the status variable in your JSON and handle it on the client side:
success: function(data) {
if (typeof data == "string")
data = JSON.parse(data);
if (data.success) {
// Code if success.
} else {
// Code if error.
}
},
From the docs (scroll down to the error section):
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event.
The Ajax error method is hit only when you get a Yellow Screen Error in the server side. In your scenario you are handling the error using try catch and returning a valid response. So this is not considered as a error but a valid response. Remove your try catch so that Ajax will pick up the error event, else if you want to show the actual error message from server then you can use the success property to decide if the response was a success or a error , its similar to what Praveen has already posted in his answer.
success: function(data) {
if (data.success) { //as you are passing true/false from server side.
// Code if success.
} else {
// Code if error.
}
},
I have a page on a project I'm developing that is attempting to make an ajax request with a specific value assigned by the button's (there are multiple) id tag. This works; the value is successfully passed and an ajax call is triggered on every click.
When I try to make the call again to the same page with a different button the variables are reassigned however the GET request that is sent remains unchanged.
How do I pass a NEW variable (in this case id) passed into the GET request?
function someAJAX(target) {
var trigger = [target.attr('id')];
console.log[trigger];
$.ajax({
// The URL for the request
url: "onyxiaMenus/menuBase.php",
// The data to send (will be converted to a query string)
data: {
//class: target.attr("class"),
tableCall: true,
sort: trigger,
sortOrder: 'DESC',
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
//The available data types are text, html, xml, json, jsonp, and script.
dataType: "html",
// Code to run if the request succeeds;
// the response is passed to the function
success: function (data) {
console.log("AJAX success!");
$('#prop').replaceWith(data);
}
,
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error: function (xhr, status, errorThrown) {
console.log("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
}
,
// Code to run regardless of success or failure
complete: function (xhr, status) {
console.log("The request is complete!");
$('#view').prepend(xhr);
}
});
}
$(document).ready(function () {
$(".sort").on( "click", function (e) {
//e.stopPropagation();
//e.preventDefault();
target = $(this);
//console.log(target.attr("class"));
console.log(target.attr("id"));
/* ADD CHILDREN TO ELEMENT*/
if (target.hasClass('asc')) {
target.removeClass('asc')
} else {
target.addClass('asc')
}
/* MANAGE CLASS ADD/REMOVE FOR TARGET AND SIBLINGS */
if (target.hasClass('btn-primary')) {
} else {
target.addClass('btn-primary')
}
someAJAX(target);
target.siblings().removeClass('btn-primary');
})
});
Try to call your ajax like this someAJAX.bind(target)();
Then in function become
function someAJAX() {
$.ajax({
// The URL for the request
url: "onyxiaMenus/menuBase.php",
// The data to send (will be converted to a query string)
data: {
//class: this.attr("class"),
tableCall: true,
sort: this.attr('id'),
sortOrder: 'DESC',
},
// Whether this is a POST or GET request
type: "GET",
// The type of data we expect back
//The available data types are text, html, xml, json, jsonp, and script.
dataType: "html",
// Code to run if the request succeeds;
// the response is passed to the function
success: function (data) {
console.log("AJAX success!");
$('#prop').replaceWith(data);
}
,
// Code to run if the request fails; the raw request and
// status codes are passed to the function
error: function (xhr, status, errorThrown) {
console.log("Sorry, there was a problem!");
console.log("Error: " + errorThrown);
console.log("Status: " + status);
console.dir(xhr);
}
,
// Code to run regardless of success or failure
complete: function (xhr, status) {
console.log("The request is complete!");
$('#view').prepend(xhr);
}
});
}
trigger doesn't seem to be defined anywhere. That's the only data that would be changing between your requests as the other ones are statically coded.
You just need to make sure trigger is defined and changes between the two requests.
Thanks for the input on this problem. I got down to the bottom of my problem. My requests were being handled correctly but dumping the tables was creating syntax errors preventing the appending of new information to my page.
Thanks for the quick replies!
It wall works now.
I am posting data to the wicket server via ajax when user click.to make the state ,retrieve the data when page loading ,via ajax GET, if only one request is sending then its working fine ,but in second request following error has thrown.
org.apache.wicket.core.request.mapper.StalePageException
How can I send the data to the server via ajax and later load the panel
with the submitted data when user load it.
Code :Java Script
Sending data to the server
function submitdata() {
$.ajax({
url : $('#mark').attr('json:callback.url1'),
type : 'post',
cache : false,
data : ko.toJSON(familyModel),
ntentType : 'application/json',
dataType : 'json',
complete : function() {
} ,
error: function(xhr, status, error){
console.log(xhr);
alert(status);
alert(error);
}
});}
}
Page Load
$(document).ready(function() {
$.ajax({
url : $('#mark').attr('json:callback.url'),
type : 'GET',
cache : false,
contentType : 'application/json',
success: function (data) {
console.log(data);
var parsed = JSON.parse(data);
// ko.mapping.fromJS(data, familyModel);
/ ko.applyBindings(familyModel);
// familyModel=new FamilyModel();
ko.applyBindings(familyModel);
},
error: function(xhr, status, error){
console.log(xhr);
alert(status);
alert(error);
}
});
}
public class AbstractJSONBehavior extends AbstractAjaxBehavior {
public void onRequest() {
RequestCycle requestCycle = RequestCycle.get();
readRequestData(requestCycle);
sendResponse(requestCycle);
}
You are using plain jQuery APIs and Wicket believes that the requests are non-Ajax, so it increments the Page#renderCount counter to prevent using page with stale information.
If you use Wicket.Ajax.post({...}) then Wicket will figure this out automatically.
So you can either use Wicket.Ajax.post() or pass either the request parameters or headers from https://github.com/apache/wicket/blob/master/wicket-request/src/main/java/org/apache/wicket/request/http/WebRequest.java#L40-L48 with value true to the jQuery#ajax().
How can I get status code (200, 400, 404 etc.) at showResponse below:
$("#myform").validate({
submitHandler: function(form) {
var options = {
success: showResponse
};
$(form).ajaxSubmit(options);
function showResponse(responseText, statusText, xhr, $form) {
if (responseText == 'ok') { // status code to be used instead
...
} else {
...
}
}
return false;
}
});
This is from the jQuery Ajax docs:
statusCode(added 1.5)Map
Default: {}
A map of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:
$.ajax({
statusCode: {
404: function() {
alert('page not found');
}
}
});
If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error, they take the same parameters as the error callback.
According to the jQuery form docs you can pass any of the standard $.ajax options to ajaxForm.