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')";
?>
Hi this is how you can pass php variable into external js file,
<?php
$last_id= "Red";
?>
<script type="text/javascript">var color = "<?= $last_id?>";</script>
<script type="text/javascript" src="myscript.js"></script>
Try and let me know
As your posted code you are missing hr.send(vars)
and as I am seeing your $last_id
is coming after registration. So i suggest you to store that value in session then use and after ajax call destroy the session if needed.
<?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);
session_start();
$_SESSION['last_id'] = $last_id;
?>
// ----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 vars = "userId=<?php echo $_SESSION['last_id']; ?>";
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;
}
}
}
hr.send(vars);