Google Maps Geocoding AJAX using a variable as the URL - javascript

$('form').submit(function(event){
event.preventDefault();
var userData = "https://maps.googleapis.com/maps/api/geocode/json?address="+$('input#city').val()+"&key=MY_API_KEY";
console.log(userData);
$.ajax({
type: "GET",
url : userData,
success: function(data){
$.each(data['results'][0]['address_components'], function(key, value) {
if(value["types"][0] == "postal_code"){
$('.alert-success').fadeIn(2000).html('Post/ZIP Code: '+value["long_name"]);
}
});
}
})
});
So, I have this code, above, which is currently returning no error nor any results as desired.
It works fine as long as I put the entire 'https://maps.googleapis.com/maps/api/geocode/json?address=""&key=""' string in the url: "", section of the ajax, but when trying to pass my variable in it doesn't want to do anything.
From what I've found variables should pass through easily enough into the ajax call so I'm kind of lost.

Your condition if (value["types"][0] == "postal_code") { is not working.
Check the returned data object via console.log.
Here is a working fiddle without it:
https://jsfiddle.net/1t82y0xa/

You need to URL encode the string returned by $('input#city').val()
related question: JavaScript URL encode
Note: Not all geocoder records return members of the response array with a postal_code type (like for example a query for "New York, NY", it has multiple zip codes).
var userData = "https://maps.googleapis.com/maps/api/geocode/json?address="
+ encodeURIComponent($('input#city').val())
+ "&key=MY_API_KEY";
console.log(userData);
$.ajax({
type: "GET",
url: userData,
success: function(data) {
console.log(data);
$.each(data['results'][0]['address_components'], function(key, value) {
if (value["types"][0] == "postal_code") {
$('.alert-success').fadeIn(2000).html('Post/ZIP Code: ' + value["long_name"]);
}
});
}
});

Related

javascript, array of string as JSON

I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.

Trouble working sync with async javascript

I'm working in my own rss reader using JS, JQuery and PHP for serving the data as JSON. What I'm doing basically is making async calls to my server to get JSONs with the posts, then on 'success' I parse them using a '$.each' and with JQuery load the content in the DOM.
All of this operations were made async, but now I need to call them in a certain order, and when everithin is done THEN calling a function to process the data.
To give you some background on my task, what I'm doing is a query over a small list of RSS sources to get just the very latest post. With them I concat a string and this string is passed to a text-to-speech service.
I've managed to make it work using an arbitrary setTimeout value of 10 seconds, but my goal is to call the function when all the sources have been processed.
This is a basic version of my parser:
function urgent_posts(url) {
$.ajax({
//the location of my server
url: 'myPostServer.php?url=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
//do this for each entry in the feed
$.each(data.feed.entries, function(key, value) {
//validate the date to get just the latest post
if (is_urgent(value.publishedDate)) {
//if condition is met save the title
save_urgent_post_title(value.title);
}
});
}
});
}
What I did to 'make it work' was the following:
$('#test_button').on('click',function(){
urgent_posts(source_1);
urgent_posts(source_2);
urgent_posts(source_3);
//and so on...
urgent_posts(source_n);
setTimeout(function(){
text_to_speech(get_urgent_post_string);
},10000);
});
I tried with no result to make use of the deferred object y JQuery like this:
function urgent_posts(url) {
var deferred = $.Deferred();
$.ajax({
//the location of my server
url: 'myPostServer.php?url=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
//do this for each entry in the feed
$.each(data.feed.entries, function(key, value) {
//validate the date to get just the latest post
if (is_urgent(value.publishedDate)) {
//if condition is met save the title
save_urgent_post_title(value.title);
}
});
}
});
return deferred.promise();
}
And chaining everything together:
$('#test_button').on('click',function(){
urgent_posts(source_1)
.then(urgent_posts(source_2))
.then(urgent_posts(source_3))
.then(function(){
text_to_speech(get_urgent_post_string);
});
});
I'd apreciatte your comments and suggestions.
First, your deferred object is never resolved. You have to add the deferred.resolve() somewhere. Just after the $.each loop looks like a nice place.
Second, $.ajax already returns a promise. So you can just write this :
return $.ajax({
//the location of my server
url: 'myPostServer.php?url=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
//do this for each entry in the feed
$.each(data.feed.entries, function(key, value) {
//validate the date to get just the latest post
if (is_urgent(value.publishedDate)) {
//if condition is met save the title
save_urgent_post_title(value.title);
}
});
}
});
I manage to solve the problem using this article: link
The refactored code looks like this now:
function urgent_posts_feed_1(callback) {
return $.ajax({
//the location of my server
url: 'myPostServer.php?url=' + encodeURIComponent(feed_1),
dataType: 'json',
success: function(data) {
//do this for each entry in the feed
$.each(data.feed.entries, function(key, value) {
//validate the date to get just the latest post
if (is_urgent(value.publishedDate)) {
//if condition is met save the title
save_urgent_post_title(value.title);
}
});
}
});
}
I repeat myself (I know it's not cool to do so) and write the following functions manually setting the url:
urgent_posts_feed_2
urgent_posts_feed_3
urgent_posts_feed_4
...
urgent_posts_feed_n
And finally...
urgent_post_feed_1()
.then(urgent_post_feed_2)
.then(urgent_post_feed_3)
//...
.then(urgent_post_feed_n)
.then(function(){
text_to_speech(get_urgent_post_string);
});
This way it works like a charm. Now I have to figure out how to pass parameters to the function and not interfer with the callback.

Display search results from API

Hello there I'm trying to create an app to search for recipes. I've tried using the Yummly API and BigOven api, but I can't get either to work.
here is the code i have for bigOven. I can't get any search results to appear in the "results".
$(function() {
$('#searchform').submit(function() {
var searchterms = $("#searchterms").val();
// call our search twitter function
getResultsFromYouTube(searchterms);
return false;
});
});
function getResultsFromYouTube (searchterms) {
var apiKey = "dvxveCJB1QugC806d29k1cE6x23Nt64O";
var titleKeyword = "lasagna";
var url = "http://api.bigoven.com/recipes?pg=1&rpp=25&title_kw="+ searchterms + "&api_key="+apiKey;
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
alert('success');
console.log(data);
$("#results").html(data);
}
});
}
Can anyone give me instructions on how to do this?? Thank you very much.
The API is returning JSON data, not HTML. I checked the API docs, and JSONP isn't necessary.
However, when you run this code:
$('#results').html(data);
Your code is going to just put the JSON into your HTML, and that isn't going to get displayed properly. You didn't say whether console.log(data) outputs the data correctly, but I'll assume it is.
So, you'll need to transform your JSON into HTML. You can do that programmatically, or you can use a templating language. There are a number of options, including underscore, jquery, mustache and handlebars.
I recommend handlebars, but it's not a straightforward bit of code to add (the main difficulty will be loading your template, or including it in your build).
http://handlebarsjs.com/
It would depend on you which key and values you have to show to your user's and in which manner... For ex. there is even an image link, you could either show that image to your user's or could just show them the image link...
Simple <p> structure of all the key's with there value's
jQuery
$.each(data.Results, function (key, value) {
$.each(value, function (key, value) {
$("#result").append('<p>Key:-' + key + ' Value:-' + value + '</p>');
});
$("#result").append('<hr/>');
});
Your ajax is working, you just need to parse the results. To get you started:
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
// Parse the data:
var resultsString = "";
for (var i in data.Results){
console.log( data.Results[i] );
resultsString+= "<div>"+data.Results[i].Title+ " ("+data.Results[i].Cuisine+")</div>";
}
$("#results").html(resultsString);
// If you want to see the raw JSON displayed on the webpage, use this instead:
//$("#results").html( JSON.stringify(data) );
}
});
I had created a little recursive function that iterates through JSON and spits out all of the values (I subbed my output for yours in the else condition) -
function propertyTest(currentObject, key) {
for (var property in currentObject) {
if (typeof currentObject[property] === "object") {
propertyTest(currentObject[property], property);
} else {
$('#results').append(property + ' -- ' + currentObject[property] + '<br />');
}
}
}
Then I called it within your AJAX success -
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
console.log(data);
propertyTest(data); // called the function
}
});
It spits out all of the data in the JSON as seen here - http://jsfiddle.net/jayblanchard/2E9jb/3/

How do I alert my json results?

I get these results via php to alert in my ajax alert
[{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}]
How do I do $('#divid').html(message); ?
I want only specified value from the json array.
Here is the code
function showMessage(id){
var dataString = 'id=' + id;
$.ajax(
{
type: "POST",
url: "/inbox/instshow",
data: dataString,
success: function(results)
{
if(results == "error")
{
alert('An error occurred, please try again later. Email us with the issue if it persists.');
}
if(results != "notallowed" && results != "error" && results != "login")
{
alert(results);
alert(results[0].message);
}
}
});
}
data = [{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}]
$('#divid').html(data[0].message);
DEMO
You might have to parse a JSON string using jQuery.parseJSON.
// results is your JSON string from the request
data = jQuery.parseJSON(results);
$('#divid').html(data[0].message);
If you ajax you should include:
dataType: 'json'
code
$.ajax(
{
type: "POST",
url: "/inbox/instshow",
data: dataString,
dataType: 'json', // here
success: function(results) {
}
.........
Including this jQuery will parse the returned data as JSON for you automatically (don't need any manual parsing effort) and you'll get your result that you're trying now.
use JSON.stringify() function
var data=[{"message_id":"3","box":"0","from_id":"3","to_id":"1","title":"Hello sir!","message":"how are you?","sender_ip":"","date_sent":"","status":"0"}] ;
alert(JSON.stringify(data));
Here's your data broken down by levels:
[
{
"message_id":"3",
"box":"0",
"from_id":"3",
"to_id":"1",
"title":"Hello sir!",
"message":"how are you?",
"sender_ip":"",
"date_sent":"",
"status":"0"
}
]
You would use data[0].message because the first level indicates an array, hence the need of [0] to reference the first and only element, and the second is an object, which properties can be accessed by the object.member syntax.
for debugging purposes
console.log(data, data.message, "whatever")
You need to open firebug or safari's inspector and look in the "console"

Passing an array to a web method in Javascript

I am currently trying to pass an array that I have created in Javascript to my webmethod in my aspx.cs.
Heres what I have:
JAVASCRIPT
function callServer(requestMethod, clientRequest) {
var pageMethod = "Default.aspx/" + requestMethod;
$.ajax({
url: pageMethod, // Current Page, Method
data: JSON.stringify({ request: clientRequest }), // parameter map as JSON
type: "POST", // data has to be POSTed
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 60000, // AJAX timeout
success: function (result) {
ajaxCallback(result.d);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
}
function myButtonCalls()
{
var values=[];
values[0] = "Hello";
values[1] = "goodbye";
callServer("myMethod", values);
}
ASPX.CS
[WebMethod]
public static string myMethod(string[] request)
{
return "This is test";
}
It fails before it even gets to my web method. I know this code works for regualr strings but The ajax code that uses JSON doesnt see to want to work with arrays.
Any ideas of what i need to change?
Thanks
In the aspx.cs, I needed to accept with type list not array. Thanks for the comments!

Categories

Resources