I think you can use JSON.stringify:
// after your each loop
JSON.stringify(values);
Answer from mimiz on Stack OverflowI think you can use JSON.stringify:
// after your each loop
JSON.stringify(values);
All major browsers now include native JSON encoding/decoding.
// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject);
// To decode (This produces an object)
var obj = JSON.parse(json_str);
Note that only valid JSON data will be encoded. For example:
var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"
Valid JSON types are: objects, strings, numbers, arrays, true, false, and null.
Some JSON resources:
- JSON on Mozilla Developer Network
- JSON on Wikipedia
If you set datatype: "json" in the .ajax() call, the data object you get, contains the already parsed JSON. So you can access it like any other JavaScript object.
console.log( data[0].response );
Otherwise you might have to parse it first. ( This can happen, when the returned MIME type is wrong.)
data = JSON.parse( data );
console.log( data[0].response );
Citing the respective part of the jQuery documentation:
dataType
If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
1)
console.log(data[0].response)
2)
for(var i in data){
console.log(data[i].response);
}
If you want to use $.getJSON() you can add the following before the call :
$.ajaxSetup({
scriptCharset: "utf-8",
contentType: "application/json; charset=utf-8"
});
You can use the charset you want instead of utf-8.
The options are explained here.
contentType : When sending data to the server, use this content-type. Default is application/x-www-form-urlencoded, which is fine for most cases.
scriptCharset : Only for requests with jsonp or script dataType and GET type. Forces the request to be interpreted as a certain charset. Only needed for charset differences between the remote and local content.
You may need one or both ...
I think that you'll probably have to use $.ajax() if you want to change the encoding, see the contentType param below (the success and error callbacks assume you have <div id="success"></div> and <div id="error"></div> in the html):
$.ajax({
type: "POST",
url: "SomePage.aspx/GetSomeObjects",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
$("#success").html("json.length=" + json.length);
itemAddCallback(json);
},
error: function (xhr, textStatus, errorThrown) {
$("#error").html(xhr.responseText);
}
});
I actually just had to do this about an hour ago, what a coincidence!
It depends a lot on what you want todo with it, but this is a basic way of accessing the element keys. You can simply use the dot operator for each element key: "data.email" etc.
$.ajax({
type: 'POST',
url: 'support.php',
success: function(result) {
var data = jQuery.parseJSON(result);
alert(data.email);
}
});
INSERT INTO HTML ELEMENT:
I created a div with id="landingPad" and swapped out the alert line with:
$('#landingPad').html(data.email);
MAKE A LIST OF THE DATA RECEIVED:
Then I changed my div into an unordered list:
<ul id="landingPad"></ul>
After changing the success function, it listed all the data received from support.php:
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'support.php',
success: function(result) {
var data = jQuery.parseJSON(result);
$.each(data, function(index, value) {
$("#landingPad").append("<li>" + value + "</li>");
});
}
});
});
CREATE FORM ELEMENTS WITH AJAX DATA:
Next, I created the following form:
<form name="http://example.com/edit_my_values" action="post">
<div id="landingPad"></div>
<input type="submit" name="go" value="Edit Values"/>
</form>
Then by editing the AJAX, I created a form on the fly with the values received:
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'support.php',
success: function(result) {
var data = jQuery.parseJSON(result);
$.each(data, function(index, value) {
$("#landingPad").append('<input type="input" name="'+index+'" value="'+value+'"/><br/>');
});
}
});
});
INSERT DATA INTO AN EXISTING FORM:
Given the following form:
<form name="http://example.com/edit_my_values" action="post">
<label for="error">Error </label><input type="text" name="error"/><br/>
<label for="successInfo">Success </label><input type="text" name="successInfo"/><br/>
<label for="email">Email </label><input type="text" name="email"/><br/>
<label for="subject">Subject </label><input type="text" name="subject"/><br/>
<label for="description">Description </label><input type="text" name="description"/><br/>
</form>
You can fill your fields with AJAX data as follows:
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'support.php',
success: function(result) {
var data = jQuery.parseJSON(result);
$.each(data, function(index, value) {
$('[name='+index+']').val(value);
});
}
});
});
You can access an array in this way
$.ajax({
type: 'POST',
url: 'support.php',
success: function(result) {
$('#content1').html(result[0]);
},
});
Code example with JSON.stringify:
<html>
<head>
<title>jQuery Test</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function(){
$.ajax({
url: "text.php",
type: "POST",
data: {
amount: $("#amount").val(),
firstName: $("#firstName").val(),
lastName: $("#lastName").val(),
email: $("#email").val()
},
dataType: "JSON",
success: function (jsonStr) {
$("#result").text(JSON.stringify(jsonStr));
}
});
});
});
</script>
</head>
<body>
<div id="result"></div>
<form name="contact" id="contact" method="post">
Amount: <input type="text" name="amount" id="amount"/><br/>
firstName: <input type="text" name="firstName" id="firstName"/><br/>
lastName: <input type="text" name="lastName" id="lastName"/><br/>
email: <input type="text" name="email" id="email"/><br/>
<input type="button" value="Get It!" name="submit" id="submit"/>
</form>
</body>
</html>
text.php
<?php
$amount = $_POST["amount"];
$firstName = $_POST["firstName"];
$lastName = $_POST["lastName"];
$email = $_POST["email"];
if(isset($amount)){
$data = array(
"amount" => $amount,
"firstName" => $firstName,
"lastName" => $lastName,
"email" => $email
);
echo json_encode($data);
}
?>
Your object is most likely being passed properly. It's the way you're capturing the result that returns [object object] as @Spudley explained. The console doesn't know how to display the construct but you can display specific attributes using the object.attribute syntax. Use console.log() on the JS side or the code below for a prettified output.
// Indent with tabs
// Data is the parameter sent to the success function in the ajax handler
JSON.stringify( data , null, '\t');
From How can I pretty-print JSON in (unix) shell script?
Also Temporarily remove dataType on the ajax handler if you sense there's a bug somewhere. Getting the ouput to show on a GET request should do. Change this back to POST for any operation that modifies something like a database delete or alter.
Lastly, modify the header as shown in @GroovyCarrot's answer. If you're using Chrome the extra whitespace seems to be a bug: Tab and pre wrapped around JSON output in Chrome