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.

2

3 Answers 3

0

Using AJAX

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


        }

Refer

Pass Javascript variable to PHP via ajax

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

Comments

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/

Comments

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";

Comments

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.