1

I want to access javascript variable inside PHP. How Can I do this?

below is my javascript onClick of button I am getting value in alert.

$(".check").click(function(){
  var priceee = document.getElementById("total-price").value;
  //alert(priceee);
});
techiva.blogspot.com
  • 1,170
  • 3
  • 17
  • 37

2 Answers2

0
Try below to send the JS data to PHP via AJAX,

  $.ajax({
   type: 'POST',
   url: 'yourphppage.php',
   data: { 
      'totalprice' : $("#total-price").val(), 
   },
   success: function(response){
   }

  })

In yourphppage.php,

  echo $_POST['totalprice'];
user3040610
  • 750
  • 4
  • 15
0

You can use an AJAX call to perform this either using the POST or GET Method as said by phpuser. For this to work you must be running it on a server so either on your local machine (localhost) using something like XAMPP or on an actual server.

Here is an example on how to write it.

$(function () {
$(".check").click(function(){
    var priceee = $("#total-price").val();

});
$.ajax({
    type: 'POST',
    url: 'file.php', //your php page
    data: {
        price: pricee
    },
    success: function (response) {
        //the code you want to execute once the response from the php is successful
    },
    error: function () {
        //error handling (optional)
    }
});

});

Your PHP page (in this example file.php)

<?php

if (isset($_POST['price'])) {
    $price = $_POST['price'];
    //now your variable is set. as $price in php
    echo $price; //returns price as response back to jQuery
}

Hope this helps, more information in the jQuery Ajax call documentation (http://api.jquery.com/jQuery.ajax/)

Spalqui