I have a problem with executing Javascript after Ajax loads some data from a php file, I'm new to Javascript and Ajax so odds are that it is a minor mistake. I tried several things and here is what I came up with:
var request = new XMLHttpRequest();
$(document).ready(function() {
$(".menu li").each(function() {
this.onclick = function() {
getDetails(this.id);
if(this.id===1)
{
for(var i=1;i<4;i++) {
var img= ".img"+i;
$(img).on("click", function(){
var art = $(this).closest('article');
art.css('height', 'auto');
art.find('p').slideToggle(200);
if(this.src.indexOf("plus") > -1)
{
this.src = "images/min.png";
}
else
{
art.css('height', '62px');
this.src = "images/plus.png";
}
});
$(img).wrap($('<a>',{href: '#'}));
}
}
};
});
});
function getDetails(itemName) {
if (request === null) {
alert("Unable to create request");
return;
}
var url = "getDetails.php?LiID=" + encodeURI(itemName);
request.open("GET", url, true);
request.onreadystatechange = displayDetails;
request.send();
}
function displayDetails() {
if (request.readyState === 4 && request.status === 200) {
$(".description").empty().append($(request.responseText));
}
}
Here is the .php file where I get the data from:
<?php
$index= $_REQUEST['LiID'];
$details = array(
'1' => "<h1>Home</h1>
<article>
<h1>Over mezelf <img src='images/plus.png' class='img1'/></h1>
<p class='p1'>Test</p>
</article>
<article>
<h1>Contact <img src='images/plus.png' class='img2'/></h1>
<p class='p2'>Test</p>
</article>
<article>
<h1>Website <img src='images/plus.png' class='img3'/></h1>
<p class='p3'>Test</p>
</article>",
'2' => "<h1>Artists</h1>
<p>Artists page.</p>",
'3' => "<h1>Releases</h1>
<p>Here u can find our releases.</p>"
);
echo $details[$index];
?>
The problem is that the following code doesn't execute, first I worked without Ajax and then it worked properly.
for(var i=1;i<4;i++) {
var img= ".img"+i;
$(img).on("click", function(){
var art = $(this).closest('article');
art.css('height', 'auto');
art.find('p').slideToggle(200);
if(this.src.indexOf("plus") > -1)
{
this.src = "images/min.png";
}
else
{
art.css('height', '62px');
this.src = "images/plus.png";
}
});
$(img).wrap($('<a>',{href: '#'}));
}