0

My code is doing the following (note all HTML, JavaScript and PHP code is on the same file):

A form is used for entering data and is validated by PHP. The PHP gets JSON data from a Google API and sends it to JavaScript . A JavaScript function parses the JSON and displays the required fields in a table.

I want to call the JavaScript function from PHP after getting the JSON but when I call it from PHP , console displays function not defined. The same code works when I call the function from an HTML button. I have tried defining the function before the PHP script, after it, in the head, basically everywhere. When I define it in the head with my other JavaScript functions the other functions also get function not defined error.

The JavaScript function:

    function generateTable() {
        var placejs = <?php echo json_encode($placesresponse); ?>; //getting the json from php
        var pjs = JSON.parse(placejs);
        var body = document.getElementsByTagName("body")[0];
        var tbl = document.createElement("table");
        var tblBody = document.createElement("tbody");
        var results = pjs.results;
        //Outputing the headers
        var row = document.createElement("tr");
        var thead = document.createElement("th");
        var headtext = document.createTextNode("Category");
        thead.appendChild(headtext);
        row.appendChild(thead);
        thead = document.createElement("th");
        headtext = document.createTextNode("Name");
        thead.appendChild(headtext);
        row.appendChild(thead);
        thead = document.createElement("th");
        headtext = document.createTextNode("Address");
        thead.appendChild(headtext);
        row.appendChild(thead);
        tblBody.appendChild(row);
        //outputting the values
        for (var i = 0; i < results.length ; i++) {
            row = document.createElement("tr");
            var curresult = results[i];
            var result_keys = Object.keys(curresult);
            for (var j = 0; j < result_keys.length ; j++) {
                var cell = document.createElement("td");
                var cur = result_keys[j];
                if(result_keys[j] == "icon")
                {
                var im = document.createElement("img");
                im.setAttribute("src",curresult[cur]);
                cell.appendChild(im);
                row.appendChild(cell);
                }
                if(result_keys[j] == "name")
                {
                var cellText = document.createTextNode(curresult[cur]);
                cell.appendChild(cellText);
                row.appendChild(cell);
                }
                if(result_keys[j] == "vicinity")
                {
                var cellText = document.createTextNode(curresult[cur]);
                cell.appendChild(cellText);
                row.appendChild(cell);
                }
            }
            tblBody.appendChild(row);
        }
        tbl.appendChild(tblBody);
        body.appendChild(tbl);
        tbl.setAttribute("border", "1");
        tbl.style.marginLeft = "auto";    
        tbl.style.marginRight = "auto"; 
        tbl.style.borderCollapse = "collapse";
    }

The part in PHP where I am calling this:

    $placesurl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=$latitude,$longitude&radius=$radius$type&keyword=$keyword&key=$placeskey";
        $placesresponse = file_get_contents($placesurl); //getting the json
        $placesjson = json_decode($placesresponse,true);
        if($placesjson['status']=="ZERO_RESULTS"){
            echo '<script>';
            echo 'noresult();';
            echo '</script>';
        }
        else{
            echo '<script>';
            echo 'generateTable();'; //function call
            echo '</script>';

        }

This is an assignment and I have to follow guidelines so I cannot just generate the table from PHP. Also I cannot use jQuery for the same reason. Any help would be appreciated, I am new to this stuff.

edit:

1) Sorry for not posting this earlier, the console shows this one extra error: "SyntaxError: expected expression, got '<'" for the line where i assign the json to the javascript variable:

    var placejs = <?php echo json_encode($placesresponse); ?>;

2) I tested a little bit more and its clear that whatever function i define inside the same script tags as generateTable() is also shown as undefined in the console. And the script tag is placed before the function call.

twk001
  • 1
  • 3
  • have you tried this way `?> – Ahmed Sunny Mar 06 '18 at 08:11
  • @AhmedSunny — Why would that make a difference? – Quentin Mar 06 '18 at 08:56
  • There isn't enough information in the question to identify what the problem is. Try providing a [mcve] (with emphasis on "complete"). Make sure that you don't have any other errors that are reported before the "function undefined" error. (The function might be undefined because of a syntax error that is reported when the page loads). – Quentin Mar 06 '18 at 08:58
  • Sorry for not posting this earlier, the console says this one error before that : "SyntaxError: expected expression, got '<'" for the line where i assign the json to the javascript variable "var placejs = ;". I will try updating the code to be more complete as you say. – twk001 Mar 06 '18 at 20:05
  • I tested a little bit more and its clear that whatever function i define inside the same script tags as generateTable() is also shown as undefined in the console. And the script tag is placed before the function call. – twk001 Mar 06 '18 at 20:55
  • is it all in one page? can you post complete structure, just functions and calls, not extra stuff. i think your code in not in correct flow. – Ahmed Sunny Mar 07 '18 at 08:11
  • `placesresponse` isnt this already encoded? if so then in js func you dont need to json_encode. – Ahmed Sunny Mar 07 '18 at 08:14

3 Answers3

0

In javascript function must be defined before calls. Check your php result html.

0

You don't really have enough information here for me to give a definitive answer, and I'm not a php guy, so I can't speak to your php code, but it seems as if you're using php to inject a JSON object into a javascript variable. After doing that there should be no need to call JSON.parse. You should only do that if you need to convert a javascript string into a javascript object. You already have a javascript object. placejs should contain the object that you want to work with. If you use your browser's debug tools, you should see that that variable contains an object. There is no need to parse a javascript object, it's already an object.

Jesse
  • 915
  • 1
  • 11
  • 20
-1

You don't need this line:

var pjs = JSON.parse(placejs);

and this is because you're echoing a raw json object in the line before instead of a json string.

Popsyjunior
  • 185
  • 10
  • While this is a problem with the code in the question, it doesn't help with the problem that the question is asking about. – Quentin Mar 06 '18 at 08:59
  • I added it just to be sure but since you guys say it isn't needed I'll remove it. – twk001 Mar 06 '18 at 20:10