java script to json - javascript

If I have an array like
price=["1#1000", "1000#2000"]
how to convert it into JSON so that it can be send into ajax call of jQuery
$.ajax({
type: 'POST',
url: '',
data: {
'price': price
},
dataType: 'JSON',
success: function(data) {
console.log("success");
console.log(data);
var products = data.products;
console.log(products);
},
});

Since you already posted...parts of jQuery, here is a jQuery plugin that should do it
http://plugins.jquery.com/plugin-tags/stringify
|EDIT| The jQuery-plugins-site is put down for a while.
Anyways, you a looking for a function called Stringify. You can read more about it here:
http://www.json.org/js.html
A simple google-search should give you plenty results.

When writing price=["1#1000", "1000#2000"] you already have your data represented as a javascript array.
It should be possible for you to simply pass this as an argument as you have described within your use of the $.ajax method.
Alternatively (if you really need to parse price as a json object) see the jQuery builtin function for this: http://api.jquery.com/jQuery.parseJSON/
But recheck that this is not just possible, as you have described it, if not, what errors are you getting?

Related

Ajax request, fetch JS array and make it available

I'm trying to fetch a JS array created by a PHP file and re-use the JS array in a JS script in the page. I have tried many different solutions found on this site but none seems to work but I don't know what the issue is with my script.
I have a PHP file that echoes the following:
[["content11", "content12", "content13", "content14","content15"],
["content21", "content22", "content23", "content24","content25"]]
I'm using a simple Ajax get to retrieve the data:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html",
success : function(data)
{
result = data;
alert (result);
}
});
The alert displays the expected output from the PHP file but if I now try to access the array like result[0], it outputs "[" which is the first character. It looks like JS sees the output as a string rather than an array.
Is there something I should do to make JS understand it's a JS array?
I have seen many solution with JSON arrays but before going into this direction, I'd like to check if there are simple solutions with JS arrays (this would prevent me from rewriting too much code)
Thanks
Laurent
In you php file you need check that your arrays echos with json_encode.
echo json_encode($arr);
And in your javascript file:
$.ajax({
type: "GET",
url: myUrlToPhpFile,
dataType: "html", // json
success : function(data)
{
var res = JSON.parse(html);
alert(html); // show raw data
alert(res); // show parsed JSON
}
});
You can use JSON.parse to format the string back into an array.
JSON.parse(result)[0]
or
var result = JSON.parse(result);
result[0];
#Rho's answer should work fine, but it appears that you're using jQuery for your AJAX call, which gives you a shortcut; you can use $.getJSON instead of $.ajax, and it will read the data as JSON and provide you with the array immediately.
$.getJSON(myUrlToPhpFile, function(result) { ... });
This is really just a short way of writing what you already have, but with a dataType of json instead of html, so you could even do it that way if you prefer. This is all assuming that you're using jQuery of course, but your code was following their API so it seems a good bet that you're either using jQuery or something compatible.

get json data with jquery

Hey guys I would like to know how can I get json data with ajax call.
I tried this but seems won't work :P
First I created a JavaScript file to put inside my json data elements :
var food = [
{'name':'bread', 'price':'7,25'},
{'name':'fish', 'price':'9,00'}
];
I saved it as food.js.
Then I tried to make an ajax call from an another file, this is my code :
$(document).ready(function(){
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food.name;
alert(result);
});
}});
});
Any ideas?
Thanks in advance ;)
Firstly, you have a syntax error in your example - there's too many closing braces on the $.ajax call, although I guess that's just a typo.
In your JSON, food is an array, so you need to use an indexer to get the properties of the objects within it:
success: function(data) {
var result = data.food[0].name; // = "bread"
alert(result);
});
try this
$(document).ready(function() {
$.ajax({
async: false,
dataType: "json",
type:'GET',
url:"food.js",
success: function(data) {
var result = data.food[0].name;
alert(result);
}
});
});
You need to loop through the returned data since it's an array:
$.each(data,function(i,val) {
alert(data[i].name);
});
I love how people are completely ignoring the fact that your "food.js" is not a JSON string, it's JavaScript code. This might work on old-school eval-based "JSON", but with jQuery AJAX your target file should be plain JSON. Remove the var food = from the start, and the ; from the end.
Then you can access data.food[0].name;
In this case, you are trying to get an another javascript file via ajax. For do this, you can "include" your script ( of food.js ) in your page, using Ajax GetScript ( see here ).
Your code is mucth better when you request directly json files.
You probably want to use the getJSON function in jquery : http://api.jquery.com/jquery.getjson/
$.getJSON( "food.json", function( data ) {
//here your callback
}
It will set the datatype to json and the method to GET by default.
You should also use the .json extension and not the js extension for you jsons. And format it like a proper json :
{
"food": [
{
"name": "bread",
"price": 7.25
},
{
"name": "fish",
"price": 9.00
}
],
}
You can use this website to help you format jsons : http://www.jsoneditoronline.org/
The way you are trying to call your element won't work. The data you obtain is an array. In the callback, you can try this :
console.log(data)
console.log(data.food)
console.log(data.food[0])
console.log(data.food[0].name)
console.log(data.food[0].price)
Finally, note that you formatted your numbers with a coma, this is not the way you format numbers in javascript. Use a dot, that way you'll be able to manipulate it as a number.

Enumerating through Yahoo Pipes generated JSON with jQuery fails

I'm trying to lessen manual update work by using Yahoo Pipes and jQuery to update a table with upcoming events from a different domain. I have created this Pipe to gather the data, and it seems to work.
Now I am reading the JSON file with the following jQuery Script taken from this tutorial:
$.ajax({
type: "GET",
url: "http://pipes.yahoo.com/pipes/pipe.run?_id=57aa32bf3481c8dca0c07afcf9b9dc29&_render=json",
async: false,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
$('body').append(data.query.results.a.content);
}
});
The jQuery append failes, I guess because 'data.query.results.a.content' does not relate well to the JSON structure created by the pipe.
I've tried altering both the pipe and the append in several ways and am just short of giving up, I'd be very grateful for your Input.
Think you are parsing the json result incorrectly.
On viewing the json object here http://jsonviewer.stack.hu/
You will observe content node for each item is at value.items[0].a.content
i.e. try something like this :
$('body').append(data.value.items[0].a.content);
You will need to iterate the items array like this
$.each(data.value.items, function(index,element) {
$('body').append(element.a.content);
});
Try it on fiddle : http://jsfiddle.net/EFvJf/

jQuery now showing the phrased variable value

Stuck on the first stage of a big project. I am trying to display the JSON value that I get from URL shown below. It shows the data when I past the URL on the a browser. But when I put the URL in variable and try to show in html it doesn't show the phrased value.(I will delete the app/key one I get the solution.) Thanks in advance.
http://jsfiddle.net/rexonms/6Adbu/
http://api.flickr.com/services/rest/?format=json&method=flickr.photosets.getPhotos&photoset_id=72157629130565949&per_page=10&page=1&api_key=ccc93a20a1bb9060fa09041fa8e19fb5&jsoncallback=?
Have you tried using the $.getJSON() or the $.ajax() method? This seems to return the data just fine:
$.getJSON(apiCall, function(data) {
console.log(data);
});
Here's a working fiddle.
Additional Information
It seems like you may benefit from a simple tutorial that explains AJAX in relation to jQuery's $.getJSON() and $.ajax() methods.
$("<span>").html(apiCall)
apiCall is a string (containing the URL). All you're doing here is setting a span to have the URL as its content. You need to actually use AJAX to load said URL.
$.ajax({
url: 'http://api.flickr.com/services/rest/',
dataType: 'jsonp',
type: 'GET',
data: {
format: 'json',
method: 'flickr.photosets.getPhotos',
photoset_id: '72157629130565949',
per_page: 10,
page: 1,
api_key: 'ccc93a20a1bb9060fa09041fa8e19fb5'
},
jsonp: 'jsoncallback',
success: function(data){
console.log(data);
}
});
Inside success, data is the JSON object returned by the API.

pass array and individual string to php file using ajax call

I try to implement the following code
var flag = new Array();
var name = $("#myselectedset").val();
$.ajax({
type: 'post',
cache: false,
url: 'moveto.php',
data: {'myselectset' : name,
'my_flag' : flag
},
success: function(msg){
$("#statusafter").ajaxComplete(function(){$(this).fadeIn("slow").html(msg)});
}
});
You can see that the name is a single string and the flag is an arry, am I using the right format for passing them throw ajax call, anyone could help me, thanks
It is impossible to pass arrays in a POST request. Only strings.
You will either need to stringify your array, or consider posting as JSON instead.
You should be able to do something quite simple, like replace your "data" property with:
data : JSON.stringify( { myselectset : name, my_flag : flag } )
That will convert the data into a JSON string that you can turn into PHP on the other side, using json_decode($_POST["my_flag"]);
Very important note:
For JSON.stringify to work, there can't be any functions in the array - not even functions that are object methods.
Also, because this is a quick example, make sure that you're testing for null data and all of the rest of the best-practices.

Categories

Resources