Ng21
Ng21

Reputation: 231

how to use document.getElementbyId in PHP

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>'  ;

    }

Upvotes: 3

Views: 33031

Answers (4)

RandomTap
RandomTap

Reputation: 21

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]

Upvotes: 2

wodka
wodka

Reputation: 1390

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>

Upvotes: 1

Palmy
Palmy

Reputation: 49

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

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

Upvotes: 3

Taylor Foster
Taylor Foster

Reputation: 1215

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>';
    }

Upvotes: 3

Related Questions