<script>
$.get("url", function(data, textStatus, jqXHR) {
var json = JSON.stringify(data);
});
// I would like to use **json** variable here
</script>
Hey,
I would like to get data from url. I can get the JSON file and stringify it to json variable. But I have some struggles when I 'm trying to use json variable. Because, it is local variable.
Also,
<script>
var json = "";
$.get("url", function(data, textStatus, jqXHR) {
json = JSON.stringify(data);
});
// I would like to use **json** variable here
</script>
when I am trying to use json as a global variable, even I can not stringify data to it.
Question : How can I solve my problem?
It would be better to use your JSON data when it is available by putting the dependent code in a callback or a promise:
$.getJSON("url").then(function(data) {
// json is already parsed here
// put json dependent code here
});
You could also put your application logic in a function (assuming it's depending on the JSON data) and use that as your callback:
function initialize(data) {
// all of your data dependent logic here
}
$.getJSON("url").then(initialize);
Related
my search params is
$params=Yii::$app->request->queryParams;
And my api call is like
function doInBackground(){
var params=<?=json_encode($params)?>;
$.get('car/get-map-data',
{
"params":params
},
function(data){
if(data)
{
console.log(data);
}
});
}
But i am getting an error like
PHP Notice – yii\base\ErrorException
Array to string conversion
on the line
var params=<?=json_encode($params)?>;
How to solve this.I want to pass the search params to another api.
you can use getQueryString()
function doInBackground(){
var params=<?=Yii::$app->request->getQueryString();?>;
$.get('car/get-map-data',
{
"params":params
},
function(data){
if(data)
{
console.log(data);
}
});
}
I think that handling the query params via URLSearchParams would be more non-hacky and clearer solution than obtaining them via PHP.
By URLSearchParams you can collect them into JS object and properly pass it as POST data to your AJAX request.
I have an API endpoint like this:
https://client.systemonesoftware.com/bannink/json/?language=nl
I need to read and parse it into a table with all the information. But I get no output when I try to do it with Javascript.
<script>
$.getJSON('https://client.systemonesoftware.com/bannink/json/?language=nl', function(data) {
var json = JSON.parse(data);
alert(json.cached);
alert(json.data[1].id);
});
</script>
This piece of code gives nothing..
$.getJSON returns JavaScript object so you don't need to parse it, try:
$.getJSON('https://client.systemonesoftware.com/bannink/json/?language=nl', function(json) {
console.log(json.data[1].id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.
I believe your issue is that the data already comes through parsed:
<script>
$.getJSON('https://client.systemonesoftware.com/bannink/json/?language=nl', function(json) {
alert(json.cached);
alert(json.data[1].id);
});
</script>
I could not retrieve data to jquery div element but i can see ajax response in firebug.
$(document).ready(function () {
$.ajax({
url: "https://m.lowes.com/CatalogServices/product/nvalue/v1_0?nValue=4294857975&maxResults=6&showURL=1&rollUpVariants=1&showUrl=true&storeNumber=0595&priceFlag=rangeBalance&showMarketingBullets=1&callback",
dataType: "jsonp",
success: function (data) {
var returnedData = JSON.parse(data);
$('#result').html(returnedData);
}
});
})
this is my response.for example my url contains data productCount:64 ,I should extract productCount from ajax success and display it in html div id result
When you parse out the JSOn data you use it like so:
var parsed_data = JSON.parse(JSON_DATA);
$('#result').html(parsed_data.key);
So if your parsed_data is somewhat like:
{name:"test",age:12}
then you use it like:
$('#result').html(parsed_data.name); //it will give you test
if you really want to print out the whole data use JSON.stringify(obj) like so:
$('#result').html(JSON.stringify(parsed_data));
In your code you are returning a json and you are trying to insert ino the div it, into the div you can only insert html code instead json.
Try to inspect the json you are returning and in case you need to insert each element into the div, do it, but don't do for all.
The html() method doesn't know what you want to assign, it only insert an html.
You need to iterate over your json data in returnData. You are not able to put json directy into html. You need to convert / parse / iterate it before. So, for example:
$.each(returnedData, function (index, value) {
// do stuff with it, e. g.:
// $('#result').html($('#result').html() + value);
});
https://jsfiddle.net/m8udusps/
The code here actually works. However it says there is a problem when it is parsing the JSON. You needed to add crossDomain: true, to allow it to actually get the results.
Having received a supposed JSON struct like:
{
"Field1": "value1",
"Field2": "value2"
}
This code gets the values of the keys (just first key in this example). Result is an alert message with Data: value1:
$.ajax({
'url' : './localurl',
'type' : 'GET',
'success' : function(data) {
alert("Data: "+data.Field1);
},
'error' : function(request,error) {
alert("Error in response: "+JSON.stringify(data));
}
});
In this case Field1 is the key received and it is directly accesible through data variable, so it is not necessary to do the JSON.parse(data) (in fact this JSON.parse produce an error)
I'm trying to save the .ajax response, which queries a xml from a REST interface, but I am not successful. Until now the code works, and I get the response, but optimally I would like to parse some of the items into javascript variables or at least save the whole response into one variable. My code looks is the following:
// the actual request
function request(url) {
$.ajax({
type : "GET",
url : "localhost:8080/package/rest/pubs/getpubswithinbbox?south=41.886288445510516&west=12.483901977539062&north=41.893700240146295&east=12.500102519989014",
dataType : "xml",
success : function (data) {
console.log("Successfully queried API!");
console.log(data);
},
error : function (data) {
console.log("An error occurred while processing XML file.");
}
});
};
//Code Ends
Using console.log(data) I also can view the file as a document, but as already mentioned, I would like to save some XML-Elements into variables (or the whole XML document for a later processing).
The XML looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><osm generator="Overpass API" version="0.6">
<note>The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.</note>
<meta osm_base="2014-06-05T12:35:02Z"/>
<node id="1701218666" lat="41.8885564" lon="12.4950752">
<tag k="amenity" v="pub"/>
<tag k="name" v="Camden Town"/>
</node>
</osm>
Do you have any tips of how to proceed with my code snippets? I want to set the request to sync by using async: false
Thanks!
Create div tag in html body like and in jquery ajax part just use $(#result).append(data); inside sucess function
The response object you define within your success/error callbacks can be used as any other JS object. So if you have an existing variable you want to assign it to, do so (though try to avoid cluttering the global namespace) or even attach it to the page using jQuery's .data() function. Example:
// the actual request
function request(url) {
$.ajax({
type : "GET",
url : "localhost:8080/package/rest/pubs/getpubswithinbbox?south=41.886288445510516&west=12.483901977539062&north=41.893700240146295&east=12.500102519989014",
dataType : "xml",
success : function (data) {
console.log("Successfully queried API!");
console.log(data);
$('body').data('APIResult',data);
},
error : function (data) {
console.log("An error occurred while processing XML file.");
}
});
};
Then, elsewhere in your script, whenever you want to reference or use the API response, simply call it or assign it to a local var as such:
var APIData = $('body').data('APIResult');
foo = data
Note that foo will remain undefined until the asynchronous function has been resolved.
You should probably declare foo in the scope you want it in (using var foo outside the call to ajax).
I intend to access set of records from MYSQL and handle it in Javascript for a calendar component. Hence I used PHP to fetch the records and dumped it as a array of json records to a flat file. Now i tried to read this json via flatfile from javascript but I am facing few issues.
var event_list;
$.getJSON("testFile.json", function(json) {
alert("fetching");
event_list= jQuery.extend(true, {}, json);
alert(json);
event_list=json;
alert(JSON.stringify(event_list)); // This echo's me the data
});
alert(JSON.stringify(event_list)); // But this doesn't ???
I am unable to access the data outside the scope of getJSON() routine.
It would be great if someone could help me with this snippet.
You can't access the fetched JSON outside of the callback because it's bound to the scope of the callback, which may or may not be asynchronous (in this case, it is).
You can however hide the scoping by using Deferred (aka Promises/A).
jQuery has support for it like this:
var request = $.getJSON("testFile.json");
request.done(function (data) {
console.log(data);
});
So now request is a promise that holds the value of your request.
There is no (good) way to make data available synchronously in the global scope.
You could make use of the async property and set to FALSE and global property to FALSE which would serve your requirements.
var data;
data= function () {
var tmp = null;
$.ajax({
'async': false,
'type': "POST",
'global': false,
'dataType': 'html',
'url': "fetch_data.php",
'data': { 'userid': "19"},
'success': function (json) {
tmp = json;
}
});
return tmp;
}();
alert(data); //would give you the json data from PHP
Because it is an asynchronous call, not synchronous. The call outside is reading the variable before the Ajax call is made/returned. You need to do all of the work in the callback.
JQuery is using AJAX to load the JSON file, and AJAX is asynchronous.
Because of that what's happening is that the line after the getJSON is getting called first while the JSON file is still being loaded and the callback hasn't been called yet.
That's why event_list is still undefined and doesn't return any data.