Reputation: 2733
Im trying to make a gallery application with some ajax. It has to work this way: when typing a title of an image you want to upload, what appears is a dynamic gallery with photos of title containing the string you're currently typing in the text input. Everything is fine except for displaying of the images. This is the code:
js file:
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){ //IE
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp =false;
}
}else{ //other browser
try{
xmlHttp= new XMLHttpRequest();
}catch(e){
xmlHttp =false;
}
}
if(!xmlHttp)
alert("cos nie tak!");
else
return xmlHttp;
}
function process(){
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
typedText=encodeURIComponent(document.getElementById("title").value );
xmlHttp.open("GET", "ajax.php?text="+typedText, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse=xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message=xmlDocumentElement.firstChild.data;
document.getElementById('underInput').innerHTML=message;
setTimeout('process()', 1000);
}else{
alert('wrong');
}
}
}
I have managed to make variable message
to have a list of URLs of the images needed. It looks like that: image1.jpg image2.jpg image3.jpg ...etc
.
What im struggling with is to use javascript to parse this string and to use javascript to display those images in div id="underInput"
node in my index.php
file.
Thanks for help!
Upvotes: 2
Views: 66
Reputation: 528
You can try to split your string image names by whitespace something like this: In your handleServerResponse function:
//"image1.jpg image2.jpg image3.jpg";
message = xmlDocumentElement.firstChild.data;
var image_list = message.split(' ');
for (var i in image_list) {
var img = document.createElement("img");
img.src = image_list[i];
document.getElementById('underInput').appendChild(img);
}
But, I recommend you to use a JSON data from server instead simple string, it's very easy and don't need to split it, otherwise you can manage arrays and objects, this is most effective.
you can output a json in php so:
$myarray = array('image1.jpg', 'image2.jpg', 'image3.jpg');
echo json_encode($myarray);
Upvotes: 2