1

Hi I am new to PHP and javascript, am unable to send a variable from Javascript to PHP page. My Javascript code is separate .js file where I have declared a variable count which incremented at each correct answer that user gives. I wanted to pass this data to PHP page so that I can save it to database.

I have tried ajax post method and session storage but nothing seems to be working.

Is the below function correct for post data from JS to PHP?

function score(){
$.post("score_db.php",
{
  score:count

},
function(data){
  //
});
}

Any help will be appreciated.

3 Answers3

0

Using AJAX

$.ajax({
        url: 'score_db.php',
        type: 'POST',
        data: {score:count},
        success: function (data) {


        }

Refer

Pass Javascript variable to PHP via ajax

Community
  • 1
  • 1
Sridhar R
  • 20,190
  • 6
  • 38
  • 35
0

Please try this. Here you can send data to php file { score:count }.

   function score(){
    $.post( "score_db.php", {  score:count })
    .done(function( data ) {
        alert( "Success" + data );
     });

   }

Docs Link for more information

http://api.jquery.com/jQuery.post/

Maz I
  • 3,664
  • 2
  • 23
  • 38
0

send data from jquery like this...

    function score(){
    $.post( "score_db.php", {  score:count })
    .done(function( data ) {
        alert( "Success" + data );
     });
    }

in php file

  if(isset($_POST['score']))
    echo $_POST['score']; //it will print jquery count variable
  else
    echo "nothing";
Kalpit
  • 4,906
  • 4
  • 25
  • 43