-2

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: '#'}));
                }
stijn.aerts
  • 6,026
  • 5
  • 30
  • 46
  • 2
    Your AJAX request is asynchronous, so naturally your loop is going to try to run long before the response comes back. That's why there's an `onreadystatechange` callback. – cookie monster Jun 04 '14 at 13:46
  • 1
    You should read it: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – A. Wolff Jun 04 '14 at 13:48
  • After reading the provided links, I have problems with accessing my .php file in code, so how should I edit my code? – stijn.aerts Jun 04 '14 at 14:06

2 Answers2

0

I resolved it, I used following code.

$(document).ready(function() {
    $(".menu li").each(function() {
        this.onclick = function() {
            //getDetails(this.id);
            $.ajax({
                url: "getDetails.php?LiID="+this.id
            }).done(function(data){
                $(".description").empty().append(data);
                imgHandle();
            });
        };
    });
});

function imgHandle()
{
    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: '#'}));
    }
}

Is this valid code? Or isn't this a good way to resolve this?

stijn.aerts
  • 6,026
  • 5
  • 30
  • 46
-1

In jquery, a simple illustration would be

$.ajax({
  type: "GET",
  url: "http://sample/url",
  data: { // your data to pass to the server here}
  dataType: "script"
});

You can then configure your php script to return a javascript file(which has your logic) which will be executed upon a successfull ajax call.

Joseph N.
  • 2,437
  • 1
  • 25
  • 31
  • You have posted only the code for making an AJAX call with jQuery. Then you are proposing weird solution with PHP serving a javascript file. Have you ever heard of jQuery AJAX callbacks? Callbacks are listed in this http://api.jquery.com/jquery.ajax/#jqXHR section. – ElmoVanKielmo Jun 04 '14 at 13:58