How to get Google maps URL with a 'placeid' with AJAX? - javascript

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 :)

Related

Can Mockjax handle single IDs Api from Json file

I'm using Mockjax for the first time to mock a Restful API which will return a series of data given an id. Right now i have a json file that has several Items, and i would like to have a function inside Mockjax (or where necessary) to return only the queried ID. how can I achieve this?
current code :
$.mockjax({
url: "/Api/Cases/{caseId}",
proxy: "/mocks/cases nuevo.json",
dataType: 'json',
responseTime: [500, 800]
});
$.ajax({
type: 'GET',
url: '/Api/Cases/',
data: {caseId: taskId},
success: function(data){
//use the returned
console.log(data);
}
});
current error:
GET http://localhost:8080/Api/Cases/?caseId=100 404 (Not Found)
Great question... yes, you can do this. But you'll have to write the functionality yourself using the response callback function and then making a "real" Ajax request for the file (instead of using the proxy option). Below I just make another $.ajax() call and since I have no mock handler setup for that endpoint, Mockjax lets it go through.
Note that setting up URL params is a little different than you suggest, here is what the mock setup looks like:
$.mockjax({
url: /\/Api\/Cases\/(\d+)/, // notice the regex here to allow for any ID
urlParams: ['caseID'], // This defines the first matching group as "caseID"
responseTime: [500, 800],
response: function(settings, mockDone) {
// hold onto the mock response object
var respObj = this;
// get the mock data file
$.ajax({
url: 'mocks/test-data.json',
success: function(data) {
respObj.status = 200;
// We can now use "caseID" off of the mock settings.urlParams object
respObj.responseText = data[settings.urlParams.caseID];
mockDone();
},
error: function() {
respObj.status = 500;
respObj.responseText = 'Error retrieving mock data';
mockDone();
}
});
}
});
There is one other problem with your code however, your Ajax call does not add the ID to the URL, it adds it to the query string. If you want to use that API endpoint you'll need to change your source code $.ajax() call as well. Here is the new Ajax call:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId, // this will add the ID to the URL
// data: {caseId: taskId}, // this adds the data to the query string
success: function(data){
//use the returned
console.log(data);
}
});
Note that this presumes the mock data is something like:
{
"13": { "name": "Jordan", "level": 21, "id": 13 },
"27": { "name": "Random Guy", "level": 20, "id": 27 }
}
What I have ended up doing, is: I have left the $.mockjax function untouched, and i have manipulated the data inside the ajax request, using jquery's $.grep function as follows:
$.ajax({
type: 'GET',
url: '/Api/Cases/' + taskId,
success: function(data){
//note you have to parse the data as it is received as string
data = JSON.parse(data);
var result = $.grep(data, function(e){ return e.caseId == taskId; });
//since i'm expecting only one result, i pull out the result on the 0 index position
requestedData = result[0];
}
});
The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test see Jquery API, And since our test is that the caseId attribute of the element equals to the taksId variable sent, it will return all the elements that match the given Id, in this case, only one, this is why I've taken only the result on the 0 index position requestedData = result[0];
**Note: **
A more suited solution would be a mixture between what i've done and #jakerella 's answer, since their method implements the find element method inside the mockjacx function, and my function presumes a usual JSON response:
[{"caseId": 30,"name": "Michael"},{"caseId": 31,"name": "Sara"}]

Correct path structure to open JSON object using AJAX

I'm trying to create a "mock API" module in JS, so I want to request data from a source (products.json) via a url like myapi.com/get/products. It doesn't have to be a legitimate API.
I have this working using an example JSON object from http://www.jsontest.com - but I'm not sure how to do this with my own external data, products.json
My function:
var displayProductList = (function() {
var productList = {
init: function(uri) {
this.getData(uri);
},
getData: function(uri) {
$.ajax({
context: this,
dataType: 'json',
url: uri,
success: this.runOutput
});
},
runOutput: function(data) {
...
}
}
productList.init('http://echo.jsontest.com/key/value/one/two');
})();
This works OK (I can't run it from JSFiddle as it's not https, but it should work): https://jsfiddle.net/xou1k8y8/1/
So my question is, how would I replace the URL in my code with the path to my directory get/products.json and be able to access the data therein?
For example:
productList.init('localhost/my-project/get/products.json');
Doing the above doesn't work. I've also tried adding /products so I can access the products JSON data below.
My JSON looks like this:
{"products":[
{
"id":"0001",
"title":"The Jungle Book",
"price":"13.60",
"currency":"GBP",
"isbn":"978-0062389503",
"stock":{
"in-stock":"yes",
"stock-quantity":"98"
}
}
};
Your localhost URL is not correct. You need to put // before the hostname in a URL, otherwise it's treated as a directory name.
productList.init('//localhost/my-project/get/products.json');
Note that because of the AJAX same-domain restriction, you can only do this when you loaded the HTML file from http://localhost.
Simply switch the URL for your file path:
getData: function(uri) {
$.ajax({
context: this,
dataType: 'json',
url: 'get/products.json',
success: this.runOutput
});
},
Simple as that c:

Ajax post not received by php

I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;

Unable to get value from json object

I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id

GitHub API results different between cURL and jQuery AJAX

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.

Categories

Resources