JQuery trouble with sending ajax report - javascript

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);
});

Related

How to fix ajax issue with not displaying in console?

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

Getting SyntaxError: missing ; before statement during ajax JQuery Call

Code is:
var rootData = null;
$.ajax({
url: 'http://localhost:12345/request',
data: rootData,
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
error: function() { alert('Failed!'); },
success: function() { alert('OK'); }
});
I've got :
"SyntaxError: missing ; before statement"
I don't understand why !
This error might occur when you're not escaping a string properly and the JavaScript engine is expecting the end of your string already.
Check rootData, it might be causing this error. (I'm assuming rootData is set to null then populated with some data before sending the request)
OK I found the solution:
a Rest Server is on port 12345 (Tomcat)
and a Spring MVC server on port 8080 (Tomcat)
the request from MVC is
var treeData = null;
$.ajax({
url: 'http://localhost:12345/request',
data: treeData,
type: 'GET',
async:false,
crossDomain: true,
dataType: 'json',
error: function() { alert('Failed!'); },
success: function( treeData ) { ....
and the rest server must accept the cross domain request just by adding #CrossOrigin to it :
#CrossOrigin(origins = "http://localhost:8080")
#RequestMapping(value = "/request", produces = { MediaType.APPLICATION_JSON_VALUE}, method = RequestMethod.GET)
public String request() { ....

How to read boolean value from json via JS

I want read returned value from this method:
public ActionResult ClientIsBlocked(int? clientId)
{
if (!clientId.HasValue)
return Json(null);
bool isBlocked = false;
try
{
isBlocked = this.clientsProvider.GetClientById(clientId.Value).IsBlocked;
}
catch
{
// logg
}
return Json(isBlocked);
}
in java script in my view. It should be async/ajax. How to do that?
It is my js code in view.
function isBlocked(id) {
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
url: '#Url.Action("ClientIsBlocked", "CustomerManagement", new { Area = "CustomerManagement" })',
data: JSON.stringify({ 'clientId': id }),
success: function(data) {
if(!data.success) {
}
}
})
In your action change :
return Json(isBlocked);
to:
return Json(isBlocked,JsonRequestBehavior.AllowGet);
otherwise your ajax may fail throwing exception:
Server Error in '/' Application.
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
and in js in success callback:
success: function(data) {
alert(data); // data is the bool that is returned by action
}

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
});

Do you need to use two calls - 1 get and 1 post in ajax or can you send data back with the success / failure?

I have the following controller method:
public JsonResult CreateGroup(String GroupName)
{
ApplicationUser user;
var userName = User.Identity.Name;
using (DAL.GDContext context = new DAL.GDContext())
{
user = context.Users.FirstOrDefault(u => u.UserName == userName);
if (user != null)
{
var group = new Group();
group.GroupName = GroupName;
group.Members.Add(user);
context.Groups.Add(group);
context.SaveChanges();
}
}
string result = userName;
return Json(result, JsonRequestBehavior.AllowGet);
}
with the following ajax call:
$(function () {
$('#CreateGroup').on("click", function () {
var groupName = $('#groupname').val();
if (groupName != '') {
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: JSON.stringify({ 'GroupName': groupName }),
dataType: "json",
cache: false,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
}
});
The CreateGroup function fails saying "Uncaught ReferenceError: data is not defined"
Do i have to use another Json request - type post - to get the username?
you can do the call without using JSON.stringify. Also your controller method has a cache attribute that may yield more control. Personally, I would use the controller cache control. You are probably getting a cached version of the controller call prior to returning data.
[OutputCache(NoStore = true, Duration = 0)]
public ActionResult CreateGroup(string GroupName)
$.ajax({
url: '#Url.Action("CreateGroup","AjaxMethods")',
type: "POST",
data: { 'GroupName': groupName },
dataType: "json",
traditional: true,
success: function (data, status, xhr ) {
alert("success");
CreateGroup(data);
},
error: function () {
alert("An error has occured!!!");
}
});
NOTE: Update success callback.

Categories