0

I'm trying to get a jQuery script to update the content of an HTML paragraph tag variously according to whether or not a PHP if statement, which checks for data in a database, evaluates to true or not:

if ($num_rows > 0) { ?> // If results are returned from database...

 <script>
   $(document).ready(function() {
    $('p.message').text('Some data');   // ... p should read 'Some data'
   });
 </script>

<?php else {            // otherwise
 <script>
   $(document).ready(function() {
    $('p.message').text('No data');    // ...p should read 'No data'
   });
 </script>
}

The contents of are intended to change dynamically without the need for a page refresh, but do not do so. Only after the page has been refreshed is the new value shown.

Any ideas as always much appreciated.

5
  • You cannot execute jQuery on server. Commented Apr 30, 2013 at 15:32
  • 3
    PHP executes on the server. The generate html/script will contain ONLY the results of your if() at the time the php code is executed. if the variable changes later, the JS code for the OTHER condition will physically not be present in your page. Commented Apr 30, 2013 at 15:32
  • 1
    php is server-side, javascript is client-side. php code can't be ran from the client other than by using ajax. Commented Apr 30, 2013 at 15:33
  • Thanks guys. Any ideas on how to achieve what I want? To get different content into that p tag according to the database contents? Commented Apr 30, 2013 at 15:35
  • What u need to show ? u need to get data from server without refreshing ? Commented Apr 30, 2013 at 15:48

3 Answers 3

3

Use AJAX to get the content from PHP. You can have the success populate the data into your HTML.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Biotox and the other respondents. I did it with AJAX and success and it's working fine. Not a good question - I realised after asking that PHP and jQuery cannot communicate - it was a long day!
2

What You are trying to do can be achived through Ajax. Belwo Is a simple Example

Jquery

 setInterval(function(){UpdateMessage()},10000) // Will Eecute after 10 Seconds

 function UpdateMessage()
 {
 $.ajax({
  type:"POST",
  url:"Script.php",
  success: function(data)
               {
                $(".message").text(data);
               }
       });//END OF Second AJAX
   }

HTML

   <p class='message'></p>

Script.php

 if ($num_rows > 0)
 echo "SOME DATA";
 else
 echo "No Record";

above code will refresh Your Data every after 10 Seconds Without Refresh

Comments

1

did you try include jquery into that php file? like

<script type="text/javascript" src="jquery-1.9.1.min.js"></script>

Comments

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.