Couldn't able to remove double quotes from json string - javascript

I couldn't able to remove the double quotes from json string. Following is my code.
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":"hi#gmail.com","password":"123"}"
I need the actual result:
{"username":"hi","email":"hi#gmail.com","password":"123"}
Can anyone help me on this.
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;
}

Try
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":"hi#gmail.com","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":"hi#gmail.com","password":"123"}"}
// The required string : {"d":{username:"hi",email:"hi#gmail.com",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":"hi#gmail.com","password":"123"}"}
console.log(data.d); // output : {"username":"hi","email":"hi#gmail.com","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:"hi#gmail.com",password:"123"}" (correct)
console.log(content.username); // output : hi
var _name = content.username;
alert(_name); // hi
}

Related

Ajax Call to Service with Multiple Return Values

I am building a WCF service in C# in which I would like to be able to return multiple values from some of my functions. The code below appears to do this:
[WebMethod]
public void ReturnMultipleValues(int startingValue)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
var jsonData = new { FirstValue = startingValue, SecondValue = startingValue * 2 };
Context.Response.Write(ser.Serialize(jsonData));
}
I am trying to access this function through an ajax call in JavaScript code:
function runTestService() {
$.ajax({
type: "POST",
url: "http://localhost:12345/WebServices/MyService.asmx/ReturnMultipleValues",
contentType: "application/json;charset=utf-8",
data: "{ 'startingValue' : 6 }",
dataType: "json",
done: function(data) {
var firstValue = data.FirstValue;
var secondValue = data.SecondValue;
alert("First: " + firstValue + ", Second: " + secondValue);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
}
When I execute the above JavaScript code, the function in the .done portion never executes. When I check Fiddler, however, I see that the function in my service did execute properly and returned the correct values in the JSON.
Is there another way I should code either the service or the ajax call to it?
You are not supposed to write to Context.Response by yourself. Just return an object from method and let the framework do it for you
[WebMethod]
public object ReturnMultipleValues(int startingValue)
{
var jsonData = new { FirstValue = startingValue, SecondValue = startingValue * 2 };
return jsonData;
}
And you have to consider the fact web service wraps json repsonse in object with d property
{
"d": {
"FirstValue": 6,
"SecondValue": 12
}
}
So update js as well
done(function (data) {
data = data.d;
var firstValue = data.FirstValue;
var secondValue = data.SecondValue;
alert("First: " + firstValue + ", Second: " + secondValue);
});

No 'Access-Control-Allow-Origin' header when receiving JSON data from server

I am trying to make the client side receiving JSON data from the Server, however, it constantly popped up the error method. When I try to use Chrome to debug, it popped up: XMLHttpRequest cannot load http://localhost:8080/TransportationNetwork/rest/paths?st=3,6. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I have tried to change dataType to 'jsonp', but it doesn't work. However, when I use POSTMAN to test the data from Server, everything works fine, I can see the JSON data comes from the server.
Here is the picture shows the testing result from POSTMAN:
Pictures shows POSTMAN testing result from server
The following is my code on both server side and client side:
Could anyone tell me how to add the 'Access-Control-Allow-Origin' header for my java code?(if it is this problem)
The Java Code:
#Path("/paths")
public class PathsResource {
PathDao pathDao;
public PathsResource() {
pathDao = new PathDao();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
//#Consumes("text/plain")
public List<DirectedEdge> pathsInfo(#QueryParam("st") String st) {
System.out.println("Searching paths : " + st);
return pathDao.getEdgeList(st);
}
}
The Javascript:
var serviceURL = "http://localhost:8080/TransportationNetwork/rest/paths";
$('#findPaths').click(function() {
getPaths();
});
function getPaths() {
console.log('display paths');
$.ajax({
type:'GET',
url: serviceURL,
dataType:'json', // data type get back from server
data:'st=' + dataToServer(), //data sent to server
success: renderList,
error: function(jqXHR, textStatus, errorThrown){
alert('Path Finder: ' + textStatus);
}
});
}
function dataToServer() {
var array = "";
str1 = $('#source').val();
str2 = $('#target').val();
array = str1 + "," + str2;
return array;
}
function renderList(data) {
//var parsedData = JSON.parse(data);
var list = data == null ? [] : (data instanceof Array ? data : [data]);
$('#PathList li').remove();
$.each(list, function(index, path) {
$('#PathList').append('<li>'+ path.source + ' -> ' + path.target + ': ' + path.weight + '</li>');
});
}

Pass Exception from plugin to Javascript

For some reasons I have a javascript that create an entity record and a plugin will fire on post create. If the pugin throw an exception, it does NOT display to the user as the javascript is involved. I am wondering if there is a way to pass the exception from the plugin to javascrit so it can display it to the user.
Thanks.
Do you receive any http status code error like 40*, 500, 50* , if you use Odata, you have a callback to get the error. Javascript exception may not be throw.
Example:
.ajax({
type: “POST”,
contentType: “application/json; charset=utf-8″,
datatype: “json”,
url: serverUrl + ODATA_ENDPOINT + “/” + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader(“Accept”, “application/json”);
},
success: function (data, textStatus, XmlHttpRequest) {
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
alert(“Error on the creation of record; Error – “+errorThrown);
}
});
}
Checking the XMLHttpRequest readyState and status should do the trick:
function createRecord(eObject, eName) {
var jsonEntity = window.JSON.stringify(eObject);
var u = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var rec = new XMLHttpRequest();
var p = u + ODATA_ENDPOINT;
rec.open('POST', p + "/" + eName, false);
rec.setRequestHeader("Accept", "application/json");
rec.setRequestHeader("Content-Type", "application/json; charset=utf-8");
rec.send(jsonEntity);
if (rec.readyState == 4) {
if (rec.status == 200) {
var r = JSON.parse(rec.responseText).d;
return r;
}
else {
var error;
try {
// To get the exception from the responseXML
// I get an error when trying to use JSON.parse(rec.response)
// Unexpected token <
// I would much rather use JSON.parse
// than fiddling with the XML
// Please let me know if you find how to
// get the error message with JSON.parse
var xmlDoc = rec.responseXML;
var error = xmlDoc.childNodes[0]
.childNodes[0]
.childNodes[0]
.childNodes[1]
.childNodes[0].nodeValue + "."; // The error message
}
catch (e) {
// unable to get error message from response
error = "General Error";
}
return error;
}
}
// there is a problem
// maybe return general error message
return "General Error";
}
Thanks for all of you. I did resolve the issue by modifying part of my code to the following:
rec.send(jsonEntity);
if (rec.readyState == 4) {
if (rec.status >= 200) {
var newRecord = JSON.parse(rec.responseText).d;
return newRecord;
}
else {
var error;
var er;
try {
error = rec.responseText.toString();
error = error.substring(error.lastIndexOf("value\": ")+9,error.lastIndexOf("\""));
alert(error);
}
catch(e) {
error = rec.responseText.toString();
error = encodeURIComponent(error);
er = error.substring(error.lastIndexOf("value%22%3A%20%22")+17,
error.lastIndexOf("%22%0D%0A%7D%0D%0A%7D%0D%0A%7D"));
er = decodeURIComponent(er);
return er;
}
}

Call a GET API each XX seconds, and put the JSON response in a CSV

I'm a newbie, and I apologize for this.
I am writing a script that will make a GET request. The result is a JSON array and the best deal would be to have it put automatically in a CSV/TXT file.
$.ajax({
type: "GET",
url: BASE_URL,
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
},
success: function(jimmi) {
// Output the results
if (typeof jimmi === "string") {
station = JSON.parse(jimmi);
}             
var ar_len = jimmi.length
for (i=0; i < ar_len;) {
$("#results").html(
"Station: " + jimmi[i].name + "<br />")  
i++     
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
My problems:
* I get displayed only the last element of the array, and I can't figure out why.
* I would need to make this call automatically each 5 seconds
* The JSON results should be written into a CSV/TXT file.
Can someone help me?
BTW, the URL is https://its.navizon.com/api/v1/sites/1001/stations/ and you can log using demo#navizon.com - no password (read only)
Your problem is that you're changing the contents of #results for each element of jimmi by changing the entire inner HTML. So in the end, only the last element gets displayed. You need to use append instead. To make the call every 5 seconds, use the setTimeout method. Something this like:
function makeCall() {
$.ajax({
type: "GET",
url: BASE_URL,
beforeSend: function(jqXHR) {
jqXHR.setRequestHeader("Authorization", "Basic " + Base64.encode(USERNAME + ":" + PASSWORD));
},
success: function(jimmi) {
// Output the results
if (typeof jimmi === "string") {
jimmi = JSON.parse(jimmi);
}
for (i=0; i < jimmi.length; i++) {
$("#results").append("Station: " + jimmi[i].name + "<br />");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error');
}
});
window.setTimeout(makeCall, 5000);
}
makeCall();
Note: The line station = JSON.parse(jimmi); is not useful because the variable station is never used. I changed it to something that made more sense.

How to decode a JSON string?

On the server side do I have 2 hashes I encode into JSON strings like so
my $j = JSON->new;
$j = $j->utf8;
my $data;
$data->{users} = $j->encode(\%user_result);
$data->{owners} = $j->encode(\%owner_result);
$json_string = to_json($data);
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json_string;
On the client side I have
$(document).ready(function(){
$('form').live('submit', function(){
$.ajax({
type: "GET",
url: "/cgi-bin/ajax_confirm.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: $(this).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text("responseText: " + XMLHttpRequest.responseText +
", textStatus: " + textStatus +
", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
},
success: function(result){
if (result.error) {
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} else { // perl script says everything is okay
var users = result.users;
var owners = result.owners;
...
users contains
{"ss":"Sandra Schlichting","fn":"Full name"}
but it is not an array. When I use $.each() it takes on character at a time.
Problem
How do I turn it into an array, so I can use
function makeTable(users) {
var result = '<table>\n<tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
which should produce
Initials Full Name
ss Sandra Schlichting
fn Full name
You should use jQuery.getJSON() as mentioned at http://api.jquery.com/jQuery.getJSON/.
There is also $.parseJSON() method to parse string to json if you want to go that way.
You don't need to turn it into an array. According to the jQuery.each() documentation it takes both arrays or objects and JSON is a subset of the object literal notation of JavaScript.
Edit: Here's an example: http://jsfiddle.net/pedrocorreia/s5UrZ/2/
You can use the JSON parser created by douglas crockford:
https://github.com/douglascrockford/JSON-js
include the json2.js in your page, the you can do:
var object = JSON.parse(string);
Then you can use it as an array.
you can use for in statement
var index = 0;
for(user in users){
result += '<tr><td>' + index + '</td><td>' + user['fn'] + '</td></tr>\n';
index++;
}

Categories

Resources