1

I would like to call a javaScript function in a php Div. I have tried somethings, but they do not work. Here are the code lines.

<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>

<div class="container">
    //Set the image here. (I would like to set the image here. )
    //That is what I have tried, but it does not work.
    <?php $img_name = echo  $row['img_name']; ?> //e.g. $img_name = cat.jpg; ?>
    //Call the  img() function to set the image
    echo '<script type="text/javascript">', 'img('.$img_name.');', '</script>';
</div>

Here is the js function

<script>
function img(img_src){
    //Create div
    var m_div = document.createElement('Div');
    m_div.style.background = "green";
    m_div.id = "id_div";

    //Create img
    var img_input = document.createElement('img');
    img_input.id = "id_img"; 
    img_input.src = "images/" + img_src; // e.g. img_src = cat.jpg;
    img_input.height = "380";
    img_input.width = "290";

    //Append img to div
    document.getElementById("m_div").appendChild("img_input");
}
</script>

Thank you in advance.

0

2 Answers 2

1

You can't call javascript from PHP. You have to use PHP to produce HTML that in-turn can call the javascript function. Print out the image file name from the PHP variable -> into the HTML -> as a parameter value into the javascript function.

    $img_name = 'showMe.jpg';
    echo '<script type="text/javascript">img("'.$img_name.'")</script>';
Sign up to request clarification or add additional context in comments.

2 Comments

Injecting arbitrary data into script (or even HTML) isn't a great idea. At least use json_encode() to be compatible.
Thank you @user_pt. I have considered your opinion and I have created another question stackoverflow.com/questions/61569289/… Please have a look there.
0

You can't call js from PHP. PHP is a backend language that means run before the javascript loaded, javascript is a frontend language that means is loaded after the browser loads the page.

However you can pass PHP to javascript but is not recommended. It is better to use ajax to load the variable from the server. This is a link to read more information about pass variables from PHP t to javascript.

example:

//Call the  img() function to set the image
<script type="text/javascript">
  var row = <?php echo  json_encode($row); ?>; //e.g. $img_name = cat.jpg; ?>
  (function(image) {
      img(image);
  })(row.img_name);
</script>

1 Comment

Thank you @Fermin Perdomo. I have considered your opinion and I have created another question stackoverflow.com/questions/61569289/… Please have a look there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.