简体   繁体   中英

Specific problem passing javascript variable from work.php page to index.php page

Hey guys I have this page work.php with html and javascript codes and the form refers to index.php page. Also I am trying to pass the variable counter from my javascript to the index.php page. It's not working at all. Can you please have a look? I can't seem to figure out the issue.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<form method="post" action="index.php" enctype="multipart/form-data">
<div id=parent_div>
<button  type="button" id="add_step" > Add step!</button>

<input type='submit' name='submit'>
<br/>
</form>
</div>
</body>
</html>
<script>


$(document).ready(function(e){


var counter=2;
function send_counter(counter) {
    $.ajax({
      url   : "index.php", 
      type  : "POST",
      cache : false,
      data  : {
        counter : counter
      }
    });
  }
});
</script>

And here is my index.php page:

<?php



if (isset($_POST['submit'])){
$counter=$_POST['counter'];
echo "$counter";

}
?>

You are only passing the variables you mention in the data parameter

function send_counter(counter) {
    $.ajax({
      url   : "index.php", 
      type  : "POST",
      cache : false,
      data  : { counter : counter }
    });
  }
});

So only counter so $_POST will only contain that one array occurance, $_POST['counter'] .

So change the PHP to look for that

<?php
if (isset($_POST['counter'])){
    $counter=$_POST['counter'];
    echo "$counter";
}
?>

Or you could add a submit to the data object.

function send_counter(counter) {
    $.ajax({
      url   : "index.php", 
      type  : "POST",
      cache : false,
      data  : { counter : counter, submit: 1 }
    });
  }
});

and change the PHP back to

<?php
if (isset($_POST['submit'])){
    $counter=$_POST['counter'];
    echo "$counter";
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM