Here is a snippet of javascript from my C# web MVC application:
$.ajax({
url: 'myurl'
}).done(function(response) {
$scope.Vdata = JSON.parse(response);
return $scope.$apply();
});
The JSON response form this call looks like this
"{
\"renditions\": {
\"live\": \"true\",
\" type\": \"default\",
\"rendition\": {
\"name\": \"Live \",
\"url\": \"http: //mysite\"
}
}
}"
I would like to wrap the json response rendition object into an array to look like this-(note the added square brackets for the array)
"{
\"renditions\": {
\"live\": \"true\",
\" type\": \"default\",
\"rendition\": [{
\"name\": \"Live \",
\"url\": \"http: //mysite\"
}]
}
}"
I tried something like this which didn’t work:
$.ajax({
url: 'myurl'
}).done(function(response) {
var tmp;
if (!respose.renditons.rendition.isArray) {
tmp = respose.renditions.renditon;
respose.renditon = [];
respose.renditon.push(tmp);
}
$scope.Vdata = JSON.parse(response);
return $scope.$apply();
});
The response will sometimes include the rendition object as an array so I only need to convert to an array in cases where its not.
Can someone please help me with the correct javascript to convert the json object into an array. Preferably modifying my existing code
Try this:
$.ajax({
url: 'myurl'
}).done(function(response) {
var json = JSON.parse(response);
if(!Array.isArray(json.renditions.rendition)) {
json.renditions.rendition = [json.renditions.rendition];
}
return json;
});
Fiddle demo (kind of...)
You can check if the object is an array using this:
Object.prototype.toString.call( response.renditions.rendition ) === '[object Array]'
And you can simplify the conversion to an array -- just wrap it as an array using x = [x]:
if (Object.prototype.toString.call( response.renditions.rendition ) !== '[object Array]') {
response.renditions.rendition = [response.renditions.rendition];
}
Fiddle demo.
add data type JSON to your ajax post. example
$.ajax({type: "POST",
url: URL,
data: PARAMS,
success: function(data){
//json is changed to array because of datatype JSON
alert(data.renditions);
},
beforeSend: function (XMLHttpRequest) {
/* do something or leave empty */
},
complete: function (XMLHttpRequest, textStatus) { /*do something or leave empty */ },
dataType: "json"}
);
Related
I need to extract the URL of an image from a JSON response (maybe I could put it in a variable).
I read this page on the MediaWiki API help
I follow this example to get the information about images on a page:
https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100
that return this JSON:
{
"batchcomplete": "",
"query": {
"pages": {
"2061": {
"pageid": 2061,
"ns": 0,
"title": "Albert Einstein",
"thumbnail": {
"source": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Albert_Einstein_Head.jpg/75px-Albert_Einstein_Head.jpg",
"width": 75,
"height": 100
},
"pageimage": "Albert_Einstein_Head.jpg"
}
}
}
In which way can I extract the URL of the image?
I tried this:
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages.2061.thumbnail.source;
var stgurl = JSON.stringify(urlImage);
alert(stg);
}
})
but doesn't work.
Yes, it doesn't work because this url: https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100 doesn't return JSON but HTML. If you want the JSON representation, you need to append &format=json to your url.
Change data.query.pages.2061.thumbnail.source to data.query.pages["2061"].thumbnail.source as you can't use numbers in a dot notation.
And also the alert; change stg to stgurl
$.ajax({
type:"get",
url:"https://commons.wikimedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json",
dataType:"jsonp",
contentType:"application/json; charset=utf-8",
success: function(data) {
var urlImage = data.query.pages["2061"].thumbnail.source;
//var stgurl = JSON.stringify(urlImage); - unnecessary JSON.stringify
var stgurl = urlImage;
alert(stgurl);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I tried to use the solution in this post:
iterating through json object javascript
Use the recursion in this way:
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
it seems to work.
I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },
How do I access the Marie-Antoinette.json object in this JSON file? I would like to get the title element of the object but I can't seem to get it to output. Here is my JavaScript code which outputs the object but I cant seem to access the objects elements.
$.ajax(
{
type: 'GET',
url: 'http://localhost:5984/movies/efadd5913f5cfd254b2861efd4001cb7',
//contentType: "application/json; charset=utf-8",
dataType: "JSONP",
jsonpCallback: 'callback',
//async: false,
success: function(r)
{
alert("ok");
$.each(r, function(index, value){ // iterating over each object
console.log(index);
if(index == "_attachments")
{
console.log(value); //how do I output the title ("Marie-Antoinette.json") and the other stuff in the object?
}
});
}
});
Here is the file. The elements I would like to access are in the "_attachments" element of the object.
{
"_id": "efadd5913f5cfd254b2861efd4001cb7",
"_rev": "6-417588bbff9aa74726b11440a86a8532",
"_attachments": {
"Marie-Antoinette.json": {
"content_type": "application/json",
"revpos": 2,
"digest": "md5-Io/Pxakfp/4R8ntjQKWMDg==",
"length": 761,
"stub": true
}
}
}
I think what is throwing me off is that it is an object inside the _attachment section.
The Marie-Antoinette.json object is inside your _attachments object, but because it contains a . it can't be accessed using dot-notation. You'll have to use array-like notation, passing the key as a string like so:
success: function (response) {
console.log(response._attachments['Marie-Antoinette.json']);
}
If you have multiple "attachments", you can access them in a loop like this:
success: function (response) {
$.each(response._attachments, function (i, attachment) {
console.log(attachment);
});
}
You could use Object.keys to extract keys from _attachments object and then print it:
var title = Object.keys(r._attachments)[0];
console.log(title);
Or if you have multiple attachments:
var titles = Object.keys(r._attachments);
console.log(titles.join());
Object.keys always returns an array.
in your function:
success: function(r)
{
for (key in json._attachments) {
console.log(key); // gives the names
console.log(json._attachments[key]); // gives the content
}
}
that would give you the stuff in _attachments
The below jQuery ajax method makes a call to node.js application that returns a json formatted data. I did check the console and it returns the json in this format
{ "SQLDB_ASSIGNED": 607, "SQLDB_POOLED":285, "SQLDB_RELEVANT":892, "SQLDB_TOTSERVERS":19}
However, when i try to access the element using the key name i get "undefined" on the console ?
Nodejs
res.send(JSON.stringify(" { \"SQLDB_ASSIGNED\": "+assigned_tot+", \"SQLDB_POOLED\":"+pooled_tot+", \"SQLDB_RELEVANT\":"+relevant_tot+", \"SQLDB_TOTSERVERS\":"+servertotal+"}"));
Jquery Ajax
$.ajax({
url: '/currentdata',
async: false,
dataType: 'json',
success: function (data) {
console.log(data);
for(var i in data)
{
console.log(data[i].SQLDB_ASSIGNED+"---"+data[i].SQLDB_POOLED+"---"+data[i].SQLDB_RELEVANT+"---"+data[i].SQLDB_TOTSERVERS );
}
}
});
Your Node.js part is very weird. You are stringifying a string:
res.send(JSON.stringify(" { \"SQLDB_ASSIGNED\": "+assigned_tot+", \"SQLDB_POOLED\":"+pooled_tot+", \"SQLDB_RELEVANT\":"+relevant_tot+", \"SQLDB_TOTSERVERS\":"+servertotal+"}"));
Why not just this? That's probably what you are looking for:
res.send(JSON.stringify({
SQLDB_ASSIGNED: assigned_tot,
SQLDB_POOLED: pooled_tot,
SQLDB_RELEVANT: relevant_tot,
SQLDB_TOTSERVERS: servertotal
}));
And then in the callback just this:
data.SQLDB_ASSIGNED; // Here you go
I don't know why you are iterating over the keys of the json. You want this:
console.log(data.SQLDB_ASSIGNED+"---"+data.SQLDB_POOLED+"---"+data.SQLDB_RELEVANT+"---"+data.SQLDB_TOTSERVERS );
So the code would be:
$.ajax({
url: '/currentdata',
async: false,
dataType: 'json',
success: function (data) {
console.log(data.SQLDB_ASSIGNED+"---"+data.SQLDB_POOLED+"---"+data.SQLDB_RELEVANT+"---"+data.SQLDB_TOTSERVERS );
}
});
You seem to be treating the data variable as an array of objects, containing the keys you specify. I guess what you would like to do is this:
for(var key in data) {
console.log(key+": "+data[key]);
}
Or what?
I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id