简体   繁体   中英

PHP function call and array passing in Javascript code

Pls help..

I have a dynamic form in which the no. of elements are not fixed, and i need to perform JS validation on the form. I have a PHP function that will return me an array of all elements that are currently displayed in form. I want to use this in the JS code..

I am trying something lyk dis::

function checkValidation() {

  <?php echo  
    // php function call
    $arrColumnsInfo = $this->fetch_fields_info();
    print('<pre>');
    print_r($arrColumnsInfo);
    print('</pre>');
  ?>
}

Not working for me..throws JS error.. OR this..

function checkValidation() {
  <?php=
    // php function call 
    $arrColumnsInfo = $this->fetch_fields_info();?>
    alert(<?=$arrColumnsInfo?>);
}

Again.. not working..

My PHP array output:

Array
(
[client_code] => Client Code::1::Basic company Info::desc::TB
[entity_name] => Entity Name::1::Basic company Info::::TB
[type_of_entity] => Type of entity::1::Basic company Info::Type of entity,Sole trader,Partnership,Australian Private Company, other::DD
[fixed_fees] => fixed fees::8::Fees Related::yes,no::RD
[billing_time] => Billing time::8::Fees Related::Weekly,Fortnightly,Monthly,Yearly::DD
)

The key here used is the name of form element.. eg. i am building my form lyk dis..

<input type="text" name="client_code" value="">... 

and so on.. and in the same way all form elements are dynamically created. And now i want to validate this form so i again need this array in javascript.

You could use json_encode to transform your PHP Array into a from that can be used by JavaScript.

function checkValidation() {
  var data = <?php echo json_encode($this->fetch_fields_info()) ?>;
  // ... run your client-side checks
  alert(data);
}

Just keep in mind, that you always have to provide valid JavaScript code. That can sometimes be quite tricky if you insist on writing that JavaScript code with inline PHP.

You should at least consider doing your validation on the server-side (in PHP) and only passing the result to your client.

your php code have to generate the result something like this:

var arr = <?php echo $arr; // result: [1,2,3,4,5,6,7] ?>

or the other array() format that support in JavaScript..

it is just an example.

take a look on the give link : Array in Javascript this link tells you that what format you need to use an Array.

data is not sufficient to help you @disha. please provide some more and edit this . also what is this '=' in you first line of php? provide some more details that someone can really help you. Happy coding!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM