To display json on web browser - javascript

We want to display json of Google search results on browser called from servlet using Google API. The handleSearchResult is not displaying the responseText on browser.
Also the servlet is not mapping the querywords from the text box of html to Google API search url(servlet). Thanks
home.html
<html>
<head>
<script type="text/javascript">
var request;
function handleSearchResult(){
alert("hanldeRes");
//query.text = resp.items.name;
alert(request.responseText);
//var resp = eval('('+responseText+')');
//alert(resp.items.title);
}
function createHttpRequest()
{
alert("insideCreateRequest");
if(typeof XMLHttpRequest != "undefined") {
request = new XMLHttpRequest();
}
else if(window.ActiveXObject) {
request = new ActiveXObject("Msxml2.XMLHTTP");
if(!request) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if(request) {
request.onreadystatechange = handleSearchResult();
request.open("GET","http://localhost:8080/WebSearchOptimization/SearchService",true);
request.send(null);
}
else {
alert("error on Page createHttpRequest");
}
return false;
}
function home_onclick()
{
alert("passingRequest");
createHttpRequest();
}
</script>
</head>
<body>
<br><br>
<form method="get" name="form">
<input type="text" id="query" name="query">
<input type="button" value="Search" id="search" onclick="home_onclick()">
<div></div>
</form>
</body>
</html>

I have made some modification on your code.Hope this will help.
function handleSearchResult(){
if (request.readyState==4 && request.status==200)
{
alert(request.responseText);
}
}
function createHttpRequest()
{
//....
if(request) {
request.onreadystatechange = handleSearchResult;
var q = encodeURI( document.getElementById("query").value );
request.open("GET","http://localhost:8080/WebSearchOptimization/SearchService?"+q,true);
request.send(null);
}
//.....
}

Related

AJAX logic not working

I am new to AJAX and learning it. I am searching a food item in my HTML textbox and trying to communicate with the server to know if the item is available. The respective status of the item should be shown in the div tag below the textbox but it is not showing.
I haven't studied jQuery yet and would like to know the below things:
How to get the response from the server in plaintext using AJAX and JavaScript, and display it in the div tag below the textbox (advise the changes to be made in the code).
What change should I make in JavaScript code to send the AJAX request in POST method (I know about the changes in PHP code)?
//index.html
<head>
<script type="text/javascript" src="food.js">
</script>
</head>
<body>
<h3>The Cheff's Place</h3>
Enter the food you want to order
<input type="text" id="userInput" name="input" onkeypress="sendInfo()"></input>
<div id="underInput"></div>
</body>
</html>
//food.js
var request;
function sendInfo() {
var v = document.getElementById("userInput").value;
var url = "index.php?food=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.readyState == 0 || request.readyState == 4) {
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send(null);
} catch (e) {
alert("Unable to connect to server");
}
}
}
function getInfo() {
if (request.readyState == 4) {
if (request.status == 200) {
var val = request.responseText;
document.getElementById('underInput').innerHTML = val;
}
}
}
//index.php
<?php
header('Content-Type: text/plain');
$food = $_GET['food'];
$foodArray = array("paneer", "butter", "chicken", "tandoori", "dal");
if (in_array($food, $foodArray))
{
echo "We do have " .$food;
}
elseif($food == "")
{
echo "Kindly enter some food";
}
else
{
echo "We do not sell " .$food;
}
?>
I ran your code. It's working fine. Just replace onkeypress with onkeyup.
<input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input>
Using JQuery (Assuming you have included jquery file or cdn) :
Include the following snippet in script tag at the end of the body.
$("#userInput").keyup(function(){
$.get("index.php", { food: $("#userInput").val() })
.done(function(data) {
$("#underInput").html(data)
})
});

soapRequest is not defined

When I click on the button I get a soapRequest is not defined error.
How can I fix this error?
My code:
<head>
<script type="text/javascript">
var soapRequest = function () {
var str = //the soap request code
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, false);
} else if (typeof XDomainRequest != "undefined") {
alert xhr = new XDomainRequest();
xhr.open(method, url);
} else {
console.log("CORS not supported");
alert("CORS not supported");
xhr = null;
}
return xhr;
} //end of function createCORSRequest//
//calling the xhr
var xhr = createCORSRequest("POST",
"https://thelocalserver/therequest?wsdl");
if (!xhr) {
console.log("XHR issue");
return;
}
xhr.onload = function () {
var results = xhr.responseText;
console.log(results);
} //end of function onload
xhr.setRequestHeader('Content-Type', 'text/xml');
xhr.send(str);
} //end of function soapRequest//
</script>
</head>
<body>
<form name="Demo" action="" method="post">
<div>
<input type="button" id="API" value="Soap" onClick="soapRequest" />
</div>
</form>
</body>
<html>
Try the following:
Javascript:
var soapRequest = function (){
//the soap request code
var createCORSRequest = function (method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, false);
} else if (typeof XDomainRequest != "undefined") {
var xhr = new XDomainRequest();
xhr.open(method, url);
} else {
console.log("CORS not supported");
alert("CORS not supported");
xhr = null;
}
return xhr;
}//end of function createCORSRequest//
//calling the xhr
var xhr = createCORSRequest("POST", "https://thelocalserver/therequest?wsdl");
if (!xhr){
console.log("XHR issue");
return;
}
xhr.onload = function (){
var results = xhr.responseText;
console.log(results);
}//end of function onload
xhr.setRequestHeader('Content-Type', 'text/xml');
xhr.send(str);
}//end of function soapRequest//
HTML:
<form name="Demo" action="" method="post">
<div>
<input type="button" id="API" value="Soap" onClick="soapRequest()" />
</div>
</form>
<input type="button" id="API" value="Soap" onClick="soapRequest()" />
Ref :- http://www.w3schools.com/jsref/event_onclick.asp
You need to call the function upon "onclick" event

image upload using javascript?

This is my HTML and javascript.
I'm trying to upload an image using javascript.
I did find some examples using jquery, but was hoping if this function below can be modified to do the same.
The image upload script is a PHP script, which works when the form is posted normally, but when using this function below, it doesn't send the image to the PHP script. $_FILES is empty.
How can I modify this function to send the image as well?
<html><head>
<script type="text/javascript">
function jax( ){
pd = document.getElementById("pd").innerHTML;
i = document.getElementById("i").value;
url= "ajax.php"; //?act=uploadPic&title=" + pd + "&i=" + i;
q="act=uploadPic&title=" + pd + "&i=" + i;
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support ajax. Allow Active scriptting in internet settings."); return false;
}
}
}
ajaxRequest.onreadystatechange= function(){
if(ajaxRequest.readyState == 4){
r =ajaxRequest.responseText;
alert(r);
}
}
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(q);
}//func
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p> Title: <input type="text" name="pd" id="pd" value=" Title here " />
<p> Image: <input type="file" name="i" id="i" />
<p> <button onclick=" jax( ) "> Upload </button>
</form>
</body>
</html>
The PHP script to verify if image is send:
ajax.php
<?php print_r($_FILES); ?>
this is my function,but can't working lower than ie8:
function jax(){
url= "ajax.php?act=uploadPic";
var formData = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
xhr.open('post',url,true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
xhr.addEventListener('progress',function(e){
if (e.lengthComputable) {
console.log(e.loaded+'/'+e.total);
}
},false);
xhr.send(formData);
}

Not able to Json response from rest server

Im trying to parse a Json response from a rest server using JavaScript and display the data.
The rest server works fine its just that i cant parse the data. I have looked at dozens of examples and from my understanding the code looks fine.
This is my first attempt at learning Ajax and if i fix this i can continue with my project.
This is the response
{"id":"1","author":"Bill Burke","title":"RESTful Java with JAX-RS","year":"2009"}
This is the server
#Path("/books") // JAX-RS annotation
public class BookResource {
#GET // JAX-RS annotation
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
#Path("/{bookId}")
public Book getBook(#PathParam("bookId") String id) {
return BookDao.instance.getBook(Integer.parseInt(id));
}
}
This is the client
<!DOCTYPE html>
<html>
<head>
<title>Form to create a new resource</title>
<script type="text/javascript">
function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xhr = false;
}
}
}
return xhr;
}
function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange = function() {
parseJ(request);
};
request.open("GET", file, true);
request.send(null);
}
}
function parseJ(request) {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
var obj = JSON.parse(request.responseText);
document.getElementById("details").innerHTML = obj.id + " " + obj.author + " "
+ obj.title + " " + obj.year;
}
}
}
</script>
</head>
<body>
<a
href="http://localhost:8080/Distributed_REST_booksServer/rest/books/1"
onclick="grabFile(this.href); return false;">Book 1</a>
<br>
<div id="details"></div>
</body>
</html>
html console error
html console error after modification
Your server is returning XML, try to force it as JSON and maybe add an accept header to the request from the client.

JavaScript + Querystring + div

How to load content in to a html page. please note IM not allowed to use php or C. Only javascript and html.
for example
load Page B in to Page A
http:myweb.com/index.html?load=pageb
thank you.
Issue an AJAX request to Page B
Get the contents using responseText
Display the contents inside a div using innerHTML property.
If you can use a js framework then I would suggest jQuery and #marcgg's answer will do it.
Just plain JavaScript:
<html>
<head>
<script>
function getUrlVars() {
var map = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
map[key] = value;
});
return map;
}
function createRequestObject() {
var ro;
// Mozilla, Safari,...
if (window.XMLHttpRequest) {
ro = new XMLHttpRequest();
if (ro.overrideMimeType) {
ro.overrideMimeType('text/xml');
// See note below about this line
}
// IE
} else if (window.ActiveXObject) {
try {
ro = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!ro) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
return ro;
}
function sndReq(param,server,handler) {
//location.href = server+"?"+action; //uncomment if you need for debugging
http = createRequestObject();
http.open('GET', server, true);
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
http.onreadystatechange = handler;
http.send(param);
}
handler_function = function()
{
if(http.readyState == 4)
{
if (http.status == 200)
{
document.getElementById("your_div_element").innerHTML = http.responseText;
}
else
{
alert('There was a problem with the request.');
}
}
}
</script>
</head>
<body>
<div id="your_div_element"></div>
<script>
var getvars= getUrlVars();
sndReq(null, getvars['action'], handler_function);</script>
</body>
</html>
html:
//Page A
<html>
<head><title>Page A</title></head>
<body>
<div id="pageB"></div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#pageB').load('pageb.html')
});
</script>
</body>
</html>
Using jQuery:
$.ajax({
type: "POST",
url: "http://some.com/page.html",
success: function(msg){
alert( "here's your data: " + msg );
jQuery("#yourDivID").html(msg);
}
});
http://docs.jquery.com/Ajax/jQuery.ajax
edit: added how to put it into a div

Categories