-2

How to get javascript variable value in PHP and php value stored in to database.

if my JS code like

var age = new Date().getFullYear()-getYearInteger();

This code o/p 2016-(yearofbirth). I am getting output correct in JS. How to store this age value in MySQL database. How to call ajax function and insert the values?

1
  • 1
    Make an ajax call or submit the form and hit Insert query... Commented Nov 25, 2016 at 6:52

2 Answers 2

1

Send this javascript value through form or ajax submit method and get this value saved in Database.

You cannot directly get js values in Php.

A simple example is 
var age  = new Date().getFullYear()-getYearInteger(); 
$.ajax({
      url : '/save.php',
      type : "POST",
      data : {
                age    : age,
                saveAge    : true,
             },
      success : function(data)
      {
              data = JSON.parse(data);
              if(data.status == 1)
              {
                   window.location = 'index.php/dashboard';
              }
              else
              {                                

              }
       }    
});
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for response. i added the code but not stored in database. in save .php i added insert query but stored all age value as 0. can u explain that?
Can you please show me your code in save.php
@ Mukesh Swami I just write insert query <?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("numcalc", $con); $sql="INSERT INTO expression (id, age) VALUES ('','$age')"; if (!mysql_query($sql,$con)) { die('Error: ' . mysql_error()); } echo "your data added successfully"; mysql_close($con) ?>
0

In order to save JS value to a PHP variable you need to make a server call.

You can easily do the vice versa like this:

var jsVariable = '<?= $php_variable ?>';

Have an ajax call, send the data to server side and store it in a variable.

3 Comments

Thank you for your response. i have no knowledge in ajax. can u explain in detail?
@jeni just read your comment, did you check ajax? you can see this example stackoverflow.com/questions/2269307/…
Its not not working Please anybody help me. i added the above code in javascript page . how to insert into database. how to call ajax

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.