jmextratall jmextratall -4 years ago 53
Javascript Question

I have a JavaScript function that calls a PHP Function. How can I get the results to display in the html and not in an alert box?

I have a PHP function that makes a cURL call to an API. I want this call to be triggered by the click of a button using JavaScript. How can I get the result to display in the HTML and not in an alert box? My code is as follows:

<script>
function echoSkilljar() {
alert("<?php skilljarApiCall(); ?>");
}
</script>

<?php
function skilljarApiCall() {
// Get cURL resource
$curl = curl_init();

// Set some options - passing a username to Skilljar in the URL
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => 'https://api.skilljar.com/v1/users/***********/published-courses',
CURLOPT_HEADER => 0,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERNAME => 'sk-live-***********'
));

// Send the Request & save response to $response
$response = curl_exec($curl);

// Close request to clear up some resources
curl_close($curl);

// Trim response string to remove leading and trailing "[ and ]"
$trimmed = trim($response, '"[');
$newTrimmed = rtrim($trimmed, ']"');

// Convert trimmed string to JSON
$json = json_encode($newTrimmed);

// Convert JSON to usable associative array
$newJson = json_decode($json);
$array = json_decode($newJson, true);

// Make sure it worked... (fingers crossed);
// var_dump($array);

// Yay it worked! Now make sure we can access the elements of the array...
echo $array['course']['id'] . "/ " . $array['course']['title'];
}
?>

<button onclick="echoSkilljar()">Skilljar Stuff</button>
<div id="info"></div>

Answer Source

With your code, this part:

<script>
    function echoSkilljar() {
        alert("<?php skilljarApiCall(); ?>");
    }
</script>

basically gets resolved to some fixed string. Let's assume the result is my-output. That means your HTML looks like this when rendered:

<script>
    function echoSkilljar() {
        alert("my-output");
    }
</script>

So, in this case, we're just talking about how to make a simple string output in the HTML.

There are a large number of ways you could go about this. You didn't specify, but I'm going to assume you wanted to put it inside of the <div id="info"></div>.

To do that, we'll just select it and set it's innerText.

<script>
  function echoSkilljar() {
    document.getElementById('info').innerText = "my-content";
  }
</script>

<button onClick="echoSkilljar()">Click Me</button>
<div id="info"></div>

Basically, just replace this line:

alert("<?php skilljarApiCall(); ?>");

with this:

document.getElementById('info').innerText = "<?php skilljarApiCall(); ?>";

When rendered, it'll look like this:

document.getElementById('info').innerText = "my-content";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download