getting place name from Json using google API - java

When I run this code I get a blank screen and nothing gets displayed.What changes I have to make in order to get this right and where am I going wrong?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> </script>
<script>
$(document).ready(function() {
$.getJSON("https://maps.googleapis.com/maps/api/place/search/json?location=-33.8670522,151.1957362&radius=500&types=food&name=harbour&sensor=false&key=AIzaSyC1BIAzM34uk6SLY40s-nmXMivPJDfWgTc",
function(data, textStatus){
alert(data);
$.each(data.results,function(i, name) {;
$("#placenames").append(i+':'+name.vicinity+'<br/>');
});
});
});
</script>
</head>
<body>
<div id="placenames"></div>
</body>
</html>

Have you tried using Google Maps Javascript API? It does all the JSONP stuff for you.
Here is a demo with your coordinates: http://jsfiddle.net/ThinkingStiff/CjfcX/
Script:
var places = new google.maps.places.PlacesService( document.createElement( 'div' ) ),
searchRequest = {
name: 'harbour',
location: new google.maps.LatLng( -33.8670522, 151.1957362 ),
radius: 500,
types: ['food']
};
places.search( searchRequest, function ( results, status ) {
var html = '';
for ( var index = 0; index < results.length; index++ ) {
html +=
'<li '
+ 'data-location-id="' + results[index].id + '" '
+ 'data-address="' + results[index].vicinity + '" '
+ 'data-latitude="' + results[index].geometry.location.lat() + '" '
+ 'data-longitude="' + results[index].geometry.location.lng() + '" '
+ 'data-name="' + results[index].name + '">'
+ '<div>' + results[index].name + '</div>'
+ '<div>' + results[index].vicinity + '</div>'
+ '</li>';
};
document.getElementById( 'results' ).innerHTML = html;
} );
HTML:
<script src="http://maps.googleapis.com/maps/api/js?libraries=places,geometry&sensor=true"></script>
<ul id="results"></ul>
Output:

Google API does not support the callback/JSONP from a jQuery get/getJSON at this time
To load async, you need to do something like this:
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
http://code.google.com/apis/maps/documentation/javascript/basics.html#Async

You have to add this querystring so that it is parsed as jsonp:
&callback=?
See this blog post for more information:
http://www.mattcashatt.com/post/index/Obtaining-and-Parsing-Open-Social-Graph-Data-with-JSONP-and-jQuery

Related

How to pass dynamically added textbox to spring MVC controller java

$("#addButton").click(function () {
if(counter > 3){
alert("Only 3 textboxes allowed");
return false;
}
var selectfield = $('#selectcolumnlist option:selected').val();
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'TextBoxDiv');
newTextBoxDiv.after().html('<input type="text" name="textbox_' + selectfield + '" class="form-control" id="textbox_'+selectfield+'" placeholder="' + selectfield + '" value="" style="width: 400px;"/><input type="button" value="Remove Field" class="remove_this" id="removeid" accessKey="'+selectfield+'"/>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
$('#selectcolumnlist option:selected').remove();
counter++;
});
$("#TextBoxesGroup").on('click', '#removeid', (function() {
var a = $(this).attr('accessKey');
alert(a);
$(this).parent('div').remove();
$('#selectcolumnlist').append(new Option(a,a));
counter--;
}));
Above code is adding a textbox based on the dropdown select option. It can add a maximum of 3 textboxes.
How do I pass this textbox value to spring MVC controller.
It appears that you are using JQuery to build the UI. Assuming that you have a Spring MVC endpoint exposed at POST http://localhost:8080/api/boxes you can use jQuery.ajax() method:
$.ajax({
method: "POST",
url: "http://localhost:8080/api/boxes",
data: { textbox: "value" }
})
.done(function(msg) {
alert("Saved: " + msg);
});

AJAX call getting failed when I send duplicate parameter

I'm facing quite funny problem, the problem is--
In my application there is a functionality to add products into the shopping-cart, I've implemented this functionality using AJAX. When I add different items (e.g. Item-1, Item-2,..., Item-n) it works fine, but when I add same item again (e.g. Item-1, Item-1 OR Item-1, Item-2,..., Item-n, Item-1) it gets failed
following is my AJAX Code--
var xmlHttp;
//FUNCTION TO CREATE BROWSER COMPATIBLE OBJECT.
function createBrowserObject()
{
if (typeof XMLHttpRequest != "undefined") //Object for Netscape 5+, Firefox, Opera, Safari,and Internet Explorer 7
{
//alert("Obj created");
xmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) //Version for Internet Explorer 5 and 6.
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp == null) //Fails on older and nonstandard browsers
{
alert("Browser does not support XMLHTTP Request");
}
}
function addToCartChange()
{
if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") //Check whether Server response came back with no errors.
{
document.getElementById("cart_div").innerHTML = xmlHttp.responseText;
}
}
function addToCart(titleId)
{
var lastIndex=cartID.substring(parseInt(cartID.lastIndexOf("_"))+1);
var titleId="product_title_"+lastIndex;
var priceId="product_price_"+lastIndex;
var productTitle=document.getElementById(titleId).innerHTML;
var productPrice=document.getElementById(priceId).innerHTML;
productPrice=productPrice.substring(parseInt(productPrice.lastIndexOf(";"))+1);
createBrowserObject();//CREATE BROWSER COMPATIBLE OBJECT.//
var url = "../AddToCartServlet"; // URL of server-side resource.//CALL TO THE SERVLET//
url += "?productTitle=" + productTitle + "&productPrice=" + productPrice;
xmlHttp.onreadystatechange =addToCartChange; //ASSIGN RESPONSE HANDLER FUNCTION NAME TO ONREADYSTATECHANGE//.
xmlHttp.open("GET", url, true); //INITIATE GET or POST REQUEST. (Here GET)
xmlHttp.send(null); // SEND DATA. (Always null in case of GET.)
}
My AddToCartServlet code is--
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
System.out.println("inside AddToCartServlet ");
String strProductTitle=request.getParameter("productTitle");// TO STORE THE VALUE IN productTitle VARIABLE.//
String strProductPrice=request.getParameter("productPrice");// TO STORE THE VALUE IN productPrice VARIABLE.//
AuthenticateServlet.strListItemName.add(strProductTitle);
AuthenticateServlet.strListItemPrice.add(strProductPrice);
String strBuffur="<table width='100%' border='0' cellspacing='0' cellpadding='0' class='cart_table'>";
float floatTotal=0;
for(int i=0; i < AuthenticateServlet.strListItemName.size(); i++)
{
System.out.println("inside loop strListItemName("+i+")= "+AuthenticateServlet.strListItemName.get(i));
strBuffur=strBuffur + "<tr id='item_"+i+"'>" + "<td width='58%' align='left' valign='middle'><strong><span class='prod_name'>"+AuthenticateServlet.strListItemName.get(i)+"</span></strong></td>"
+ "<td width='19%' align='center' valign='middle'>"
+ "<form id='form1' name='form1' method='post' action=''><label>"
+ "<input type='text' value='1' name='textfield' id='itemQty_"+i+"' class='cart_input' />"
+ "</label></form></td>"
+ "<td width='23%' align='left' valign='middle'><strong>Rs. "+AuthenticateServlet.strListItemPrice.get(i)+"</strong></td></tr>";
floatTotal=floatTotal+Float.parseFloat(AuthenticateServlet.strListItemPrice.get(i));
}
// System.out.println("Exit for.....");
strBuffur=strBuffur + "<tr class='total_td'>"
+ "<td colspan='2' align='right' valign='middle'><strong>Total:</strong></td>"
+ "<td align='left' valign='middle'><strong>Rs. "+floatTotal+"</strong></td></tr>"
+ "<tr> <td colspan='3' align='center' valign='middle'> <input name='' type='button' value='Check Out' class='add_cart' onclick='gotoCheckOut()'/></td></tr>"
+ "</table>";
response.getWriter().println(strBuffur);
}
In short, call to AddToCartServlet gets failed when I add Same item again. Please help.. Thanks..!
If the Collection You are using for adding item name ie AuthenticateServlet.strListItemName is a Set then this can be a reason for failure

java script unable to find the element

here is my issue:
when i say getelementbyid("table1") it says"Uncaught TypeError: Cannot set property 'innerHTML' of null"
i am rendering a dynamic table via java script asshown below:
function mainProcessing()
{
<% ProductController pc=new ProductController();%>
var val = <%=pc.doTask()%>
var jobj=JSON.stringify(val);
document.write(jobj);
alert(jobj);
var obj=JSON.parse(jobj);
alert("jobj");
alert(obj.toString());
var object = eval("(" + jobj+ ")");
alert("this part is done");
return object;
}
function drawtable()
{
var JSONObj=mainProcessing();
var tablecontents = "";
for (var i = 0; i < 5; i ++)
{
tablecontents += "<tr>";
tablecontents += "<td>" + i + "</td>";
tablecontents += "<td>" + i * 100 + "</td>";
tablecontents += "<td>" + i * 1000 + "</td>";
tablecontents += "</tr>";
}
document.write(JSONObj.toString());
alert("just outside nested loop");
document.getElementById("table1").innerHTML = tablecontents;
}
for testing i have inserted randome values in the table.
and that html part goes like this:
<title>Indian Divine !!!</title>
</head>
<body onload="drawtable()">
<center>
<h1>my name is jobj</h1>
<table id="table1">
</table>
</center>
</body>
</html>
the browser user is Chrome.
IDE Eclips Juno
You can not use document.write after the page load. It replaces the content. If you are trying to see what is in it, use console.log(jobj);
Second, if you plan on using this code with IE, you can't set the tables innerHTML.
Third, do not use eval() to convert JSON. Use JSON.parse()
document.write(mayur) replaces the whole document (including the table) with the value of mayur, because you are calling it after the document was loaded. At the moment you are trying to access the element with ID table1, it does not exist anymore.
Solution: Don't use document.write.
More info: MDN - document.wite

Passing a Java string to Javascript

I am trying to load a table with data by initializing a Javascript variable with a string in JSON format. If I declare:
<script type="text/javascript">
var data = new String("{totalCount: '1', identifier: 'EntityID', items: [{'EntityID':'1','Country':'United States','Region':'','State':'California','County':'Santa Clara','City':'San Jose','ZipCode':'95134'}]}");
var d3 = eval('(' + data + ')');
<span dojoType="dojo.data.ItemFileWriteStore" jsId="dataStore" data=d3></span>
</script>
then my table will correctly load the row.
I have tried initializing a Java string before my script and then passing that object into a Javascript variable like so:
<%
String d = "{totalCount: '1', identifier: 'EntityID', items: [{'EntityID':'1','Country':'United States','Region':'','State':'California','County':'Santa Clara','City':'San Jose','ZipCode':'95134'}]}";
%>
<script type="text/javascript">
var data = new String(<%=d%>);
// var data = new String(d) // tried this as well
var d3 = eval('(' + data + ')');
<span dojoType="dojo.data.ItemFileWriteStore" jsId="dataStore" data=d3></span>
</script>
My table does not recognize this and is unable to load the row when I attempt to pass it this way. How can I properly pass a Java string to Javascript so that my table will be able to load the data?
Try with quotes around.
var data = new String("<%= d %>");

Why doesn't my script accept characters?

In my SQL the echo $row['ans'] are type varchar(11): JAN,FEB,MAR,APR. I do know now why it won't be displayed out, but when I change JAN,FEB,MAR,APR into numbers it works. Please impart you knowledge and understanding to me. Thanks!
choice box
var months = [<?php echo '"'.implode('","',explode(",",$rows['ans'])).'"'; ?> ];
months.sort( function() { return Math.random() - .5 } );
for ( var i=0; i<4; i++ ) {
$('<div>' + months[i] + '</div>').data( 'months', i ).appendTo( '#monthPile' ).draggable( {
//containment: '#content',
stack: '#monthPile div',
cursor: 'move',
revert: true
} );
}
Create the slots
var slot = [<?php echo '"'.implode('","',explode(",",$rows['ans'])).'"'; ?> ];
for ( var i=0; i<=3; i++ ) {
$('<div>' + slot[i] + '</div>').data( 'months', i ).appendTo( '#monthSlots' ).droppable( {
accept: '#monthPile div',
hoverClass: 'hovered',
drop: handleCardDrop
} );
}
}
When injecting strings into javascript you need to put "" around those characters to tell that its a string. Your numbers work because with out the "" javascript interprets those characters as numbers. Try using the php implode function to add double quotes around your strings in the array (this is assuming $row['ans'] holds an array)
Update working example:
<?php
$rows = array(
"ans" => "JAN,FEB,MAR"
);
?>
<html>
<body>
<script type="text/javascript">
var test = [<?php echo '"'. implode('","',explode(",",$rows['ans'])) . '"'; ?>];
document.write(test.toString());
</script>
</body>
</html>

Categories

Resources