-1

I have a function

function getCalendarData(){
   ob_start();
   echo "<script type='text/javascript' src='http://splocal/courses/calendar.js'></script>";
   $calendarAry = ob_get_contents();
   print_r($calendarAry);
   return $calendarAry;
 }

here i am trying to assign the return value of js call to a variable . but its not working.

what is the correct way of doing it?

calender.js file 


    function returnCalenderArray(data){
        console.log(data);
        document.write(data);
        return data;

    }


    $.ajax({
         type: "GET",
         url: "http://localhost:8080/privateTraining/getTrainingsJson",
         data: { ListID: '1'},
         dataType: "jsonp",

         success: function(data) {
         alert('Hi'+data);
         returnCalenderArray(data);
      }
});  
maaz
  • 3,534
  • 19
  • 61
  • 100

2 Answers2

0

Technically, you can't call PHP from JavaScript, at least not on the same page. PHP is a server-side only language, JS is client-side. The only way to call a PHP script from a JS function is to open a new page in the background (not displayed to the browser) and do it this way. It is called AJAX and I suggest you to take some interrest in this technology.

For very easy ways to use AJAX, use a JS framework, such as jQuery.

SteeveDroz
  • 6,006
  • 6
  • 33
  • 65
-1

You could try constructing the javascript with PHP. this will allow you to load executable content instead of static. To do this, first you'll nee a javascript function to load the php into a script element. something like :-

function loadscript(src){
       var myscript = document.createElement('script');
       myscript.src = src;
       document.getElementByTagName('head')[0].appendChild(src);
}

you can then write php variables to a constructed JS code then load the php by calling the function in the browser. The PHP would be somthing like this.

on the server myphpcode.php

<?php
$sessionid = $_SESSION['user_id'];
?>
mydiv.innerHTML = 'User ID ' + <?php echo $sessionid; ?>;   

js call in HTML page

loadscript('myphpcode.php');

use the same method to send data back to the server via PHP by constructing a valid query string in javascript to apppend to the loadscript call.

var a = 'some data';
var b = 'some more data';
var urlstring  = 'myphpcode.php?a=' + a + '&b=' + b;
loadscript(urlstring);

you can then store the javascript variables in a database for example by writing a function in myphpcode.php.

<?php
include mydbconnection.php  // some database connection code
if ((isset $_GET["a"]) && (isset $_GET["b"])) { //check the url query string has data 
   $a = $_GET["a"];
   $b = $_GET["b"];
   $query = "INSERT into mydatabase.mytable (columnA, columnB)
             VALUES ('" . $a . "','" . $b . "');";
   if ($mysqli->prepare($query)){
       $mysqli->execute();
   }
}
?>
Paul Nelson
  • 137
  • 4