Skip to content
Advertisement

Script html php

In the script below, I currently have a fixed value in the array of $out variable. Example: $out[1]. What I need is for this fixed value (in this case 1), to be replaced by the str value of the function.

str is javascript

$out[1] is php

Someone can help me?

<script>
    function teste2(str) {
        var xhttp;    
        if (str == "") {
            document.getElementById("cli").innerHTML = "";
            return;
        }
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                   document.getElementById("resimg").innerHTML =
                   "<img src=" + "<?php echo ("img/base/".$out[1]);?>" + ">"   
             }
        };
    xhttp.open("GET", "clique.php?q="+str, true);
    xhttp.send();
    }
</script>

Advertisement

Answer

As mentioned, it doesn’t make sense why you are mixing PHP in your JS. If you need data from the server side usable by your client side JS, there are multiple approaches.

  1. The preferred approach is to make an API endpoint you can call and return JSON.
  2. Another approach (not recommended) is to output a JSON object in a script tag on server render and then access it like:
<script>
    let data = <?php echo(json_encode($myData)); ?>;
</script>

To answer your question though, you can set the value with JS since the variable you want is client side:

function teste2(str) {
    var xhttp;    
    if (str == "") {
        document.getElementById("cli").innerHTML = "";
        return;
    }
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            let src = 'img/base/' + str;
            document.getElementById("resimg").innerHTML = '<img src="' + src + '">';   
        }
    };
    xhttp.open("GET", "clique.php?q="+str, true);
    xhttp.send();
}
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement