I’m practicing coding jQuery and Ajax and making a plain Google search box, but it won’t work. There’s no console errors and debugging in Chrome doesn’t help much. Here’s the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#button").click(function() {
$.ajax({
url : "http://www.google.com/search",
dataType : "html",
success : function(data) {
$("#show").html(data)
},
fail : function() {
alert("failed lol")
}
})
})
})
</script>
</head>
<body>
<div id="search">
<form name="input" method="get">
Google it: <input type="text" name="googleit" /> <br /> <br /> <input
id="button" type="button" value="let me google that for you" />
</form>
</div>
<div id="show"></div>
</body>
</html>
What’s wrong with this code?
You can’t do a cross-domain call that easily, it’s restricted by Same Origin Policy. Check your network tab, it should state that the Request failed.
Also you didn’t even hand over the value of your input-field. You should append it to the url like this
?q=hello.You need a so called JSONP-call to access other domains.
Take a look at the Google Search API.