Can't get the json value by getjson from google map api
HTML
<html>
<head>
</head>
<body>
<input data-mini="true" data-theme="a" id="search" name="search" placeholder="Search for Restaurants" type="search">
<input data-inline="true" id="submit" onclick="getRestaurants()" type="submit" value="Go">
</body>
</html>
JS
function getRestaurants()
{
var search=$("#search").val();
var prestring="restaurant+in+";
var jsonRList="https://maps.googleapis.com/maps/api/place/textsearch/json?query="+prestring+search+"&key=API_KEY";
var xmlRList="https://maps.googleapis.com/maps/api/place/textsearch/xml?query="+prestring+search+"&key=API_KEY";
alert(jsonRList);//working
//NOT working
$.getJSON(jsonRList, function (data) {
alert(data.results[0].name);//returns nothing
alert("hello2");//returns nothing
});
//working
var data = '{"name": "abc","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json.phoneNumber[0].number);
alert("hello3");//working
//NOT working
$.ajax({
url: 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=kolkata&key=API_KEY',
dataType: 'jsonp',
success: function(data){
alert(data);//returns nothing
alert("ajax");//returns nothing
}
});
alert("hello4");//working
//Not working
$(document).ready(function(){
$("submit").click(function(){
$.getJSON( jsonRList, function( data ) {
alert(data);//returns nothing
alert("hello5");//returns nothing
});
});
});
}
Inside $.getjson or $.ajax not executing anything.
Another approach that is not working
$("button").click(function() {
....
https://jsfiddle.net/sphakrrokr/r9xbctnr/
Two reasons I could identify for you not getting a response from Places API -
1) You are using data type JSONP instead of JSON while the API will return results in JSON format.
2) Even though you wish to use JSONP and not JSON, you did not implement a callback in order to parse results into JSONP.
For normal use case, I would recommend to use JSON over JSONP.
Check these resources for difference between the two:
Relevant question 1
Relevant question 2
Official docs
Related
i'm working with an old codeigniter. i'm calling a onchange function. i want to get data from controller and show it to a input filed which is an array.
view page code:
<select name='feed_id[]' style='width:95px;'onchange="getfeedstock(0,this.value)"><?=$this->mod_feed->get_feeds()?></select>
<span><input type='text' name='stock[]' readonly value='' class='num_txt stock<?=$inc?>' /></span>
javascript:
<script >
function getfeedstock(i,obj){
//alert(obj);
$.ajax({
url:base_url+'feed_sale/get_feed_stock',
type:'post',
data:{
feed_id:feed_id
},
success:function(data){
//alert(data);
//var stock=5;
//$('.stock').val(stock);
},
error:function(error,msg){
alert(error+msg);
}
});
}
</script>
Use Output class of Codeigniter
https://www.codeigniter.com/userguide2/libraries/output.html
it will set page header to JSON type. And pass array using json_encode();
all array of PHP will get in JSON object format in success callback of Ajax
success: function(data) {
alert(data.msg); // showing [Object][object]
//all array visible in console log Ctrl+Shift+I (in chrome)
console.log(data);
}
If this is a re-post of an already existing. I looked a bunch of different issue already posted about this but didn't feel any matched my issue. If there is one please link it.
I'm trying to learn AJAX and have a form that takes two inputs a serverName, and a isLive. As well as a button to add a server to the list. I already made a json file that has two servers in it and when I GET info from it to update the list it lists the server's serverName and isLive fine. When I go to POST information all I get back when the list is updated is undefined.
Using console logs I know that the information is being passed from the form to Object to be sent by AJAX and that it seems to trigger the success function, but when I look there is nothing added to the Json and it says the fields are undefined.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
</head>
<body>
<h1>Server List</h1>
<ul id="servers">
</ul>
<h4>Add a Server</h4>
<p>Server Name: <input type="text" id="serverName"></p>
<p>Offline or Online: <input type="text" id="isLive"></p>
<button id="add-server">Add!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js
$(function() {
var $servers = $('#servers');
var $serverName = $('#serverName');
var $isLive = $('#isLive');
$.ajax({
type : 'GET',
url: 'servers.json',
success: function(servers) {
$.each(servers, function(i, server) {
$servers.append('<li>Server: '+ server.serverName +', Status: '+server.isLive+'<li>');
});
},
error: function() {
alert('Error loading server status!');
}
});
$('#add-server').on('click', function() {
var server = {
serverName: $serverName.val(),
isLive: $isLive.val(),
};
console.log(server);
$.ajax({
type: 'POST',
url: 'servers.json',
data: server,
success: function(newServer) {
$servers.append('<li>Server: '+ newServer.serverName +', Status: '+newServer.isLive+'<li>');
},
error: function(){
alert('error saving server');
}
});
});
});
servers.json
[{"serverName":"vanilla","isLive":"offline"}, {"serverName":"SkyFactory","isLive":"Online"}]
You can't modify a file in the server with JavaScript. Check this may help:
Use JQuery to Modify external JS File
What I want to do:
I want to do a input text field with a jquery autocomplete function which gets the source data from a cross-domain curl request. The result should look similar like this: http://abload.de/img/jquerydblf5.png (So I actually want to show additional infos which I get from the curl Request). The URL to get the source data is http://www.futhead.com/15/players/search/quick/?term= and in the end I add those letters which are currently typed in at my input field (for example "Ronaldo").
At the moment I only tried to perform the searchrequest without showing all infosin the dropdown as shown in the screen above. I only want to see which playernames I actually got back by the curl request. Later I will try to add more information for the dropdown. Maybe you guys can help me as well with this as well (I think its called custom renderItem ??).
This is what I've tried:
<script>
$( "#tags" ).autocomplete({
source: function (request, response) {
$.ajax({
type: 'GET',
url: 'playerscraper.php',
dataType: "json",
data: function () {
return $("#results").val()
},
success: function (data) {
// I have no idea what this response and map is good for
response($.map(data, function (item) {
return {
label: item.label,
id: item.value,
};
}));
},
});
}
});
</script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
My playerscraper.php is performing the curl request and actually returns a array (tested with echo):
$term = $_GET['term'];
$curlRequest = new CurlRequest();
$result = $curlRequest->get('http://www.futhead.com/15/players/search/quick/?term=' . $searchterm);
$players = array();
return json_encode($result);
My problem:
I have no idea how to do the source part for the autocomplete function this way, that I get the right results from the ajax request with my searchterm from the input field. When I type in something in the input field, nothing happens (the function which defines the source is getting called - tested with an alert).
I am trying to pull in book data upon a user form submission from the ISBNdb API. I am using JSON in the url as required. As of now I am using the form to search by books category (see about halfway down page). When I enter a search term, I get 2 errors in the console:
Resource interpreted as Script but transferred with MIME type
text/plain:
"http://isbndb.com/api/v2/json/J6FR9HT6/books?jsoncallback=jQuery1111037271023145876825_1404698815454&q=science&_=1404698815455".
jquery.min.js:4 Uncaught SyntaxError: Unexpected token :
I see the q=science that I am expecting, but what is all the other stuff jQuery seems to be adding? Any help MUCH appreciated!
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('form').submit(function (event) {
event.preventDefault();
var searchTerm = $('#search').val();
// the AJAX part
var isbndbAPI = 'http://isbndb.com/api/v2/json/J6FR9HT6/books?jsoncallback=?';
var bookOptions = {
q: searchTerm
};
function displayBookData(data) {
var bookHTML = '<ul>';
$.each(data.data,function(i,book) {
bookHTML += '<li>';
bookHTML += book.title;
bookHTML += '</li>';
}); // end each
bookHTML += '</ul>';
$('#book-results').html(bookHTML);
}
$.getJSON(isbndbAPI, bookOptions, displayBookData);
}); // end submit
}); // end ready
</script>
</head>
<body>
<form>
<label for="search">Type a search term</label>
<input type="search" name="search" id="search">
<input type="submit" value="Search" id="submit">
</form>
<div id="book-results"></div>
</body>
</html>
UPDATE
It seems to receive the JSON back okay, and I can see the results in the console. Still confused as this is all new to me. Also, I may not be displaying it as HTML correctly either.
The url at original post did not include a parameter required by the api :
error: "'query' or 'q' is a required parameter"
See ISBNdb API -- Version 2
Request URL: http://isbndb.com/api/v2/xml/mykey/books?q=science
Try
$.getJSON("https://query.yahooapis.com/v1/public/yql?q=select"
+"* from json where url='http://isbndb.com/api/v2/json/J6FR9HT6/books?q=science'"
+"&format=json&diagnostics=true&callback=?"
, function(data, textStatus, jqxhr) {
console.log(data.query.results.json.data);
$.each(data.query.results.json.data, function(index, value) {
$("<li>", {"text" : value.title +", "
+ (value.author_data
? (value.author_data.name
? value.author_data.name
: value.author_data.id)
: void(0)) }).appendTo("ul");
});
})
.fail(function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
});
jsfiddle http://jsfiddle.net/guest271314/bZBLf/
The API you mentioned does not support JSONP. As its documentation states, it only supports JSON, YAML, and XML.
Response Formats
The API will serialize it's return data in one of 3 different formats:
Json - /api/v2/json/my-api-key
Yaml - /api/v2/yaml/my-api-key
XML - /api/v2/xml/my-api-key
jQuery tries to treat the returned JSON file as a JS file, but it isn't thus causing the error.
Your server-side either needs to change its content-type to give you JSON, or you need to get the data back and treat it as text, then convert to JSON.
It looks like you are trying to request JSONP though ... not sure if you can/how easy it will be to pull it down as text and then convert it and still get the callback to run.
I already tried several methods getting my xml-script parsed in java, but i can't figure it out!
I have 2 files.
mysql_get.php is returning an XML script if it is called.
post_alert.html is fetching the XML script from mysql_get.php over jQuery $.post(..) as shown below:
function init2() {
var response;
$.post("mysql_get.php", function (data) {
response = data;
alert(response)
});
var xml;
xml = $.parseXML(response);
alert($(response).find("item").each(function () {
$(this).attr("id")
}));
}
After hit a button which call init2(), i get the response message in xml style as i can see by the alert popup.
<?xml version="1.0" encoding="uft-8"?>
<root>
<collection collection="locationPoint">
<item id="1">
<latitude>23.4442</latitude>
<longitude>51.2341</longitude>
</item>
<item id="2">
<latitude>2849.24</latitude>
<longitude>213.132</longitude>
</item>
</collection>
But the alert doesn't popup "1" in addition as I wished for correct parsing.
What am I doing wrong?
Here are a couple of things:
Line 1 of you xml file should read UTF-8 not UFT-8
Line 2 should be deleted, else make sure you have a closing tag, invalid xml
Then here is a little example that I hope helps:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
</head>
<body>
<div id="dc"></div>
</body>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'mysql_get.php',
type: 'post',
dataType: 'xml',
success: function(data) {
$(data).find('item').each(function () {
$('#dc').append($(this).attr('id') + '<br/>')
});
},
error: function(data) {
$('#dc').html('error');
}
});
});
</script>
</html>
The A in AJAX stands for asynchronous. The code after $.post(..) is executed right after $.post is called, regardless of the response state.
You have to move the var xml..-code inside the $.post call.
Also, .each() only loops through the elements, without returning the IDs. Use .map() to create an object consisting of the ids, and .toArray() to get an array representation of it.
function init2() {
$.post("mysql_get.php", function(data) {
var response = data;
var xml = $($.parseXML(response));
alert(response.find("item").map(function () {
return $(this).attr("id")
}).toArray() );
});
}
Take a look at XML manipulation with jQuery