I have a simple javascript file, javascriptvar.js, which contains a json within that file like this:
var ajavascriptjsonvariable = {
id: "someid",
name: "somerandomname",
data: {},
children: []
};
What i am trying to do is to simply make the var ajavascriptjsonvariable equal to a text file where the json is stored. So i create a file called "data.json" with this inside:
{
id: "someid",
name: "somerandomname",
data: {},
children: []
}
(I'm not sure if i need a semicolon in the end of data.json or not?)
And now i try to make the variable ajavascriptjsonvariable in the js file read the data.json file, but it won't go through. Here's what i do:
$.getJSON("data.json", function(data){});
var ajavascriptjsonvariable = data;
How do i get the ajavascriptjsonvariable = the data.json file?
Edit, sorry, quotes were a typo, corrected them, what i am asking is i think i'm supposed to include something into function(data){} brackets part to make ajavascriptjsonvariable read the data.json file, i don't know that part, that's what i'm trying to figure out.
first of all the JSON wont validate it should look like this
{
"id": "someid",
"name": "somerandomname",
"data": {},
"children": []
}
next since you are making an ajax call here, u must assign the value inside the ajax callback function
$.getJSON("data.json", function(data){
var ajavascriptjsonvariable = data;
/* Rest of the code with uses the "ajavascriptjsonvariable" variable */
});
AJAX is asynchronous, in 99% of all cases assigning a value to a variable which you do not use in the callback function is wrong. Here's what you should do:
$.getJSON("data.json", function(data) {
// use data here
});
Obviously you can assign data to some other variable that exists in an outer scope, but then you cannot just use it after the $.getJSON() call! You need to call whatever codes relies on the result from your callback function.
var MyVariableModule = (function($){
var myJavaScriptJsonVariable = null;
var getJsonFile = function(){
return $.getJSON("data.json").done(function(data) {
myJavaScriptJsonVariable = $.trim(data);
});
};
return {
makeComparison : makeComparison
};
})(jQuery);
Related
I would like to extract a CSV local file in PHP using AJAX.
To do that I tried to use Papa Parse and it works great. The problem is to pass the results with AJAX. I tried with JSON.stringify, I tried to pass only the first field; I tried also to create a JSON object and then add the results to this object but, I don't know why, when I extract in PHP I got only the values of the original object.
values = {};
values['row_1'] = 'value1';
values['row_2'] = 'value2';
i = 3
$("input[type=file]").parse({
config: {
delimiter: ",",
step: function(results) {
value = results.data[0]
values['row_' + i] = value
i = i + 1
}
}
});
$.ajax({
type: "POST",
url: "extract-csv.php",
data: {
id: $('#id').val(),
...
values: values
}
...
})
With this code on PHP I returned only "value1" and "value2" (if I print "values" in the console I get object with 2++ elements)
Papa Parse worked after Ajax, so the solution is to put the Ajax call in the "Complete" Papa Parse function and then everything works fine!
i have a file locally which has array of objects in my view i need it to be warped as a variable, on viewing the variable that array should be used
i tried this but i dont know its the right way could some one help me
var url = 'proj/array/arrayobject';
console.log(url);
var refreshId = setInterval(function(){
$('div.comment-container').comment({
//here i should call that url and display object one by one with equal intervals
})
}, 1000);
could some one help me
First of all I would suggest to keep that file as JSON file having .json extension. It would make the file purpose more clear.
Secondly, You can use jQuery Ajax's getJSON() method to get data of that file and assign it to your local or global variable like below:
var myGlobalVariable = null;
$.getJSON("proj/array/arrayobject.json", function( data ) {
myGlobalVariable = data;
});
Then, You can use your myGlobalVariable in your code. But, Make sure that you use it once you get data in it. For this you can use callbacks.
For your scenerio, Code will be like below:
var url = null;
function init() {
$.getJSON("proj/array/arrayobject.json", function(data) {
url = data;
MyFunc();
});
}
function MyFunc() {
setInterval(function() {
$('div.comment-container').comment({
// use url here
})
}, 1000);
}
$(function() {
init();
});
I am unable to parse the json file obtained from this http://dbpedia.org/data/Los_Angeles.json url.
I need to find the populationTotal, areaTotal, populationDensity fields from the json data obatined from the URL above.
This is a snippet of the json data obtained from http://dbpedia.org/data/Los_Angeles.json url.
Eg.
"http://dbpedia.org/ontology/populationTotal" : [
{ "type" : "literal",
"value" : 3792621 ,
"datatype" : "http://www.w3.org/2001/XMLSchema#integer" } ] ,
"http://dbpedia.org/ontology/PopulatedPlace/areaTotal" : [
{ "type" : "literal",
"value" : "1301.9688931491348" ,
"datatype" : "http://dbpedia.org/datatype/squareKilometre" } ,
How could i get this Json data and output it using Javascript.
Do this help you?
var populationTotalData=[];
for(var key in data) {
if(key.match(/populationTotal/))
// or simplier: if(key.indexOf("populationTotal")>-1)
populationTotalData.push(data[key]);
}
Because of the Same-Origin Policy, you often can't directly fetch the data using JavaScript. However, it turns out that dbpedia.org supports JSON-P, so you can get the data with straight JavaScript like this:
// This is the "callback" function. The 'data' variable will contain the JSON.
// You can access it like I have done in the alert below.
mycallback = function(data){
alert(data["http://fr.dbpedia.org/resource/Los_Angeles"]["http://www.w3.org/2002/07/owl#sameAs"][0].value);
};
// This is the function we use to fetch the JSON data:
function requestServerCall(url) {
var head = document.head;
var script = document.createElement("script");
script.setAttribute("src", url);
head.appendChild(script);
head.removeChild(script);
}
// Note the query string that I have added (?callback=mycallback).
// This is the name of the function that will be called with the JSON data.
requestServerCall('http://dbpedia.org/data/Los_Angeles.json?callback=mycallback');
A lot more really excellent information on JSONP can be found here. You could loop inside of the mycallback function using some code like this. Obviously, you'd have to make nested loops to get exactly what you want, so this code would need modifying to fit your exact needs.
<script type="text/javascript">
for(var index in data) {
console.log(data[index]);
}
</script>
The other method would be via PHP. For example: you could pitch the whole page into a JavaScript variable like this:
<?php
$los_angeles = file_get_contents('http://dbpedia.org/data/Los_Angeles.json');
?>
<script type="text/javascript">
var data = <?php echo $los_angeles; ?>;
alert(data["http://fr.dbpedia.org/resource/Los_Angeles"]["http://www.w3.org/2002/07/owl#sameAs"][0].value)
</script>
I want the data returned from an ajax post to be put into a javascript variable where I can then run an if statement checking whether that variable is equal to true. However, Firebug is telling me the variable verify is not defined. How do I write the function within the ajax post to set the data to verify correctly? Code is below.
$.post('ajax_file.php',
{
user_id: user_id,
band_term: band_term
}, function (data) {
var verify = data;
if (verify == 'true')
{
$('#request_form').hide();
$('#where_to_go').hide();
$('#change_form').show();
}});
The ajax file returns true on success and false on failure.
if (mysql_query($sql) == true)
{ echo 'true';} else {echo 'false';}
Firebug shows me that the ajax file is returning with the string true, so I know the ajax file is working.
The issue is on a few places.
First, how you output data on you .php file. You should be returning JSON and accepting JSON on you ajax request. Look at this example:
<?php
$variable = array("stat" => true, "data" => array(10, 10));
print_r(JSON_Encode($variable));
?>
That will output this:
{"stat":true,"data":[10,10]}
Then on yout JS you'd do:
$.post('ajax_file.php', {
user_id: user_id,
band_term: band_term
}, function (data) {
//Data is the whole object that was on the response. Since it's a JSON string, you need to parse it back to an object.
data = JSON.parse(data);
if (data.stat === true){
$('#request_form').hide();
$('#where_to_go').hide();
$('#change_form').show();
}
});
It's because verify was created in the callback function. Also, that variable isn't visible outside that function.
To operate on returned data from an AJAX call, do it in the callback function.
$.post('ajax.php', {
user_id: user_id,
term: term
}, function (data) {
var verify = data; //assuming data is just true or false
if (verify === 'true') {
unnecessary code
}
});
The variable is defined inside the callback function is does not match the scope of the document.
To make it actually work, just define it anywhere in the beginning of your script as follows:
var verify;
$.post('ajax.php',
{
user_id: user_id,
term: term
},
function (data)
{
verify = data; // then also remove the word var from your code here.
if (verify == 'true')
{unnecessary code}
}
);
-i wouldn not use j query for ajax ( i find getdata to be better but the call back variable needs to be passed to the next function
ie. if you are gonna alert(data) as your call back, do your if statements there.
also i was running into similar problems. using numbers such as one or zero in my php response helped alot, and i just used js to determine what the actual string or alert output would be
I'm having some trouble with my AJAX request.
The problem is with the JSON object named html.
AJAX request:
$.ajax({
url : 'index',
type : 'POST',
dataType : 'json', // Makes no difference
data : {
method : 'saveModule',
html : content
},
success : function(i){
console.log(i);
}
})
I know it's about the html JSON object because if I remove it the request will succeed.
This is what it looks like with firebug's console.log();
the object is stored within [ ], is that normal?
[Object { name="Home", link="/home"}, Object { name="Work", link="/work", childs=[3]}, Object { name="Contact", link="/contact", childs=[2]}]
The childs are JSON objects as well.
Please help, it's driving me crazy!
The error I'm getting with the Web Console:
[11:58:47.215] uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://localhost/mcms/htdocs/templates/resources/js/jquery-1.6.3.min.js :: <TOP_LEVEL> :: line 5" data: no]
The content var is made from this:
var content = mcms.module.analyse(obj); // obj is a dom element, in this case a UL with sub ULs inside LIs
The function itself:
analyse : function (that) {
return $(that).children('li').map(function() {
var b = {
name: $(this).children('a').text(),
link: $(this).children('a').attr('href')
};
if ($(this).children('ul').size() > 0) {
b.childs = mcms.module.analyse($(this).children('ul'));
}
return b;
});
}
I've found the problem and fix!
The problem was that the .map() function returns an array around the JSON object.
So I made a JSON object with a counter around the map to capture it and return it :)
Thanks for helping everyone!
analyse : function (that) {
var b = {};
var x = 0;
$(that).children('li').map(function() {
b[x] = {
name: $(this).children('a').text(),
link: $(this).children('a').attr('href')
};
if ($(this).children('ul').size() > 0) {
b[x].childs = mcms.module.analyse($(this).children('ul'));
}
x++;
});
return b;
}
I'm not so sure about the method parameter. If that is the method you are looking to call, you can as well include that in your URL, right?
Well, your current call to $.ajax doesn't look exactly right. It should be something along the lines of:
$.ajax({
url : 'index',
type : 'POST',
data : <data to be sent>
dataType : <Default: Intelligent Guess (xml, json, script, or html)>
success : function(i){
console.log(i);
}
})
More info on the jQuery website: http://api.jquery.com/jQuery.ajax/
EDIT
Ok, I see you corrected the call. This looks better now. Where does content come from and what's in it before it is converted into a JSON object?
EDIT2
Well, I think this answer should be of help to you: Post Nested Object to Spring MVC controller using JSON