0

I am trying to execute a php file from a javascript function with AJAX/JQuery - nothing I have found so far works. The file with the javascript is index.php and getTemps.php is in the same directory on my apache server. I have found that getTemps works fine so it must be how I'm calling it from index.php.

getTemps.php: reads last line of file that updates every minute

<?php
$lastLine = shell_exec('tail -1 temps.log');
$temps = explode(" ", $lastLine);
echo $temps;
?>

javascript from index.php: this code is inside a function which gets called every minute

var tempString;

$.get("getTemps.php", function(data) {
    tempString = data;
});

I have also tried these with no luck.

$.ajax({url: 'getTemps.php', success: function(data) { tempString = data; }});

$.ajax({
    url : 'getTemps.php',
    type : 'GET',
    data : data,
    dataType : 'string',
    success : function (data) {
       tempString = data
    }
});

Any help would be awesome. Been stuck on this for awhile. Thanks in advance!

  • `dataType: 'string'` should be `dataType: 'text'`. But it should default to text if it doesn't recognize the type. – Barmar Nov 10 '15 at 02:16
  • I don't believe "I have found that getTemps works fine". It should just be returning the string `Array`. Why are you exploding the line? Why not just `echo $lastLine;`? – Barmar Nov 10 '15 at 02:18
  • Can you provide more information on what doesn't work? If you use your browser developer tools does the request return a valid result? Have you tried `console.log(data)`? – ajshort Nov 10 '15 at 02:19
  • @Barmar echoing lastLine does not work either. Exploding it was left over from other ways I have tried to pass it back. – inicDominus Nov 10 '15 at 02:28
  • You said that `getTemps` works fine when you test it. What do you see if you put `getTemps.php` in the browser's address bar? – Barmar Nov 10 '15 at 02:29
  • @Barmar The last line line of the file is displayed in the upper left corner. – inicDominus Nov 10 '15 at 02:31
  • You're not doing anything with `tempString`. Add something like `alert(tempString)` to the success function. – Barmar Nov 10 '15 at 02:31
  • If you're trying to use `tempString` after the AJAX call, see http://stackoverflow.com/questions/23667086/why-is-my-variable-undefined-after-i-modify-it-inside-of-a-function-asynchron?newsletter=1&nlcode=97716%7c4ba7 – Barmar Nov 10 '15 at 02:32
  • @Barmar it gets passed into the data for an AMChart just underneath the javascript it question. I actually have the alert right underneath it and it does not show. – inicDominus Nov 10 '15 at 02:36
  • That's because AJAX is asynchronous. You're trying to use `tempString` before it has completed. This is explained in the duplicate question I linked to. – Barmar Nov 10 '15 at 02:37
  • Everything that requires the response needs to be done in the callback. – Barmar Nov 10 '15 at 02:38
  • @Barmar Thank you so much! – inicDominus Nov 10 '15 at 02:39

0 Answers0