When I make a post request from Postman it works fine,but from ajax it gives the below error.Please help.Thanks in advance
Server side
#PostMapping(value = "/delete")
public ResponseEntity<BaseResponse> delete(#RequestParam("prod_id") Long productId) throws URISyntaxException {
BaseResponse response = new BaseResponse();
try{
productRepository.deleteById(productId);
response.setStatus(MessageType.SUCCESS);
}catch (Exception e){
response.setStatus(MessageType.FAIL);
}
return ResponseEntity.ok(response);
}
Ajax request
$(document).on('click','.delIcon',function(){
var row1 = $(this).closest('tr');
row = row1;
var data = $('#datatable').dataTable().fnGetData(row1);
var productId = data[0];
$.ajax({
url: "delete",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {"prod_id": productId },
success: function(response) {
if(response.status == 'SUCCESS' ){
alert('Deleted Successfully');
}
},
error: function(xhr) {
alert("Delete response got");
}
});
});
The problem has solved after removing contentType: "application/json; charset=utf-8" as #Postmapping accept only "application/x-www-form-urlencoded".So If I define contentType then it works fine
Related
I have a weird scenario happens when I send my ajax request that has 2 objects
first time it passes the second obj with the right value while the first object is null.Then second call it passes the first obj with value and the second obj as null
Here's my ajax method
var serializedForm = $(form).serialize();
var postData = {
merchTask: obj,
items: arrItems
};
$.ajax({
type: "POST",
url: $(form).attr('action'),
contentType: "application/json; charset=utf-8",
dataType:'json',
data: JSON.stringify(postData),
success: function (response) {
alert('done');
},
error: function (xhr, status, error) {
alert("Oops..." + xhr.responseText);
}
});
And here's my action in controller
public ActionResult EditTask(Task merchTask, string[] items)
{
short CompanyID = Convert.ToInt16((gSessions.GetSessionValue(gSessionsData.Company) as Company).ID);
try
{
merchTask.CompanyID = CompanyID;
if (merchTask.TaskID != 0)
{
taskTemplatesBF.Update(merchTask);
}
else
{
taskTemplatesBF.InsertMerchTask(merchTask);
}
string[] selectedLst = items;
foreach (string item in selectedLst)
{
taskTemplatesBF.InsertItemsLink(CompanyID,merchTask.TaskID,merchTask.ItemCode);
}
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
ModelState.AddModelError("", ex.InnerException.Message);
}
ModelState.AddModelError("", ex.Message);
}
return RedirectToAction("TasksTemplates", "Merch");
}
*I found a workaround to send each object separately in different ajax
but what's wrong when I send them in one request?
You have added a lot of code in the question but missed the code that was actually needed.
Okay add the event.preventDefault(); and event.stopImmediatePropagation(); functions inside your form summit event as follows:
$(document).ready(function(){
$("formId").on('submit',function(event){
event.preventDefault();
event.stopImmediatePropagation();
var serializedForm = $(form).serialize();
var postData = {
merchTask: obj,
items: arrItems
};
$.ajax({
type: "POST",
url: $(form).attr('action'),
contentType: "application/json; charset=utf-8",
dataType:'json',
data: JSON.stringify(postData),
success: function (response) {
alert('done');
},
error: function (xhr, status, error) {
alert("Oops..." + xhr.responseText);
}
});
});
});
Hope this will solve your problem.
(.js)
$.ajax({
type: "POST",
//contentType : "application/json",
dataType : "json",
url: "getStateNames",
//url:"http://localhost:8081/Mining_22_11_17/pages/admin/a.jsp",
cache: false,
data: "region=" + re + "& stId=" + state_id,
success: function(response){
//$('#result').html("");
alert("hiiii state list");
var obj = JSON.parse(response);
alert("state list" + obj);
//$('#result').html("First Name:- " + obj.firstName +"</br>Last Name:- " + obj.lastName + "</br>Email:- " + obj.email);
},
error: function(){
alert('Error while request..');
}
});
Spring MVC Controller
#RequestMapping(value="/getStateNames",method = RequestMethod.POST)
public #ResponseBody RegionDistrict add(HttpServletRequest request, HttpServletResponse response,#RequestParam String region, #RequestParam String stId) {
System.out.println("Get state");
}
By running this program I am getting 404 error.I want to send request using POST only.
$("#yourID").click(function(event) {
var region = $('#id').val();
var state_id = $('#edited').val();
$.post("${pageContext.request.contextPath}/getStateNames", {
region : region ,
state_id : state_id
}, function(data) {
//var json = JSON.parse(data);
//...
}).done(function(data) {
alert("hiiii state list");
swal("success");
//location.reload();
}).fail(function(xhr, textStatus, errorThrown) {
}).complete(function() {
//$("#btn-save").prop("disabled", false);
});
});
try this hope its works fine
$.ajax({
type: "POST",
url: "/getStateNames",
data: { region: re, stId: state_id },
success : function(response) {
alert(JSON.stringify(resoinse));
},
error: function(){
alert('Error while request..');
}
});
This should work, tell me if this solves your problem
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.
I am using WAP API, but don't know how to use ajax connect into the aaa method. Please help. same the ajax method cannot match [FromBody]Guid[] Ids, but how
[Route("aaa")]
[HttpPost]
public IHttpActionResult aaa(Guid teamId, [FromBody]Guid[] Ids)
javascript
var routeIds = new Array();
routeIds.push('EEBEEEDF-41F2-4931-41F2-362DDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
var team = { id: "EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06" };
var tmp = JSON.stringify({ teamId: "EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06", '': routeIds });
var path = GlobalData.url + "api/Event/UpdateRouteEnrollments";
$http({
method: 'POST',
url: path,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(tmp)
}).
success(function (data, status, headers, config) {
$scope.hide();
FeedStorage.save({ "id": data.TeamId, "Route": "0CE0F3C9-BB1E-4931-98F3-362DDE7BD406" });
$scope.setPlatform('team');
}).
error(function (data, status, headers, config) {
$scope.hide();
alert('An error occured:' + status);
});
I have this ajax request:
this.sendApiRequestWithFile = function (method) {
var formData = new FormData();
formData.append("name", "my name");
data_ajax = {
url: "http://localhost:1337/" + method,
method: "PUT",
data: formData,
headers: {
'Cache-Control': 'no-cache',
'Content-Type': 'multipart/form-data; boundary=----',
}
}
return $http(data_ajax).success(function(data, status, headers, config) {
return data;
}).error(function(data, status, headers, config) {
return data;
});
}
And my server is in sails.js so I catch parameters like this: req.body and it doesn't work. I try req.params.all() and doesn't work too.
I hope the following code should work. If you try to access the uploaded file from server, use req.file("file_name")
var fd = new FormData()
fd.append("name", "name value")
$.ajax({
url: "/url",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response) {
console.log("Success : " + response);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
});