Prepare Interview

Mock Exams

Make Homepage

Bookmark this page

Subscribe Email Address

Ajax%20Interview%20Questions%20and%20Answers

Question: How do I send an image using AJAX?
Answer:
While it may appear that images are being sent when using AJAX with an application like Google Maps what is really happening is that the URLs of images are being send as the response of an AJAX request and those URLs are being set using DHTML.
In this example an XML document is returned from an AJAX interaction and the category bar is populated.

<categories>
<category>
<cat-id>1</cat-id>
<name>Books</name>
<description>Fun to read</description>
<image-url>books_icon.gif</image-url>
</category>
<category>
<cat-id>2</cat-id>
<name>Electronics</name>
<description>Must have gadgets</description>
<image-url>electronics.gif</image-url>
</category>
</categories>


Notice that the image-url element contains the location of the URL for the image representing a category. The callback method of an AJAX interaction will parse the response XML document and call the addCategory function for each category included in the response XML document. The addCategory function looks up a table row element "categoryTable" in body of the page and adds a row to the element which contains the image.

<scrip type="text/javascript" >

...

function addCategory(id, name, imageSrc) {

var categoryTable = document.getElementById("categoryTable");
var row = document.createElement("tr");
var catCell = document.createElement("td");
var img = document.createElement("img");
img.src = ("images\" + imageSrc);
var link = document.createElement("a");
link.className ="category";
link.appendChild(document.createTextNode(name));
link.setAttribute("onclick", "catalog?command=category&catid=" + id);
catCell.appendChild(img);
catCell.appendChild(link);
row.appendChild(catCell);
categoryTable.appendChild(row);
}
</script>

...

<table>
<tr>
<td width="300" bgoclor="lightGray">
<table id="categoryTable" border="0" cellpadding="0"></table>
</td>
<td id="body" width="100%">Body Here</td>
</tr>
</table>


Note that the source of the image is set to the image source. The image is loaded by a subsequent HTTP request for the image at the URL "images/books_icon.gif" or "images/electronic_icon.gif" that occurs when the img element is added to the categoryTable.
Is it helpful? Yes No

Most helpful rated by users:

©2024 WithoutBook