$.ajax({
type: 'POST',
url: 'url',
data: val,
async: false,
dataType: 'json',
success: function (max) {
console.log(max.origin);
}
});
Then i am getting an output which is
["test,origin"]
I want to split it like .
test
origin
Please suggest me .
Much appreciated
If your returned value of max.origin really is ["test,origin"], you have to do something like this
var data = max.origin[0].split(',');
so that data will contain a list of the elements that are comma-separated. However, if your max.origin is in the form of ["test", "origin"], you can simply select each/all items by going through a for-loop and (optionally) print them out:
for (var i = 0; i <= max.origin.length; i++) {
console.log(max.origin[i]);
}
If you know that you only get the two elements (test and origin) each time, #void's answer is a good approach.
max.origin[0].split(",")[0] will give you test
max.origin[0].split(",")[1] will give you origin
Related
I want to receive the value thought iterator, when I use
$('#someModal').find('input[name=nameProBangHHModal]').val(data[0].TenNhanQuyCach);
it works as expected.
But when I use an iterator, the return shows [object Object].TenNhanQuyCach - not the data returned.
I try to search for other topic but I'm stuck on this. How to get the data returned in array[data[0]] with the value from the iterator method?
Thank you for your time!
$.ajax({
url: 'someurl to retrive data',
type: 'POST',
data: {id:id},
success: function(data,status) {
var tenCot = ['nameProBangHHModal','valueBangHHModal',];
var tenCotTrongCsdl = ['TenNhanQuyCach','DonViTinh',];
console.log(tenCotTrongCsdl[0]);
for (i=0;i <= tenCot.length - 1;i++) {
$('#someModal').find('input[name="' + tenCot[i] + '"]').val(data[0]+'.'+tenCotTrongCsdl[i]');
}
oh i find out the answer after search topic for array: this one: How can I access and process nested objects, arrays or JSON?.
and find out that need to use [] for variable, not the ".".
this one work for me:
$('#someModal').find('input[name="' + tenCot[i] + '"]').val(data[0][tenCotTrongCsdl[i]]);
I want to show key/value pairs (of social relationship data count) in bubble using D3.js or something similar.
Here goes my output from REST client:
{"data":{"sister":3,"General":130,"mother":3,"guest":1,"brother":10,"general":1,"father":4},"messages":[]}
And here goes the Jquery code for the same. I am getting keys in 'arr' and values in 'values' in the following code. All I need to output the data in visual form as bubble as per weight, example, 'General' count is 130, so it should have biggest bubble. like that.
$(document).on("click", "#socialGraph", function(){
var id="4501905311187190264";
$.ajax({
url: "/getSocialGraph/"+id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: function(data){
var arr=Object.keys(data.data);
var value=[];
for(var i in arr){
value.push(data.data[arr[i]]);
}
I have found several posts similar to this topic but nothing I have tried has actually worked. My question is simple and should be easy to answer. My return json object will have one key and one value. For my code below, the alert shows "[{"DISCOUNT":1}]" and all I am trying to do is parse out the "1" and display it. Ultimately, I want to plug that value into a variable and use for multiplication, but I can't even get the darn number to display by itself. My code is below:
function codeMatchTest() {
if ($('#dbReturnString').val() == '') {
alert("Please enter a discount code.");
} else {
$.ajax({
type: "POST",
url: "PROMO.svc/MatchCode",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
success: function (json) {
alert(json.d);
/*alert (json.d.discount); // getting "undefined"
$.each(json.d, function (key, value) {
var discount = value;
});
alert("Success: " + discount); //getting "undefined" */
},
error: function () {
alert("There was an error with your request.");
}
});
}
}
I have found no good references on how to actually use the data in a json object. My json object will only consist of a single key and value and I will only ever need to use the value.
Also, I have tried several iteration using $.each and none work. Based on the jquery documentation, it should be very easy but I am having not luck.
If your alert is showing "[{"DISCOUNT":1}]" that means you have an object within an array.
try alert(json.d[0].DISCOUNT);
JSON parsed objects are case sensivetive, plus its seems that json.d contains a string (wich seems to be in json) rather than an object. Try:
var discount = JSON.parse(json.d);
discount = discount[0].DISCOUNT;
success: function(json) {
alert(json.d[0]["DISCOUNT"]);
}
First comment on your code, you are reinventing what jQuery does.
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
It should just be
data: { codeInput: $('#dbReturnString').val().toLowerCase() },
Now to get the data it is simple, you are returning an array with an object in it.
Let us look at it as a regular variable and not an Ajaqx call.
var json = [{"DISCOUNT":1}];
So you got an array? How do you get the object inside of it? You reference the index. Since you said there will only be one index being returned, than use [0] to access it.
success: function (json) {
alert(json[0].DISCOUNT);
To access the first item from the json you may use
alert(json.d[0].DISCOUNT);
Because json.d is an array and it contains one object which is 0 index. So, json.d[0] will select the first item/object from the array and using .DISCOUNT you can access the object's property. It's also possible to access the property like
alert(json.d[0]["DISCOUNT"]);
Try this way
You can use JSON.parse(json.d) / json.d
var data = json.d;
for(i=0;i<data.length;i++) {
alert(data[i].fieldname);
}
I have a few jQuery plugins that I made - all parse JSON feeds and render them using Mustache.js; each plugin takes an integer value of how many items to display.
I received a Uncaught TypeError: Cannot read property 'link' of undefined when trying to parse the Stack Overflow JSON feed with the following code:
$.ajax({
type: 'GET',
url: query,
contentType: "jsonp",
dataType: 'jsonp',
success: function (jsonp) {
/* loop through JSON items converting the time from UNIX timestamp
** format to readable words by parsing it through timeConverter() */
var i;
for (i = 0; i < jsonp.items.length; i++) {
if (i > num-1){
delete jsonp.items[i];
} else {
jsonp.items[i].creation_date = timeConverter(jsonp.items[i].creation_date);
}
}
var output = Mustache.render(must_template, jsonp);
element.html(output);
return element;
} //EOF CALLBACK
}); //EOF AJAX
As a quickfix I disabled the truncation by simply commenting out the delete operation. The error suggests that Mustache.js is trying to access part of the JSON object which no longer exists; yet the delete operation clearly only affects items which are above the user-defined limit.
When this behaviour occured there were still 20 items in the array.
Note:
Yes, I've answered this question myself; however - I'm more than willing to accept another answer if it shows best practice, a neater way or improves upon my answer in some way. :)
delete is a "lower-level" operator compared to arrays. It directly removes the object property, bypassing all the specific array logic and hence does not update the length of the array.
If you want to delete an element from an array, use either .splice [MDN], or in your case you can simply set the length of the array and iterate over the remaining elements afterwards:
jsonp.items.length = Math.min(num, jsonp.items.length);
for (i = 0; i < jsonp.items.length; i++) {
jsonp.items[i].creation_date = timeConverter(jsonp.items[i].creation_date);
}
Delete is not changing array count as you already found out, it's only removing key. To remove items from array you can use splice. Example:
var array2 = [ 1, 2, 3, 4 ];
array2.splice(2, 1);
console.log('---------------------------');
console.log(array2.length); // 3
console.log(array2[0]); // 1
console.log(array2[1]); // 2
console.log(array2[2]); // 4
console.log(array2[3]); // undefined
Working sample: http://jsfiddle.net/qbXjp/1/
After much googling I couldn't find anything, even StackOverflow had failed me. Then, by chance, I came across this unintended side-effect of my 'quick hack' of commenting out the delete line..
Due to the fact I hadn't commented out the whole if/else block, my timeConverter() function wasn't being ran on the items which would ordinarily be deleted. This confirmed that the combination of for() and if(){} / else{} were working correctly. So it appeared as though Mustache.js was trying to access items that were already deleted! Almost as if the length property of the items[] array wasn't being updated when items were being deleted.
I made a jsFiddle test case and this confirmed it was the issue. Here's the code and ouput:
$.ajax({
type: 'GET',
url: query,
contentType: "jsonp",
dataType: 'jsonp',
success: function (jsonp) {
/* loop through JSON items converting the time from UNIX timestamp
** format to readable words by parsing it through timeConverter() */
var i;
for (i = 0; i < jsonp.items.length; i++) {
if (i > num-1){
console.log("Deleting item. Current Count: "+jsonp.items.length);
delete jsonp.items[i];
console.log("Deleting item. New Count: "+jsonp.items.length);
} else {
jsonp.items[i].creation_date = timeConverter(jsonp.items[i].creation_date);
}
}
console.log(jsonp);
return element;
} //EOF CALLBACK
}); //EOF AJAX
I tried a quick fix of using a counter to count each deletion, and then subtracting the deletion counter from the length property (jsFiddle):
$.ajax({
type: 'GET',
url: query,
contentType: "jsonp",
dataType: 'jsonp',
success: function (jsonp) {
/* loop through JSON items converting the time from UNIX timestamp
** format to readable words by parsing it through timeConverter() */
var i, deleted = 0;
for (i = 0; i < jsonp.items.length; i++) {
if (i > num-1){
delete jsonp.items[i];
deleted++;
} else {
jsonp.items[i].creation_date = timeConverter(jsonp.items[i].creation_date);
}
}
jsonp.items.length -= deleted;
console.log(jsonp);
return element;
} //EOF CALLBACK
}); //EOF AJAX
Here was the output this generated:
This code then ran fine when placed back in to the test environment and utilised with Mustache.js. Using the delete keyword doesn't affect the length property when used on an array
Coming from a Java background I'd taken for granted the fact that length is a property, and not a function - and therefore it isn't nessacerily updated upon any changes being made to the array. A stupid mistake that cost me more time than it should've! However, I couldn't find any other posts regarding this so I thought I'd post it up in the hope it can help anyone else in a similar position!
My tomcat log is only showing one item being passed in..
var itemArr = ["someItem", "someItem2", "someItem3"];
$.ajax({
type: "POST",
url: "myServlet",
data: $.param({item: itemArr})
});
The array contains around 20 elements.
Also if i do:
var params = $.param({item: itemArr});
alert(params);
All the values come out formatted as item=someitem&item=someitem2..etc etc
But the ajax post only outputs the first item from the array. I want them all passed through to the server in the request.
Any help would be much appreciated.
EDIT:
Using version 1.3.2 also tried with 1.4.4 - same problem
I think your $.param() call should just be this:
var itemArr = ["someItem", "someItem2", "someItem3"];
$.ajax({
type: "POST",
url: "myServlet",
data: $.param(itemArr)
});
EDIT: Nick is onto something there...
From the jQuery.param() documentation:
// <=1.3.2:
$.param({ a: [2,3,4] }) // "a=2&a=3&a=4"
// >=1.4:
$.param({ a: [2,3,4] }) // "a[]=2&a[]=3&a[]=4"
EDIT AGAIN
Maybe something like this will work for you, to emulate the 1.4 behavior:
var itemArr = ["someItem", "someItem2", "someItem3"];
var paramed = decodeURIComponent($.param({ 'item[]': itemArr }));
Demo here: http://jsfiddle.net/Ender/EHd78/1/
Oh right I missed the first sentence, yes you will only get one item passed to your server it should be an array.
This from firebug when I make that request,
item[] someItem
item[] someItem2
item[] someItem3