1

I have a php function that return to me an array of some RSS data, I would like to combine PHP with javascript. So, I did the following steps:

1- return the array from the PHP function;

2- Use foreach to loop over each element within the array returned;

3- use javascript to create <div> elements and populate each one with data brought from the array and add a dynamic effect.

Here is my code:

      <script>
                <?php 
                header("Content-Type: text/javascript; charset=utf-8");
                foreach(getFeed() as $article){ 
                ?>
                    setInterval(function() {

                    createDiv();
                    },5000);


                    function createDiv() {
                    document.getElementById("test").appendChild(document.createElement("DIV"));

                        $("#test").append('<div ><h4 id="title"><?php echo $article["title"]; ?></h4><p id="content"><?php echo $article["description"];  ?></p>');
                    }

                <?php 
                }
                ?>
      </script>

      <div  id= "test">

      </div>

The problem is I get n duplicated elements (n is the length of the array):

Element 1

Element 1

Element 1

...

However, this is not what I want, the desired result I want to return all the elements in the array:

Element 1

Element 2

Element 3

...

So, How can I solve this problem ?

5
  • why are you using JavaScript? Just echo the div elements in between the div tags for test Commented Feb 19, 2017 at 16:44
  • @MikeSchem i think because php can not handle time based mechanism like setInterval what is used here. Commented Feb 19, 2017 at 16:46
  • @MikeSchem thank you, it really works when I echo div tags, I want to add the effect of Ticker (i.e. I want to add dynamic effect) Commented Feb 19, 2017 at 16:47
  • You cannot combine PHP and javascript that way because PHP is executed on the server side, however javascript is executed on the client side such as browsers Commented Feb 19, 2017 at 17:09
  • @smarber thank you for the observation Commented Feb 19, 2017 at 18:22

3 Answers 3

2

first. stop mixing diffrent languages please :) thats ugly and bad style. seperate them. if it`s one file use hidden html tags to hide them.

<?php
  echo '<input id="hiddenField" type="hidden" value="'.json.encode(getFeed()).'">';

?>

<script type="text/javascript">
   var myArrayAsString = $('#hiddenField').val();
   var myArray = JSON.parse(myArrayAsString);
   // [{artNo: 1}, {artNo: 2}, ...]
   // now you can do what ever you want with a result array in javascript
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

First of combing scripting languages is often a headache

I recommend you rather have a php serer side call that returns your object alone (preferably in json) then call that service in you javascript, that way you have a nice separation of concerns.

Also looking at the code I see you are recreating your createDiv method every time you loop so you end up with multiple instances of that function, so when your setiInterval fires off it just keeps on picking up the first createDiv method you created and thus keeps firing it off leaving you with multiple instances of that first div.

edit for javascript code

for (var article in feed) {\n
  $("#test").append('<div class="post-id-' + article.id + '"><h4 id="title">' + article.title + '</h4><p id="content">' + article.description + '</p>');
}

2 Comments

Thank you, once I put all the elements on JSON object, how can I loop on it and create <div> and populate them wit JSON elements, this will really help me
I've added it in my answer
0

Check that.

<script>
        <?php 
            foreach(getFeed() as $article){ 
        ?>
            setInterval(function() {

                $("#test").append('<div class="post-id-<?php echo $article["id"] ?>"><h4 id="title"><?php echo $article["title"]; ?></h4><p id="content"><?php echo $article["description"]; ?></p>');

            }, 5000);

        <?php 
            }
        ?>
</script>
<div  id= "test">

</div>

4 Comments

Thank you so much, but I get the following error: SyntaxError: expected expression, got '<'
Check now. After my edit. Your array then returned by getFeed() must have id key. The same like title and description.
wunderfull unreadable code. works but nobody can read this one year after creating without working 20 minutes on this one line ...
That's really constructive @mtizziani, but you're right. OP should split each tag and use jQuery to append each tag to it's parent. You can use a minifier to compress your code in production.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.