I'm trying to echo PHP variable $last_id
to AJAX to pass it onto PHP $_POST
. May be I can skip AJAX all together and just transfer variable inside $_POST
. Do I have to use echo json_encode
?
Here is my code to see what I'm trying to accomplish here (any help appreciated):
registration.php
<?php
if(isset($_POST['submit'])) {
require 'connect.php';
$sql = "INSERT INTO table (username, password) VALUES ('".$_POST["username"]."','".$_POST["password"]."')";
if (mysqli_query($con, $sql)) {
$last_id = mysqli_insert_id($con);
echo $last_id;
?>
myScript.js
// ----AJAX Post to PHP----->
function ajax_post(ele,div){
// XMLHttpRequest object
var hr = new XMLHttpRequest();
// variables send to PHP file
var url = "insert.php";
var userId = "<?php echo $last_id; ?>";
var vars = "userId="+userId;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
}
insert.php
<?php
require 'connect.php';
$userId = $_POST['userId'];
$sql = "INSERT INTO table2 (userId)
VALUES ('$userId')";
?>