Skip to content Skip to sidebar Skip to footer

Use Javascript Array On Php Function Be It On The Same File Or On Another Along With Other Functions

I know this question has been asked multiple times but I still have not found an answer to the specific problem I am facing. I am creating a web page and whenever a user clicks a s

Solution 1:

The answer to the question is: No. You can't use a variable from Javascript inside PHP. You can generate valid Javascript code with PHP, but not the other way around. The reason is that PHP is processed in the server side, while Javascript is processed on the client side (the browser)

NOTE: You can process Javascript on the server side as well using Node, but you are already using PHP. How to use server side javascript with NodeJs is out of the scope of the question.

Now, you can create that table with PHP, and not use JS at all. I'm assuming your data is in an array format, so look into PHP loops like foreach. Then build a table by echoing (see echo('')) the table tags (table, thead, tbody, td, tr, etc).

Solution 2:

You can't use a variable from Javascript inside PHP

because

Javascript (Client side) and PHP (Server Side)

So in current context what you can do is as follows

Client Side

functionactualizarCostos(array){
            if(array.constructor === Array){
               // Here you need ajax

              $.post('http://myhost.mydomain.com/update_cost.php',
                     { table_data : array }, function(response){
                              // do something after getting response
                   });
            }else{
                alert("Input must be array");
            }
        }

Server Side (update_cost.php)

<?phpfunctionupdateCosts($item)
        {
             // do something here...
        }

        if(isset($_POST['table_data']))
        {
               foreach($_POST['table_data'] as$index => $item)
               {
                      // do something here 
                      updateCosts($item);
               }

               // Response back - if neededecho json_encode(array('status'=>true, 'msg'=>'Some Message'));
        }
?>

Post a Comment for "Use Javascript Array On Php Function Be It On The Same File Or On Another Along With Other Functions"