Given JSON containing:
[
{"myKey":"A","status":0,"score":1.5},{"myKey":"C","status":1,"score":2},
{"myKey":"D","status":0,"score":0.2},{"myKey":"E","status":1,"score":16},
{"myKey":"F","status":0,"score":0.4},{"myKey":"G","status":1,"score":3}
]
Given JS such:
MyJSON = $.getJSON('http://d.codio.com/hugolpz/getJson--/App/data/statusStarter2.json' );
How to get the JSON's content (stringified) into localStorage.data ?
Note: localStorage.data = JSON.stringify(MyJSON); returns {"readyState":1}, which is not my wish. I looked into jQuery.getJSON/, but I'am quite confused by the function (data).
getJSON works asynchronously and what it returns is AJAX request object. So use success callback function of getJSON to recieve the data
$.getJSON('http://d.codio.com/hugolpz/getJson--/App/data/statusStarter2.json', function(data) {
// do JSON.stringify(data) here
});
Did you try :
localStorage.setItem('data', JSON.stringify(MyJSON));
and
var JSON = localStorage.getItem('data');
and as ajax is async :
$.getJSON('url', function(MyJSON) {
localStorage.setItem('data', JSON.stringify(MyJSON));
});
Related
It may be possible this question has been posted so many times.But i didn't get answer from those one.I have passed url in Ajax call and i want whatever i'm getting from database through the query,get in success method of ajax request.But somehow i didn't get this.
Ajax call method:
function validateAmount() {
var amount = document.getElementById("amount").value;
// alert(amount);
// var y = x.value;
$.ajax({
url : "{{url('getAmount')}}",
type : "GET",
async : false,
dataType : "json",
success : function (result) {
alert();
}
});
}
and database query:
And this is what i want to return
public function getAmount(){
$user_id = session('user_id');
$res = DB::table('table_name')->where(['user_id'=>$user_id])->first();
return $res;
}
And one more thing,when i simply echo string in getAmount method ,ajax call get succeed but when i try to access the data through query,i'm getting fail.
Please help me to get this.
Any help will be appreciated.Thanks in advance.
First : Remove the async: false as Rory mentioned in the comments.
Second: For the ajax you have to use the echo json_encode($my_data_array);
Third: Dont use alert rather use console.log(result) to view your data.
Use Collection::toJson() method to transform you collection to json string:
$res = DB::table('table_name')->where('user_id', $user_id)->first();
return $res->toJson();
Collection::toArray() works too
So I'm working on jQuery for the first time. When I use this:
var data = $.getJSON("https://hackernews.firebaseio.com/v0/item/14279870.json", function(data) {
data = JSON.stringify(data)
});
console.log(data);
I get this guy in the log: object view
But if I try to log data.text, data.responseText, or anything like that I just get undefined. How do I get the data?
The problem is that console.log executes before data = JSON.stringify(data) because $.getJSON call is asynchronous.
That means that what you see in the console is not the object that you get inside your success callback.
To get a proper representation of your data object (after the server call), put the console log inside the callback function:
$.getJSON("https://hackernews.firebaseio.com/v0/item/14279870.json", function(data) {
console.log(data);
data = JSON.stringify(data)
console.log(data);
});
Live example with a sample JSON file (your URL returns null):
$.getJSON("http://echo.jsontest.com/key/value/one/two", function(data) {
console.log("JSON: ", data);
data = JSON.stringify(data)
console.log("Stringified: ", data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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 have application.php page where json array is echoed with php. On the client i want to get the json array with $.getJSON() on button click when form is submitted(submitHandler). The problem is that if I run alert() or console.log() in $.getJSON() nothing happens(i only see GET execution in console).
Code:
$.getJSON('../views/application.php', function(data) {
alert('alert1');
if(data) {
document.write(data.resp);
alert('alert2');
}
else {
alert('error');
}
});
GET http://localhost/app/views/application.php
you can use var temp in your script and store your data inside that variable.
var x;
<script type="text/javascript">
x='<?php echo $comparisonResult; ?>';
</script>
Sounds like a use case for sessionStorage or cookies.
Use sessionstorage if you don't need to support IE7.
I think the best way is to return the needed server data in the response of your first post request, just like this :
$.post( "/first.php", function( serverData ) {
var param = serverData.something;
...
$.post( "/second.php", param, function( data ) {
...
});
});
If you are using the two request in two different pages, you can store serverData in localStorage.
Edit after your clarification:
If you need to get data before ajax post when you click on a button, you can do this way :
$("#second-button").click(function() {
$.getJSON("/data.php", function (serverData) {
var param = serverData.something;
$.post("/second.php", param, function(data) {
...
});
}
});
Edit 2
For some reason (wrong url, invalid json, and so on) your $.getJSON fail.
Try this for debug:
$.getJSON("/data.php", function (serverData) {
console.log(serverData);
}).fail(function(j, t, e) {
console.error(e);
});
I receive the following
[{"user_id":"1","user_invoice_add1":"Stark Towers","user_invoice_add2":"123 Reginald Street","user_invoice_city":"Newport","user_invoice_state":"New York","user_invoice_country":"US","user_invoice_zip":"321654"}]
How do I pick out information from it?
trying data.user_id or data[0].user_id returns as undefined
jQuery
$.post('post.php', qString, function (obj) {
console.log(obj);
}
You'd have to first convert this string into JSON object by using a jQuery function var obj = $.parseJSON(data).
It will return you a JSON object that you can access like obj[0].user_id
use this:
myObject = jQuery.parseJSON( dataReceived );
and then you can access the data as properties of the object
Try like this..
$.map(data.d, function (item) {
alert(item.user_id)
});
jquery.ajax has a setting called dataType this is what your getting response from server as..
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown.
$.ajax({
....
dataType:"json",
success:function(data){
alert(data.user_id) //no need to parseJSON...dataType does it
};
});
Using POST
$.post('post.php', qString, function (obj) {
console.log(obj);
}, "json");
or you can use $.parseJSON(data) to convert the string as json object