Jump to content
iwato

Calling an Image File with AJAX

Recommended Posts

BACKGROUND:  I am querying a MySQL database with a Matomo GUI.  The API is called imageGraph.  The call to the API works, as I have produced the desired image by assigning the URL as the value of an href attribute of an HTML <a> element.  When using this link to display the image the image appears on a new page with its own header.  This is not the effect that I desire.  My goal is to display the image within a <div> tag on a webpage.  The code that is suppose to achieve this latter effect is provided below.  The URL that fetches the data from the API is identical for both the link and the PHP processing page for the AJAX call provided below.

The PHP (./practice.php)

$url ='https://.../matomo/index.php
	?module=API
	&method=ImageGraph.get
	&idSite=1
	&apiModule=Referrers
	&apiAction=getReferrerType
	&token_auth= ...
	&period=day
	&date=2018-04-10,2018-05-09';
$curl_request = curl_init();
curl_setopt($curl_request, CURLOPT_URL, $url);
curl_exec($curl_request);
curl_close($curl_request);

The HTML

<div id='referral_types'>
    <img src='' alt='Line Chart of Referral Types' />
</div>

The Javascript

$(document).ready(function() {
    $.ajax({
        method: 'GET',
        url: "./practice.php",
        cache: false,
        contentType: 'image/png',
        success: function(response) {
            console.log(response);
            var graphic_src = response;
            $('#referral_types').find('img').attr('src', graphic_src);
        }
    });
});

EXPERIMENTATION:  The console indicates that practice.php has been read, as it is filled with the kind of character nonsense typical of an image file.  As the API permits an optional &format parameter I experimented with several including the following:

AJAX                             PHP

dataType JSON,         &format=json
dataType XML           &format=xml
(omit)                          &format=original

The result was invariably the same.  The ALT message with no image.

Please advise.

Roddy

  

Share this post


Link to post
Share on other sites

You can't just assign a giant set of bytes to the src attribute of an image. What you actually should do is set the URL practice.php as the src of the image. On the PHP side, you should send a header indicating the type of image that is being displayed. I'm going to assume PNG, but you need to guarantee that you know the correct image type to make this work.

PHP:

<?php
header('Content-Type: image/png');

$url ='https://.../matomo/index.php
	?module=API
	&method=ImageGraph.get
	&idSite=1
	&apiModule=Referrers
	&apiAction=getReferrerType
	&token_auth= ...
	&period=day
	&date=2018-04-10,2018-05-09';
$curl_request = curl_init();
curl_setopt($curl_request, CURLOPT_URL, $url);
curl_exec($curl_request);
curl_close($curl_request);

HTML:

<img src="practice.php" alt="Line Chart of Referral Types">

Or you can even skip out on the PHP part and have the browser directly resolve the image for you:

<img src="https://.../matomo/index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Referrers&apiAction=getReferrerType&token_auth= ...&period=day&date=2018-04-10,2018-05-09" alt"Line Chart of Referral Types">

 

Share this post


Link to post
Share on other sites

Alright.  So, I cannot do what I want in the way that I am trying to do it.  However, I do not want to do it in either of the two ways that you are suggesting.  My reasons are as follows.

1)  The idea of the AJAX call is to allow users to change parameter values and  sometimes even the parameter key-value pairs of the API call sent with the cURL to the Matomo server.  In order for this to occur AJAX is a reasonable means of communication between the visitor's selection and the cURL that is sent.

2) In order to access the Matomo server an authorization token is required.  I do not want this to be made visible to anyone and everyone.  It must remain hidden -- hence, the introduction of the PHP file.

3) You appear to be suggesting a different file for each and every graph that I wish to appear on the same page. 

Any other suggestions?

Roddy

Edited by iwato

Share this post


Link to post
Share on other sites

You can add query string parameters to the PHP file to decide which graph to show and use those query string parameters in the src attribute. PHP would use those parameters to decide which graph to show. One PHP file can show as many graphs as you want it to. It would be done like this:

<img src="practice.php?graph=1">
<img src="practice.php?graph=2">

On the PHP end, you would show this:

<?php
header('Content-Type: image/png');

$graph_type = isset($_GET['graph']) ? $_GET['graph'] : 1;
if($graph_type == 1) {
  $url ='https://.../matomo/index.php
      ?module=API
      &method=ImageGraph.get
      &idSite=1
      &apiModule=Referrers
      &apiAction=getReferrerType
      &token_auth= ...
      &period=day
      &date=2018-04-10,2018-05-09';
} else if($graph_type == 2) {
  $url = 'Something else';
} else if($graph_type == 3) {
  $url = 'A third URL';
} else {
  $url = 'A fallback URL';
}

$curl_request = curl_init();
curl_setopt($curl_request, CURLOPT_URL, $url);
curl_exec($curl_request);
curl_close($curl_request);

 

You can use more parameters in the query string if you want to more clearly identify the graph, I just use a graph number for simplicity. If you want the user to be able to change the image using dropdowns or sliders you can have Javascript generate the image URL, like this:

<img id="image" src="practice.php?graph=1">
<select id="graph-type-dropdown">
  <option value="1">Graph type 1</option>
  <option value="2">Graph type 2</option>
</select>

<script>
var dropdown = document.getElementById("graph-type-dropdown");
dropdown.addEventListener("change", changeImage, false);

function changeImage(e) {
  var type = e.currentTarget.value;
  var img = document.getElementById("image");
  img.src = "practice.php?graph=" + type;
}
</script>

There is no need for AJAX here. It would make the process much slower.

Share this post


Link to post
Share on other sites

Is there really no other way to use AJAX to achieve the task?

This graphic imagery is designed to appear on my site's mainpage via HTML inserts called by AJAX.  It is not until the insert is loaded with an initial set of images that visitor's will be given the opportunity to change what they see. Maybe I am over anticipating, but getting this to work via PHP appears without having to reload the entire mainpage appears impossible.  No?

Roddy

Share this post


Link to post
Share on other sites

AJAX is not the correct tool for this problem. Why do you insist on using it?

I already gave a solution that does not require reloading the page, use Javascript. It does not need AJAX.

  • Like 1

Share this post


Link to post
Share on other sites

I appear not to have understood clearly what you are suggesting.  Alright.  I will attempt to implement it, as I learn code best through experimentation.  And, will return with the result.

Roddy

Edited by iwato

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×