0

I have a php file which needs to pass an array to an external javascript file. I'm trying to do it using AJAX because it seems like the proper way to do so. I'm trying to do an echo json_encode($exif) and then get it in the js but the json is printed on my current page. How can I achieve what I'm doing and what's the proper way to do it?

I'm trying to do the first solution of this answer How to pass variables and data from PHP to JavaScript? but I don't see how to integrate the php part so that it doesn't show up on my page.

Here is the php code. I need to pass the array while building my view. Therefore when I do the echo, the whole array is displayed on the page.

public function makeImagePage($image) 
{
    ...
        $this->parts["content"] .= "<p><u>Localisation:</u> </p>";
        $this->parts["content"] .= '<div id ="map"></div>';
        echo json_encode($exif);
        $this->parts["content"] .= '<script type="text/javascript" src="js/map.js"></script>';
    ...
}
pioupiou1211
  • 353
  • 4
  • 16
  • Whats showing up on your page that you do not want showing up on your page? Please provide more code, examples of whats wrong, examples of what you are expecting. – IncredibleHat Dec 17 '17 at 16:27
  • @IncredibleHat I added the php code. Hope it helps understand my problem. I don't know how and where I have to pass my array. – pioupiou1211 Dec 17 '17 at 16:33
  • Ah I see. You should be putting it inside the `script` tags for a js var assignment. Empty `script` tags, not the ones with `src=`. – IncredibleHat Dec 17 '17 at 16:37

1 Answers1

0

Changing this:

    $this->parts["content"] .= "<p><u>Localisation:</u> </p>";
    $this->parts["content"] .= '<div id ="map"></div>';
    echo json_encode($exif);
    $this->parts["content"] .= '<script type="text/javascript" src="js/map.js"></script>';

To this, will put the data into a javascript area for you to use:

    $this->parts["content"] .= "<p><u>Localisation:</u> </p>";
    $this->parts["content"] .= '<div id ="map"></div>';
    $this->parts["content"] .= '<script>var my_var = '. json_encode($exif) .';</script>';
    $this->parts["content"] .= '<script type="text/javascript" src="js/map.js"></script>';

This is assuming your map.js is USING that variable anywhere, and you will have to set the right js variable name, and adjust the map.js code accordingly, and such.

This is merely a first step to getting your php data somewhere for js to use.

IncredibleHat
  • 4,000
  • 4
  • 15
  • 27