How to fix ajax issue with not displaying in console? - javascript

I have a simple ajax call in my Java spring boot application that calls a method in the controller and then returns the value to the front-end console. However, when I run the code it runs with a status of 400 but it does not show anything in my console. Not sure if I am forgetting anything or I have it setup wrong, but nothing is being passed back I am assuming.
JQuery:
$(".modalPathContentBtn").on("click", function(event) {
getSecondQuery();
});
function getSecondQuery() {
var search2 = {
"dtoTiername" : "Test"
}
$.ajax({
type : "POST",
contentType : 'application/json; charset=utf-8',
dataType : 'json',
url : "/ajax/mqlGetSecondQuery",
data : JSON.stringify(search2),
success : function(result) {
console.log("It works: " + result);
}
});
}
Java:
#RequestMapping(value = "/ajax/mqlGetSecondQuery", method = RequestMethod.POST)
public #ResponseBody String sendSecondQuery(#RequestBody TestApp mTestApp, HttpServletRequest request) {
String pathVal = mTestApp.getDtoTiername();
System.out.println("Test of if it is getting to this part of the code");
return "randomString";
}

You mentioned your request is failing with a status code of 400 which would mean the success of your ajax request would not get called since the request has not succeeded. You need to add a fail handler. It would look something like this.
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: "/ajax/mqlGetSecondQuery",
data: JSON.stringify(search2),
success: function(result) {
console.log("It works: " + result);
},
fail: function(err) {
console.log(err)
}
});
This may not be exact syntax, but the idea here is that you have a fail handler

Related

bad request 400 error while sending request to RestControler Spring MVC

I am getting bad request 400 error while sending request with parameters to controler I have checked whole sysntax but I did not wind any mistake, please look at my code whats wrong there?
var url = contextPath+"/billingControler/getOrdersByResWiseTables";
$.ajax({
url : url,
data : "&resID="+$("#rsId").text()+"&tblid="+tableId,
type : "get",
dataType : "json" ,
contentType : 'application/json; charset=utf-8',
success : function(response) {
console.log(response);
}
});
error :
jquery-3.3.1.min.js?_=1520931033076:2 GET http://localhost:8088/smartpos/billingControler/getOrdersByResWiseTables?&resID=11&tblid=3 400 (Bad Request)
please check my java code
#RequestMapping(value="/getOrdersByResWiseTables", method=RequestMethod.GET, produces="application/json")
public List<OrderBans> getOrdersByResWiseTables(#RequestParam("resId") String resId,#RequestParam("tblid") String tableid) {
String result="";
logger.debug("Started adding order");
RestypeIDao pdo = new RestypeIDaoImp();
List<OrderBans> orderList = pdo.getOrdersResWIseTbles(resId, tableid);
System.out.println(orderList);
logger.debug("end adding order");
return orderList;
}
You have extra & in your URL.
Also, you're using data attribute wrong, it should be an object.
Try this:
var url = contextPath+"/billingControler/getOrdersByResWiseTables";
$.ajax({
url : url,
data: {
"resID": $("#rsId").text(),
"tblid": tableId
},
dataType:"json",
contentType:'application/json; charset=utf-8',
success:function(response) {
console.log(response);
}
});

JQuery trouble with sending ajax report

I am trying to send report with this script:
$(".saveButton").on("click", function(){
var setting = {
'propertyName' : "SomeName",
'propertyValue' : $(this).parent().siblings('.inputCol').children('.inputField').val();
};
$.ajax({
type: "Post",
contentType: "application/json",
url: "/settings/PropertyEdit",
data: JSON.stringify(setting ),
dataType: 'json',
success: function (data) {
//Do something
}
});
And receive my POST in this method:
#Link(label = "Property Edit", family = "SettingsController", parent = "Settings")
#RequestMapping(value = "/settings/PropertyEdit", method = RequestMethod.POST)
public String atmPropertyEdit(Setting setting) {
return "true";
}
However I can even stop into my breakpoint (on return) (Error 403 - no-referrer-when-downgrade), unless I change my request method to GET, then it works fine.
Have tried this script - same 403 error.
$.post('/atmsettings/atmPropertyEdit', { propertyName : "hello", propertyValue : "hello2"},
function(returnedData){
console.log(returnedData);
});

ajax call returns values and my html page

I am currently performing an ajax call to my controller with the following code:
$.ajax({
type: "POST",
url: "#Url.Action("uploadImage", "Item")",
data: '{ "imageData" : "' + image + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (success) {
alert('Success ' + success.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
This is the controller :
[HttpPost]
public ActionResult uploadImage(string imageData)
{
string imageName = Guid.NewGuid().ToString();
try
{
ProductManager pm = new ProductManager();
pm.AddNewProduct(imageName);
}catch(Exception e)
{
writeToLog(e);
}
return Json(new { success = imageName }, JsonRequestBehavior.AllowGet);
}
It gets to the controller and the AddNewProduct function runs successfully. The problem is that i want it to return the image name that is created within the controller. This works as well but with that it also return my complete html page.
I alert something on success and when an error occurs but somehow it always ends up in the error with the following alert :
it shows the value I need but why does it return my complete HTML as well?
You do not need JsonRequestBehavior.AllowGet. That must be used only for GET requests in order to protect you against a very specific attack involving JSON requests. And in your code you are using POST verb.
You should use follow code in order to get the success string received from server.
success: function (response) {
alert('Success ' + response.success);
}

Ajax call returns undefined data

I have an ajax call that requests data from an MVC controller method.
I am returning a Json result from the controller.
Ajax request completes, but the data returned is undefined.Ajax Call
var param = {
"username": uname,
"password": pass
};
var serviceURL = "/Account/CheckUser";
var req = $.ajax({
url: serviceURL,
type: "POST",
data: JSON.stringify(param),
contentType: "application/json",
complete: successFunc,
error: errorFunc
});
function successFunc(data) {
if (data.exists == true) {
console.log("Completed : " + data.exists);
} else {
console.log("Failed : " + data.exists);
}
}
Controller Method
[HttpPost]
public JsonResult CheckUser(string uname, string pass)
{
Boolean cont = true;
return Json(new { exists = cont });
}
Can anyone tell me why exists returns as undefined? UPDATE
As suggested below, I wrote the data to the console, and it seems it's returning an empty string. So I guess the question should be more 'Why is the data returning empty?
The function you specify via the complete option doesn't receive the data (for good reason: it's called even if there is no data, because there was an error). Change complete: to success:.
var req = $.ajax({
url: serviceURL,
type: "POST",
data: JSON.stringify(param),
contentType: "application/json",
success: successFunc, // <=== Here
error: errorFunc
});

How to show output in a div using partial rendering concept in MVC

I am using render partial concept in MVC. Its not showing the output in div. While debugging everything is OK (Showing Staus 200 OK) but its not going inside success block.Below is my jquery function.
function ShowNavigation() {
var jsonObj = {
'Display': 'Index',
taFormula: $('#taFormula').val()
};
$.ajax(
{
url: "/Home/Index",
type: "POST",
data: jsonObj,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
var message = data.Message;
$("#contentDiv").html(message).val();
}
});
}
My Controller code is:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var val = collection["taFormula"].ToString();
ViewBag.Output = GetValue(val);
return View();
}
Remove the datatype: "json" bit. You're receiving html back from the server, not json data, but because of that setting it's trying to parse it and failing. If you had an error callback function it would go into that.
Also, you don't need the .val() on $("#contentDiv").html(message).val();
Try adding an error handler to the ajax call and see if that gives you any more information:
error: function (xhr, status, error) {
alert(status + " : " + error);
}
Try this for your json object:
data: JSON.stringify(jsonObj),
You might need to include json.js for older browsers.

Categories