0

Javascript function which pass parameter into a php function. My javascript code is below

function add_card(card_listt,card_number){  
   var card = card_listt;
   var num = card_number;
   //document.write(card+num);
   for (var i = 0; i < num; i++) {
      var avrl = "http://192.168.27.123/?Command=add:"+card[i]+","; 
      document.write('<?php get_data($avrl); ?>'); // Here is Problem
      document.write('<?php add(1,2); ?>'); //It works fine If I use  
   }
}

my php function is below. when I use only document.write('<?php add(1,2);?>'); function then it works properly. But when I use document.write('<?php get_data($avrl); ?>'); function then it does not works.

<?php

    function get_data($url) {
       $curl_handle=curl_init();
       $timeout = 20;
       curl_setopt($curl_handle, CURLOPT_URL,$url);
       curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
       curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
       curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Welcome');
       $data = curl_exec($curl_handle);
       //return $data;
       echo $data;
   }

   function add($a,$b){
      $c = $a + $b;
      echo $c;
   }

?>
  • 2
    @M Sumon You cannot call a php function like that. `avrl` is a javascript variable not a php variable. – Ayush Feb 26 '17 at 05:47
  • Read about **AJAX**! – ibrahim mahrir Feb 26 '17 at 05:48
  • document.write(''); it works fine. But it's above not working. –  Feb 26 '17 at 05:49
  • Check this link http://stackoverflow.com/questions/1917576/how-to-pass-javascript-variables-to-php – Ayush Feb 26 '17 at 05:50
  • @MSumon `document.write('');` this works fine because the values are static. You cannot pass a variable from javascript to PHP. Javascript is client side and PHP is server side. Use ajax to send data to server side. – Ayush Feb 26 '17 at 05:51

2 Answers2

0

Use $_GET append your value to the url like http://www.example.com/someurl?myvar=myvalue in this case your url should be http://www.example.com/someurl?avrl=myvalue.

Then replace your document.write('<?php get_data($avrl); ?>'); with document.write('<?php get_data($_GET['avrl']); ?>');

Hasan Bayat
  • 926
  • 1
  • 13
  • 24
-1

Try read this or this, but i strongly recommend you to begin use jQuery, you can do such things with it not wasting time writing huge amount of code, for example here

Vasilij Altunin
  • 754
  • 1
  • 5
  • 18