Sending PHP Array in Javascript

Hi, I created an array in PHP. And I need to get this array in javascript function. This is what I tried.

$GetTheValidationRule=mysqli_query($con,"SELECT * FROM Questions WHERE Form_ID='$FormID' AND QuestionsDataHave='YES' ORDER BY Questions_ID+0, Questions_ID"); $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 it gives me an error like this

  SyntaxError: syntax error var P= <br /> 

It is not possible to get an array in this way. Please help me.

UPDATE: this is the final message about my error

  <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> 
+6
source share
5 answers

The problem is that the $ValidatinArray variable in the file is not available, which prints javascript code. Perhaps this manual page will help you:

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

0
source

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

Also, using a form is not a good idea, because if you have more than one form and form, this is a global name. For forms, you must give it a unique form name, such as "myForm", so that you can target this particular form.

Hope this helps

0
source

Sorry for the late reply ... Try rewriting the document.ready document 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
source

Try the following:

 <?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 just echo js using php.

0
source

In php json_encode, an 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); }); }); 
-1
source

All Articles