I am absolut beginner level of web development. I would like to ask how to handle the json data from that link https://www.maxenergy.com.mm/api/max_price_list. I want to show the Diesel price in my page. But how to select the exact key form json data.
[
{
"Ayeyarwady":[
{
"price":{
"95 Ron Octane":660.00,
"Premium Diesel":620.00,
"Diesel":580.00,
"92 Ron Octane":580.00
},
"address":"Aungsan Road, Yay Kyi Township,Ayeyarwady.",
"station":"Max Energy (Yay Kyi)",
"longitude":null,
"latitude":null,
"telephone":"09977877901, 046-52020"
},
{ },
{ },
{ },
{ },
{ }
]
},
{ },
{ },
{ },
{ },
{ }
]
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<div id="aya"></div>
<script>
$(document).ready(function() {
$.ajax({
url: 'https://www.maxenergy.com.mm/api/max_price_list',
dataType: 'jsonp',
type: 'GET',
}).done(function(data) {
$("#aya").html(data.Ayeyarwady.price.Diesel);
});
});
</script>
</body>
</html>
JSONArray json = new JSONArray(YOUR_RESPONSE);
for(int i=0;i<json.length();i++){
JSONObject dataJsonObject = new JSONObject(json.getJSONObject(i));
//FIRST JSONOBJECT
//NOW FROM THIS GET JSONARRAY Ayeyarwady
//AND MAKE IT FRO LOOP AGAIN AND get price and address like...
}
Hope this helps...
the array displayed in your page is part JSON part array (you can tell by the brackets type - [] is array, {} is JSON.
so you should use data[0].Ayeyarwady[0].price.Diesel (data and Ayeyarwady are arrays of objects with one child)
BUT this particular API isn't really supporting jsonp, and that's why it isn't working for you, if you add an error function callback you'll see that jQuery throws a parsererror on the data received.
you'll have to create a proxy server side request to the API, grab the data, parse as JSON and then get that data locally
Please change dataType like this,
dataType: 'json',
Related
I have a URL which I can open on browser and view the JSON data. The URL looks something like this:
https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJZeH1eyl344kRA3v52Jl3kHo&key=API_KEY_HERE
Now when I try to access this with jQuery AJAX, I fail to get any results, instead I get an error.
My AJAX call looks some like this:
$.ajax({
url: https://maps.googleapis.com/maps/api/place/details/json,
data: {
'placeid': 'ChIJZeH1eyl344kRA3v52Jl3kHo',
'key': 'API_KEY_HERE'
},
dataType: 'json',
success: function(response) {
alert(JSON.stringify(response));
},
error: function(error) {
alert(JSON.stringify(error));
}
});
var API_KEY = api_key;
var placeid = placeid;
var API_URL = `https://maps.googleapis.com/maps/api/place/details/json?placeid=${placeid}&key=${API_KEY}`
$.getJSON(API_URL, {
tags: placeid,
tagmode: "any",
format: "json"
},
function(data) {
alert(data);
});
If I build it up correctly, this should be the way to send the data correctly to the api, using the placeid inside the url string together with the api_key.
Then you use a getJSON instead of json because I assume you want to get the place data? Assuming to what you're doing in the ajax you made.
Maybe explain further what you mean with how to get google maps url with place id? Hope it helps you out :)
I am new to working with Jquery JSON and API's(this being my first Stack question, so please bear with me). So I am trying to figure out a way in which Im hitting a API and it will return data(city name) in JSON which I have to display on my page in list form. But the cities should be updated and the page should display the city names dynamically.
Here is the fiddle link:
Fiddle File
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TEST2</title>
</head>
<body>
<button>Submit</button>
<select id="list"></select>
</body>
</html>
<script type="text/javscript" src="jquery-3.1.0.js"></script>
<script type="text/javscript">
$.ajax({
type: 'GET',
url: 'API HERE',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('list', {
text: element.detail
}));
});
}
});
</script>
JSON FILE
[
{"id":3,"detail":"Mumbai, Maharashtra, India"},
{"id":10,"detail":"Pune,Maharashtra, India"},
{"id":166,"detail":"Bengaluru"}
]
Requesting for your help, thanks in advance for those who contributed
Provided you receive data from API you can do what you want.
//...
success: function (data) {
$.each(data, function(index, element) {
//$('body').append($('list', {//no comment
// text: element.detail
//}));
//add cities to select id="list"
$('<option/>') //create option
.val(element.id) //set its value
.text(element.detail) //set text
.appendTo('#list'); //and append to the list
});//each
}
this is not a JSON object, its an array, are you sure it comes back like this? try to log it then do one of the following:
if it comes as a string write this
$.ajax({
type: 'GET',
url: 'API HERE',
data: { get_param: 'value' },
dataType: 'json',
accepts: "application/json; charset=utf-8"
/* ... */
the accepts tells the server to send back json, hence you can get it as json. if it is still a string, write JSON.parse(data)
if it comes as an array like youve written, then there should be no problem, except that its an array not a json object. json should be an object not an array.
{results: [
{"id":3,"detail":"Mumbai, Maharashtra, India"},
{"id":10,"detail":"Pune,Maharashtra, India"},
{"id":166,"detail":"Bengaluru"}
]}
something like this will make it a json file.
if it comes like this, then you should write: data.results to access the array you need.
You don't need to parse. JSON is JavaScript Object Notation. you can just asign data to variable and use it in your code like
success: function(result) {
var data = result;
data.forEach(function(data){
$('body').append($('list', {
text: element.detail
}));
}
console.log(data);
//in console you can see tyour data
Object {type: "form-focus", element: "#run"}
Can't seem to find what I'm looking for in searches so this might be a duplicate but I haven't found an original yet sooo....
I have a an ajax call:
$.ajax({
url: "/events/instructor/",
type: 'POST',
data: {
instructorID: $(this).attr("id")
},
complete: function (data) {
$("#name").html(data["responseText"]["name"]);
$("#email").html(data["responseText"]["email"]);
$("#photo").html(data["responseText"]["photo"]);
$("#summary").html(data["responseText"]["summary"]);
$("#url").html(data["responseText"]["url"]);
}
});
The data being returned is encoded in JSON by the server (C#).
Obviously, data["responseText"]["fieldName"] isn't doing the trick. I could do splits and whatnot but that would mean that if the format changes, I'd need to make sure that the code above keeps up with the changed shape of the data.
How can I say something as simple as data["responseText']["fieldName"] to get the value out of that key?
i think you need to parse json first. look at the api.jquery.com/jquery.parsejson
// data = '{ "name": "John" }'
var obj = jQuery.parseJSON( data );
console.log( obj.name);
// result will be "John"
P.S. also better use 'succes' instead 'complete', you can read about this here Difference between .success() and .complete()?
success: function(data) {
console.log("response is good", data);
},
error: function (){
console.log("something is went wrong");
}
try using like this:
complete: function (data) {
var data=JSON.parse(data);
$("#name").html(data.responseText.name);
$("#email").html(data.responseText.email);
$("#photo").html(data.responseText.photo);
$("#summary").html(data.responseText.summary);
$("#url").html(data.responseText.url);
}
to get only correct response use success.
I'm trying to query GitHub's search user API by language and location. When I use the command curl https://api.github.com/search/users?q=location:denver+language:php I receive 146 results. However, when I try to use jQuery AJAX, I receive an error.
My JavaScript code:
var url = "https://api.github.com/search/users";
var request = {
q: "location:denver+language:php",
sort: "repositories",
order: "desc"
};
var result = $.ajax({
url: url,
data: request,
dataType: 'jsonp',
type: 'GET'
})
.done(function() {
alert(JSON.stringify(result));
})
.fail(function() {
alert('failed');
});
What alert(JSON.stringify(result)); gives:
{
"readyState":4,
"responseJSON":{
"meta":{
"X-RateLimit-Limit":"10",
"X-RateLimit-Remaining":"9",
"X-RateLimit-Reset":"1397393691",
"X-GitHub-Media-Type":"github.beta",
"status":422
},
"data":{
"message":"Validation Failed",
"documentation_url":"https://developer.github.com/v3/search/",
"errors":[
{
"message":"None of the search qualifiers apply to this search type.",
"resource":"Search",
"field":"q",
"code":"invalid"
}
]
}
},
"status":200,
"statusText":"success"
}
When I only use one qualifier on q it works fine and the result.responseJSON.data object contains the information that is normally provided by cURL.
use a space character instead of a plus(+). Change your query to this:
q: "location:denver language:php",
and it will work as expected, because jquery will convert this space character to a plus.
I have a javascript object that looks somthing like this:
var obj = {
"name": "username",
"userid": "9999",
"object1": {
"subObject1": {
"subArray1": [],
"subArray2": []
},
"subObject2": {
"subArray3": [],
"subArray4": []
}
},
"object2": {
"subObject3": {
"subArray5": [],
"subArray6": []
}
},
"array1": [],
"array2": []
};
I have tried to use a jQuery ajax call like this:
$.ajax({
url: "test.php",
type: "POST",
dataType: "text",
processData: false,
data: obj,
success: function(data, status) {
alert("Sucsess");
}
});
The problem is that PHP doesn't receive anything. The $_POST variable is empty. I'm not sure what I'm doing wrong.
Thanks
First, include JSON2.js (Link at bottom of that page) on the page, then change your call to this:
$.post(
"test.php",
data: JSON.stringify( obj ),
function(data, status) {
alert("Sucsess");
});
Try out jQuery 1.4.1 the $.param function was completely rewritten to support things like this.
Why not send it by using something like the json2 library to serialize the whole object as JSON, then send that via a single parameter? I don't know PHP but I would be stunned if there weren't dozens of alternative JSON parsers available.
I don't believe it is possible to send a data object like that.
If you wanted to do something like that you would have to serialize it before you send the data and then unserialize at the server. HTTP has it's limits.