I couldn't remove the double quotes from json string. My code is the following :
var values = {};
$.each($('#regForm :input'), function(i, field) {
if (field.name == "submit") {
delete field.name;
} else {
values[field.name] = field.value;
}
});
var json_text = JSON.stringify(values);
var global = JSON.parse(json_text);
console.log(global);
$.ajax({
type : "POST",
dataType : "JSON",
data : global,
url : "http://localhost:8080/SpringRestServices/register",
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Accept-Encoding", "utf-8");
xhr.setRequestHeader("Content-type", "application/json");
},
success : function(data) {
alert("success"+data);
console.log("Success:", data);
},
error: function(xhr, textStatus, errorThrown) {
console.log("HI");
alert("Failed to cancel subscription! Message:" + textStatus /*+ jqXHR.errorThrown + xhr.responseText*/);
alert("readyState: " + xhr.readyState);
alert("responseText: "+ xhr.responseText);
alert("status: " + xhr.status);
alert("text status: " + textStatus);
alert("error: " + errorThrown);
}
});
Here is my output when I see it in the firefox debugger:
"{"username":"hi","email":"[email protected]","password":"123"}"
I need the actual result:
{"username":"hi","email":"[email protected]","password":"123"}
This is my server code:
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public RegisterResponse newAccount(@RequestBody Register registration) {
String newAccountSql = "INSERT INTO register (email,password,username) VALUES (:email,:password,:username)";
RegisterResponse regResponse = new RegisterResponse();
regResponse.setResult(-1);
// ServiceDataBean<AuthToken> retBean = new
// ServiceDataBean<AuthToken>();
try {
System.out.println("register service calling.....");
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
namedParameters.addValue("email", registration.getEmail());
messageDigest = MessageDigest.getInstance("MD5");
byte[] md5 = new byte[64];
messageDigest.update(
registration.getPassword().getBytes("iso-8859-1"), 0,
registration.getPassword().length());
md5 = messageDigest.digest();
namedParameters.addValue("password", convertedToHex(md5));
namedParameters.addValue("username", registration.getUsername());
GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
// TODO what to do with the updInt also check it's not -1
int updInt = jdbcTemplate.update(newAccountSql, namedParameters,
generatedKeyHolder);
regResponse.setResult(0);
System.out.println("from register");
} catch (Throwable e) {
regResponse.setResult(001);
e.printStackTrace();
}
return regResponse;
}
I couldn't remove the double quotes from json string. My code is the following :
var values = {};
$.each($('#regForm :input'), function(i, field) {
if (field.name == "submit") {
delete field.name;
} else {
values[field.name] = field.value;
}
});
var json_text = JSON.stringify(values);
var global = JSON.parse(json_text);
console.log(global);
$.ajax({
type : "POST",
dataType : "JSON",
data : global,
url : "http://localhost:8080/SpringRestServices/register",
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Accept-Encoding", "utf-8");
xhr.setRequestHeader("Content-type", "application/json");
},
success : function(data) {
alert("success"+data);
console.log("Success:", data);
},
error: function(xhr, textStatus, errorThrown) {
console.log("HI");
alert("Failed to cancel subscription! Message:" + textStatus /*+ jqXHR.errorThrown + xhr.responseText*/);
alert("readyState: " + xhr.readyState);
alert("responseText: "+ xhr.responseText);
alert("status: " + xhr.status);
alert("text status: " + textStatus);
alert("error: " + errorThrown);
}
});
Here is my output when I see it in the firefox debugger:
"{"username":"hi","email":"[email protected]","password":"123"}"
I need the actual result:
{"username":"hi","email":"[email protected]","password":"123"}
This is my server code:
@RequestMapping(value = "/register", method = RequestMethod.POST)
@ResponseBody
public RegisterResponse newAccount(@RequestBody Register registration) {
String newAccountSql = "INSERT INTO register (email,password,username) VALUES (:email,:password,:username)";
RegisterResponse regResponse = new RegisterResponse();
regResponse.setResult(-1);
// ServiceDataBean<AuthToken> retBean = new
// ServiceDataBean<AuthToken>();
try {
System.out.println("register service calling.....");
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
namedParameters.addValue("email", registration.getEmail());
messageDigest = MessageDigest.getInstance("MD5");
byte[] md5 = new byte[64];
messageDigest.update(
registration.getPassword().getBytes("iso-8859-1"), 0,
registration.getPassword().length());
md5 = messageDigest.digest();
namedParameters.addValue("password", convertedToHex(md5));
namedParameters.addValue("username", registration.getUsername());
GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
// TODO what to do with the updInt also check it's not -1
int updInt = jdbcTemplate.update(newAccountSql, namedParameters,
generatedKeyHolder);
regResponse.setResult(0);
System.out.println("from register");
} catch (Throwable e) {
regResponse.setResult(001);
e.printStackTrace();
}
return regResponse;
}
Share
Improve this question
edited May 22, 2024 at 19:53
Sybuser
1,3622 gold badges21 silver badges49 bronze badges
asked Apr 10, 2014 at 7:58
AppHouzeAppHouze
2063 silver badges10 bronze badges
11
- When I try this json_text = {"username":"hi","email":"[email protected]","password":"123"} and global = {username:"hi", email:"[email protected]","password":"123"}. The surrounding "" on json_text in the debugger are simply to signify that it is a string. – sWW Commented Apr 10, 2014 at 8:08
- But why i am not able to post this data using ajax to spring rest service?? Rest service is working fine, I have tested it with poster pluging for firefox. – AppHouze Commented Apr 10, 2014 at 8:12
- Are you confisung the JSON-string and the parsed object? What is the error from spring? – phylax Commented Apr 10, 2014 at 8:16
- @phylax, it is going into error function. see my edited question. I have updated my question with Ajax call. – AppHouze Commented Apr 10, 2014 at 8:25
- @user3496366 try data: json_text – sWW Commented Apr 10, 2014 at 8:28
3 Answers
Reset to default 5Try
json_text= json_text.slice(1, json_text.length-1);
See if writing your ajax request like this helps. It removes the explicit dataType that I think could be causing you an issue and also removes the beforeSend function and replaces it with the built in contentType option (and removes the explicit return datatype).
$.ajax({
type : "POST",
data : global, //Or json_text, whichever worked.
url : "http://localhost:8080/SpringRestServices/register",
contentType : "application/json",
success : function(data) {
alert("success"+data);
console.log("Success:", data);
},
error: function(xhr, textStatus, errorThrown) {
console.log("HI");
alert("Failed to cancel subscription! Message:" + textStatus /*+ jqXHR.errorThrown + xhr.responseText*/);
alert("readyState: " + xhr.readyState);
alert("responseText: "+ xhr.responseText);
alert("status: " + xhr.status);
alert("text status: " + textStatus);
alert("error: " + errorThrown);
}
});
I dont think there is a need to replace any quotes, this is a perfectly formed JSON string, you just need to convert JSON string into object.This article perfectly explains the situation : Link
Example :
success: function (data) {
// assuming that everything is correct and there is no exception being thrown
// output string {"d":"{"username":"hi","email":"[email protected]","password":"123"}"}
// now we need to remove the double quotes (as it will create problem and
// if double quotes aren't removed then this JSON string is useless)
// The output string : {"d":"{"username":"hi","email":"[email protected]","password":"123"}"}
// The required string : {"d":{username:"hi",email:"[email protected]",password:"123"}"}
// For security reasons the d is added (indicating the return "data")
// so actually we need to convert data.d into series of objects
// Inbuilt function "JSON.Parse" will return streams of objects
console.log(data); // output : Object {d="{"username":"hi","email":"[email protected]","password":"123"}"}
console.log(data.d); // output : {"username":"hi","email":"[email protected]","password":"123"} (accessing what's stored in "d")
console.log(data.d[0]); // output : { (just accessing the first element of array of "strings")
var content = JSON.parse(data.d); // output : Object {username:"hi",email:"[email protected]",password:"123"}" (correct)
console.log(content.username); // output : hi
var _name = content.username;
alert(_name); // hi
}