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>' ;
}
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>
Related
I'm making a music player using php and javascript. I list the files like this:
<?php
if (isset($_GET["action"])) {
$action = htmlspecialchars($_GET["action"]);
if ($action == "listen") {
function listFolderFiles($dir) {
$ffs = scandir($dir);
echo '<ol>';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
echo '<li>'. $ff . '';
if (is_dir($dir . '/' . $ff)) listFolderFiles($dir . '/' . $ff);
echo '</li>';
}
}
echo '</ol>';
}
listFolderFiles("music");
}
} else {
echo '> listen';
}
?>
And I change the song like this:
<script>
function changesong(url) {
$("#audioplayer").attr("src", url);
$("#audioplayer").trigger('play');
}
</script>
The problem is that songs with quotes in them won't play (for example Don't Stop Me Now). Is there an easy way to fix this?
You should use addslashes(), like this:
echo '<li>'. $ff . '';
You can escape quotes for javascript function in HTML code like this:
Note that you probably need to escape double quotes as well, since they can interfere with HTML tag.
$link = $dir . '/' . $ff;
$link = str_replace("'", "'", $link);
$link = str_replace('"', """, $link);
echo '<li>'. $ff . '';
I want to know if my php variable does not exists, then I want to execute my javascript.
For example-
<?php
if(!isset($_REQUEST['myVar'])){
?>
<script>
alert('variable not exist');
</script>
<?php
}
?>
Is this right way to use javascript code in php extension file
I know all other answers solve your issue but i prefer it to do this way
<script>
<?php
$isset = !isset($_POST['myVar']) ? 'true' : 'false';
echo "var isset = $isset;";
?>
if(isset) {
alert('variable not exist');
}
</script>
when php render your page it will give this output
<script>
var isset = true;
if(isset) {
alert('variable not exist');
}
</script>
Do it like this and it will work:
if (!isset($_REQUEST['myVar'])) {
echo "<script>alert('variable not exist');</script>";
}
you can try writing this piece of code where you want the script to be placed:
<?php
if (!isset($_REQUEST['myVar'])) {
echo '<script>
alert("variable not exist");
</script>';
}
?>
I have an array in php lets call it:
$nums = array(10,25,52,32,35,23);
I want to send it to my javascript function like this:
var nums=[10,25,52,32,35,23];
How can i do this?
(My javascript file name is "nums.js")
Edit:
nums.js is a javascript code. It changes the values of table in the html. But the values only exist in php. So i have to send the values to javascript.
PHP >= 5.2
The json_encode function is for this purpose:
<?php echo 'var nums=' . json_encode(array(10,25,52,32,35,23)) . ';'; ?>
Docs: http://php.net/json_encode
PHP < 5.2
If you can't use json_encode, take a look at this post for a way to define an equivalent.
As long as your javascript file is being parsed by PHP before being sent to the client, then this should work:
<?php echo "var nums=[" . implode(',', $nums) . "];"; ?>
Just json_encode() the array and then output it as an array literal in javascript.
<?php
$nums = array(10,25,52,32,35,23);
$nums_json = json_encode($nums);
?>
<script type="text/javascript">
var nums = <?php echo $nums_json; ?>;
</script>
you can also use json_encode() but only possible from php 5.2
see more: http://us3.php.net/manual/fr/function.json-encode.php
or you can use this function:
function php2js ($var) {
if (is_array($var)) {
$res = "[";
$array = array();
foreach ($var as $a_var) {
$array[] = php2js($a_var);
}
return "[" . join(",", $array) . "]";
}
elseif (is_bool($var)) {
return $var ? "true" : "false";
}
elseif (is_int($var) || is_integer($var) || is_double($var) || is_float($var)) {
return $var;
}
elseif (is_string($var)) {
return "\"" . addslashes(stripslashes($var)) . "\"";
}
return FALSE;
}
Basically I used these codes to transform:
echo "<script>";
echo " var img_array=new Array();";
foreach($img_arr as $img_url){
$url=(string)$img_url;
echo "img_array.push('".$url."');";
}
echo "console.log(img_array);";
echo "</script>";
However, errors occur(firefox debug window) :
Error: unterminated string literal
Source File: http://127.0.0.1/CubeCart/index.php?_a=account
Line: 1, Column: 42
Source Code:
var img_array=new Array();img_array.push('http://gtms01.alicdn.com/tps/i1/T1mL3LFhhhXXaCwpjX.png
but after I checked the souce file of the html page, the script is shown like this:
<script> var img_array=new Array();img_array.push('http://gtms01.alicdn.com/tps/i1/T1mL3LFhhhXXaCwpjX.png
');img_array.push('http://gtms01.alicdn.com/tps/i1/T1DQtTFsdFXXaCwpjX.png');console.log(img_array);</script>
With which I don't see anything is wrong.
$jsArray = json_encode ($phpArray);
There is a newline in one of the items in your your php array. Use this:
echo "<script>";
echo " var img_array=new Array();";
foreach($img_arr as $img_url){
$url=(string)$img_url;
echo "img_array.push('". htmlentities(trim($url))."');";
}
echo "console.log(img_array);";
echo "</script>";
I have the above below already functional on my website. It works alright but right now, I want to create a kind of promo and if the display meets the criteria of the promo, I want it to display onclick $htx
<?php
echo "<a href='javascript:;' onclick='pkgsPopup('http://'.$hLnk');' rel='nofollow'>";
?>
I have $htx pre defined to open a link $dealpath and if it does not meet that condition, I want it to open the default link - '$hLnk'
I have tried the code below and I had an error _ I mean the page will not load at all
if ($htx) { echo "onclick=\'miaPopup('http://$dealPth');\'' } else { echo 'onclick=\'pkgsPopup('http://$hLnk');\'' }";
I will really appreciate if someone can let me know how to do this without error using the PHP if/else statement.
Here is your second block of code a little cleaner. You were missing semi-colons in the PHP as well as matching escape characters ( a mix of apostrophes and quotes)
if ($htx)
{
echo "onclick=\'miaPopup('http://$dealPth');\'" ;
}
else
{
echo "onclick=\'pkgsPopup('http://$hLnk');\'" ;
}
The problem is that you have the echo pumping out a long string that makes no sense:
if ($htx) { echo "onclick=\'miaPopup('http://$dealPth');\'' } else { echo 'onclick=\'pkgsPopup('http://$hLnk');\'' }";
should read:
if ($htx) {
echo "onclick='miaPopup(\'http://$dealPth\');'";
} else {
echo "onclick='pkgsPopup(\'http://$hLnk\');'";
}
You could simplify by saying
if ($htx) {
$url = $dealPth;
} else {
$url = $hLnk;
}
echo "onclick='pkgsPopup(\'http://$url\');'";
Something like this should work (this code is not tested):
$onclick = ($htx ? 'miaPopup("http://'.$dealPth.'");'
: 'pkgsPopup("http://'.$hLnk.'");');
echo "<a href='javascript:;' onclick='$onclick' rel='nofollow'>";
try this
if ($htx){
$onclick="miaPopup('http://$dealPth');";
}
else{
$onclick="pkgsPopup('http://$hLnk');";
}";
echo "<a href='javascript:;' onclick='$onclick' rel='nofollow'>";
Why not use jQuery
<a class='one <?=($cond?"two" : "")?>'>Link</link>
<script>
$(function(){
$(".one").click(function(){
//Class of one
});
$(".two").click(function(){
//class of two
})
})
</script>