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);
});
6

2 Answers 2

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'];
Sign up to request clarification or add additional context in comments.

2 Comments

Your Suggestion Works ...Thank you Man
@webmenstor, Glad it helps
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

1 Comment

There are shorter ways of writing the AJAX call by using the get() or post().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.