最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to use document.getElementbyId in PHP - Stack Overflow

programmeradmin4浏览0评论

i want to run javascript in PHP but this code isn't not working at all for me.

if(!mysqli_fetch_assoc($result))
    {
      echo '<script type="text/javascript">',
     'document.getElementById("console1").innerHTML += "Query did not work";',
     '</script>'  ;

    }

i want to run javascript in PHP but this code isn't not working at all for me.

if(!mysqli_fetch_assoc($result))
    {
      echo '<script type="text/javascript">',
     'document.getElementById("console1").innerHTML += "Query did not work";',
     '</script>'  ;

    }
Share Improve this question asked Jul 19, 2017 at 19:02 Ng21Ng21 2312 gold badges4 silver badges11 bronze badges 7
  • i tried it works for me , you may forgot to add console1 as id for some element in your page or the condition hasn't been true – Ali Faris Commented Jul 19, 2017 at 19:20
  • can you post the plete page? also keep in mind that php is run on server side whereas javascript is run on the client – wodka Commented Jul 19, 2017 at 19:28
  • @wodka i am calling this php file from html page using ajax. – Ng21 Commented Jul 19, 2017 at 19:36
  • @Ali i have rechecked and everything is in place – Ng21 Commented Jul 19, 2017 at 19:40
  • @wodka yes i am aware of that, i am using xampp – Ng21 Commented Jul 19, 2017 at 19:41
 |  Show 2 more ments

4 Answers 4

Reset to default 3

Replace those , with . to chain a string.

if(!mysqli_fetch_assoc($result))
    {
      echo '<script type="text/javascript">' . 
      'document.getElementById("console1").innerHTML += "Query did not work";' .
      '</script>';
    }

You can't use " in php, this worked for me!

echo "<script> 
       document.getElementById('console1').innerHTML += 'Query did not work'; 
      </script>";

You can Try the Heredoc Notation:

<?php
    echo<<<HTML
    .
    .
    <script type="text/javascript">
      document.getElementById("console1").innerHTML += "Query did not work";
    </script>
    HTML; 

//[*Note that echo<<<HTML and HTML; has to be on the very left side without blank spaces]

since it is done with ajax try something similar to this:

<?php
    if(!mysqli_fetch_assoc($result)) {
        http_response_code(500);
        die(['error' => 'Query did not work!']);
    }
?>

and in your frontend code something like:

<script>
    $.get('your/query/path?query=...', function() {
        console.log('executed');
    }).fail(function(result) {
        $('#console1').append(result.error);
    });
</script>
发布评论

评论列表(0)

  1. 暂无评论