0

My php file has code look like this

<?php

    $connect = mysqli_connect("localhost","root","","surveytest");
    $query = '';
    $table_data = '';
    $filename2 = "employee_data.js";
    $data2 = file_get_contents($filename2);
    $array2 = json_decode($data2, true);


     foreach($array2 as $row) //Extract the Array Values by using Foreach Loop
              {
               $query .= "INSERT INTO survey(name, gender, designation) 
               VALUES 
               ('".$row["name"]."', 
               '".$row["gender"]."', 
               '".$row["designation"]."'); ";  // Make Multiple Insert Query 

               $table_data .= '
                <tr>
           <td>'.$row["name"].'</td>
           <td>'.$row["gender"].'</td>
           <td>'.$row["designation"].'</td>
          </tr>
               '; //Data for display on Web page
              }
              if(mysqli_multi_query($connect, $query)) //Run Mutliple Insert Query
        {
         echo '<h3>Imported JSON Data</h3><br />';
         echo '
          <table class="table table-bordered">
            <tr>
             <th width="45%">Name</th>
             <th width="10%">Gender</th>
             <th width="45%">Designation</th>
            </tr>
         ';
         echo $table_data;  
         echo '</table>';
              }  
    ?>

My javascript file has code look like this

var json =
 {  
  "items": [
    {  
     "name": "Rusydi",  
     "gender": "Male",  
     "designation": "System Architect"  
    },  

    {  
     "name": "Hakim",  
     "gender": "Male",  
     "designation": "Conservation worker"  
    }
 ]
 }

Hey! i am a beginner for javascript and JSON.
I try to add var json into mysql database.
Now i want to refer to this javascriptfile(var json) but it's don't work.

My purpose is try to stored this variable in mysql.
That's why i try to do like this.

var json = {
    questions: [
        {
            name: "name",
            type: "text",
            title: "Please enter your name:",
            placeHolder: "Jon Snow",
            isRequired: true
        }, {
            name: "birthdate",
            type: "text",
            inputType: "date",
            title: "Your birthdate:",
            isRequired: true
        }, {
            name: "color",
            type: "text",
            inputType: "color",
            title: "Your favorite color:"
        }, {
            name: "email",
            type: "text",
            inputType: "email",
            title: "Your e-mail:",
            placeHolder: "jon.snow@nightwatch.org",
            isRequired: true,
            validators: [
                {
                    type: "email"
                }
            ]
        }
    ]
};

This is full code. https://surveyjs.io/Examples/Library/?id=questiontype-text&platform=jQuery&theme=default

Survey
    .StylesManager
    .applyTheme("default");

var json = {
    questions: [
        {
            name: "name",
            type: "text",
            title: "Please enter your name:",
            placeHolder: "Jon Snow",
            isRequired: true
        }, {
            name: "birthdate",
            type: "text",
            inputType: "date",
            title: "Your birthdate:",
            isRequired: true
        }, {
            name: "color",
            type: "text",
            inputType: "color",
            title: "Your favorite color:"
        }, {
            name: "email",
            type: "text",
            inputType: "email",
            title: "Your e-mail:",
            placeHolder: "jon.snow@nightwatch.org",
            isRequired: true,
            validators: [
                {
                    type: "email"
                }
            ]
        }
    ]
};

window.survey = new Survey.Model(json);

survey
    .onComplete
    .add(function (result) {
        document
            .querySelector('#surveyResult')
            .innerHTML = "result: " + JSON.stringify(result.data);
    });

$("#surveyElement").Survey({model: survey});

or what should i do?

3 Answers3

0

Remove the "var json =" from your file and change the extension to ".json" instead of ".js".

Since your javascript file does not contain a valid JSON string it cannot be decoded by php.

employee_data.json

 {  
  "items": [
    {  
     "name": "Rusydi",  
     "gender": "Male",  
     "designation": "System Architect"  
    },  

    {  
     "name": "Hakim",  
     "gender": "Male",  
     "designation": "Conservation worker"  
    }
  ]
 }
Stefmachine
  • 382
  • 4
  • 11
0

Ok the problem as I see it is this:

//employee_data.js
var json =
{

And then you import that

$filename2 = "employee_data.js";
$data2 = file_get_contents($filename2);
$array2 = json_decode($data2, true);

JSON is not JavaScript code (strictly speaking), it's way to format or encode JavaScript objects as strings. (JavaScript Object Notation). So your file should start with { and not a variable setting. So you just need to remove that var json = bit.

If you check var_dump($array2); it will probably say NULL and if you check echo json_last_error_msg() right after doing json_decode it will probably say something like Syntax error invalid JSON etc..

This can be reproduced like this:

 var_dump(json_decode('var json={"foo":"bar"}', true)); 
 echo json_last_error_msg();

Output:

NULL
Syntax error

Sandbox

If you remove the var json = from my overly simple example, you get this:

array(1) {
   ["foo"]=> string(3) "bar"
}
No error

Cheers!

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
0

First, isolate the json data which immediately follows var json = and ends with } which is followed immediately by ;.

Then repair the json string by wrapping all of the keys in double quotes.

Finally, convert the data to an array so that you can perform your query process with the questions subarrays.

*Note, I DO NOT recommend that you use mysqli_multi_query() because it is unstable/insecure. I recommend that you use a prepared statement to INSERT your data. I will refrain from explaining this task because there are many, many examples of how to do this on StackOverflow.

Code: (PHP Demo) (Regex 1 Demo) (Regex 2 Demo)

if (preg_match('~^var json = \K{.*?}(?=;)~ms', $js_file_contents, $match)) {  // cut away extra
    $json = preg_replace('~^\s*\K\w+~m', '"\0"', $match[0]);  // quote-wrap the keys
    var_export(json_decode($json, true));  // convert json string to array and display
}

Output:

array (
  'questions' => 
  array (
    0 => 
    array (
      'name' => 'name',
      'type' => 'text',
      'title' => 'Please enter your name:',
      'placeHolder' => 'Jon Snow',
      'isRequired' => true,
    ),
    1 => 
    array (
      'name' => 'birthdate',
      'type' => 'text',
      'inputType' => 'date',
      'title' => 'Your birthdate:',
      'isRequired' => true,
    ),
    2 => 
    array (
      'name' => 'color',
      'type' => 'text',
      'inputType' => 'color',
      'title' => 'Your favorite color:',
    ),
    3 => 
    array (
      'name' => 'email',
      'type' => 'text',
      'inputType' => 'email',
      'title' => 'Your e-mail:',
      'placeHolder' => 'jon.snow@nightwatch.org',
      'isRequired' => true,
      'validators' => 
      array (
        0 => 
        array (
          'type' => 'email',
        ),
      ),
    ),
  ),
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136
  • Thank you but now i can do it with myself ^^ –  Oct 25 '18 at 09:34
  • Posted questions deserve a system recognized resolution. Please mark the answer that you feel is best with the green tick. When you gain the privilege, please upvote answers that you find helpful. – mickmackusa Oct 25 '18 at 09:43