6

I have created an array in PHP. And I need to get that array into a javascript function. This is what I have tried.

$sql = "SELECT * FROM Questions WHERE Form_ID='$FormID' AND QuestionsDataHave='YES' ORDER BY Questions_ID+0, Questions_ID";
$GetTheValidationRule = mysqli_query($con, $sql);
$ValidatinArray = array();
$J = 0;
while($RowVal = mysqli_fetch_array($GetTheValidationRule)){
    $ValidatinArray[$J] = $RowVal['Validation_Type'];
    $J++;
}

And This is my javascript code.

$(document).ready(function() {
    $("form").submit(function(){
    var P= <?php echo json_encode($ValidatinArray); ?>;
        var O = P.length;
        alert(O);
        return false;
    });
}); 

But this gives me an error like this

 SyntaxError: syntax error
 var P= <br />

Isn't it possible to get the array in this way. Please someone help me.

UPDATE: This is the final out put of my error message

<script>
    $(document).ready(function() {
        $("form").submit(function(){
            alert('AAAAAAAAAAAAAAAAAAA');
            var IDsOfTheColumns = document.getElementsByName("DataColumnID[]");
            var Data = document.getElementsByName("DataInputValue[]");
            var A = IDsOfTheColumns.length;
            alert(A);
            <br />
            <b>Notice</b>:  Undefined variable: ValidatinArray in <b>C:\xampp\htdocs\PHIS\CreateTheForm.php</b> on line <b>16</b><br />
            var P = null;   return false;
        });
    });
</script>
Bhavik Hirani
  • 1,996
  • 4
  • 28
  • 46
t4thilina
  • 2,097
  • 3
  • 18
  • 19
  • Is that JavaScript code inside of a PHP file? – Justin Wood Dec 18 '13 at 01:46
  • 1
    I do not believe `echo json_encode($ValidatinArray);` results in a bare `
    `. Is there any processing later on going on there?
    – Wrikken Dec 18 '13 at 01:47
  • 1
    @Wrikken - that `
    ` appeared after @thefourtheye's edit to highlight his code, I assume it came from SO's WYSIWYG
    – scrowler Dec 18 '13 at 01:48
  • 1
    What is the raw result when you click "view html source" in browser – Rezigned Dec 18 '13 at 01:49
  • 3
    Is the location of the PHP and JavaScript on the same page, in your top example? You do know you don't have to assign `$ValidatinArray = array()`, or increment it inside a loop. You can just do `$ValidatinArray[] = $RowVal['Validation_Type'];`, forgetting `$J` and defining as `= array();`. – StackSlave Dec 18 '13 at 01:50
  • @ Justin Wood nd PHPglue: Yes it is. – t4thilina Dec 18 '13 at 01:51
  • 1
    @t4thilina can you try ``var_dump(json_encode($ValidatinArray));`` and show me the result – Rezigned Dec 18 '13 at 01:51
  • So you have php code in a file with `.js` extension? – zerkms Dec 18 '13 at 01:52
  • @scrowler: nope, it was already in the original question (see the _source_), and the OP answered to a now deleted erroneous answer about quoting (you weren't the only one) _"unterminated string literal var P= '
    Npe then the error shows me like this"_ ... which leads me think it's actually there...
    – Wrikken Dec 18 '13 at 01:55
  • @Rezigned: string(289) "["No validation","No validation","No validation","No validation","No validation","No validation","No validation","No validation","No validation","No validation","No validation","No validation","No validation","No validation","No validation","No validation","No validation","No validation"]" – t4thilina Dec 18 '13 at 01:57
  • 1
    Is it double quote issue? – Vicky Gonsalves Dec 18 '13 at 01:58
  • Have you tried: – Jonathan Dec 18 '13 at 02:03
  • What does this mean. Do I need to write it in replacing the Json? – t4thilina Dec 18 '13 at 02:06
  • Why is it ValidatinArray and not ValidationArray? Are you sure you call it the same thing in both places? – JAL Dec 18 '13 at 02:12
  • @t4thilina I can't see how the code snippets you provided fit together. Can you please confirm your code looks like [this gist](https://gist.github.com/simonrobb/8016325)? – Simon Robb Dec 18 '13 at 02:22
  • Might sound stupid but why don't you want to use json combined with ajax on the JS ? You are doing a sql query it sounds like the way to go. – zipp Dec 18 '13 at 05:29
  • Possible duplicate of [PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef) – miken32 Mar 23 '17 at 04:18
  • Try this : `var P = ;` – Bhavik Hirani May 28 '20 at 18:42
  • I don't understand the number of upvotes here! it's just a simple mistake for undefined variable – Ali Akbar Azizi May 29 '20 at 01:09

6 Answers6

1

Sorry for the late response...Try rewriting your document.ready as:

$(document).ready(function() {
    $("form").submit(function(){
    var P = JSON.parse('<?php echo json_encode($ValidatinArray); ?>');
        var O = P.length;
        alert(O);
        return false;
    });
});
0

The problem is, that in the variable $ValidatinArray is not available in the file, that prints the javascript code. Maybe this manual page helps you:

http://www.php.net/manual/en/language.variables.scope.php

stofl
  • 2,950
  • 6
  • 35
  • 48
0

Your tag is coming from the form that you are submitting. check what your form data is before you encode it to verify the output. you can use console.log($("form));

Also using form is not a good idea since if you have more than one form and form is a global name. For forms you should give it a unique form name like "myForm" so that you can target that specific form.

Hope this helps

0

Try this:

<?php


    echo   ' <script>
             $(document).ready(function() {
                                $("form").submit(function(){
                                var P= '. json_encode($ValidatinArray) . ';
                               var O=P.length;
                                 alert(O);
                               return false;
                          });
                   }); 
               </script>';

?>

What you do is simply echo the js using php.

The Oracle
  • 2,373
  • 3
  • 26
  • 44
0

first of all I recommend that you verify that the variable $ValidatinArray exists and that it is being passed correctly to the file where you are doing the "echo".

the error you show indicates that from the beginning the variable that contains the array does not exist. if the SQL query is inside a php function check that you are returning the variable. example

<?php 

  function GetData(){
   // ... here is the code to get the information from the database ...
   return $ValidatinArray;
  
  }

  $ValidatinArray = GetData();
?>

once you have validated that this array exists we can now see the problem of passing the data to JavaScript:

It all depends on how the structure is, if you have the PHP code and the JavaScript function in the same file you can simply use this method inside the php fil:

// ... php file code
?>
    <script>
      $(document).ready(function() {
       $("form").submit(function(){

       // you can use any of the two methods that I leave you here
       // Using only json_enconde
       var P= <?= json_encode($ValidatinArray) ?>;

       // Using json_enconde to pass the array as a string and using JSON.parse to have JavaScript convert it to an object
       var P= JSON.parse('<?= json_encode($ValidatinArray) ?>');

       var O = P.length;
       alert(O);
       return false;
      });
     });
    </script>

In case the php file is executed at the moment of opening the page and the file that contains your function in JavaScript is in another file:

You can generate a "global" JavaScript variable from the php code as follows

 // ... code php file
 ?>
 <script>
     window.variablename = <?= json_encode($ValidatinArray) ?>
 </script>
 <?php

inside your JS file you can receive the array like this

$(document).ready(function() {
    $("form").submit(function(){
       var P= window.variablename ;
       var O = P.length;
       alert(O);
       return false;
    });
  });

PD: using <?= is equivalent to using echo

Webdeveloper_Jelle
  • 2,868
  • 4
  • 29
  • 55
Yopa
  • 26
  • 1
-1

In php json_encode the array like this:

$inlinejs='';
$inlinejs.='var validatinArray=\''.addslashes(json_encode($ValidatinArray)).'\';'."\n";
$inlinejs.='var validatinArray=eval(\'(\' + validatinArray + \')\');'."\n";

and in javascript:

$(document).ready(function() {
    $("form").submit(function(){
    <?php echo $inlinejs; ?>
    console.log(validatinArray);
    });
}); 
joHN
  • 1,765
  • 3
  • 15
  • 31
  • `eval()` in JavaScript is not the recommended was to parse JSON data! See [How to parse JSON in JavaScript](http://stackoverflow.com/a/4935684/2594742) for the better way. – AeroX Jan 20 '14 at 12:13