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
4 Answers
Reset to default 3Replace 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>