0

Background

I am a complete beginner to web designing and i am using PHP and mySQL.

Code in hand

This is my HTML file named UserRegistration.php

<?php
session_start();
?>
<html>
<body>
<script>
function FillRecord(Id)
{
     $.ajax({
     type: "POST",
     url: "Algorithm/UserRegistration-FillUserRecords.php",
     data:'Id='+Id,
     success: function(data)
     {
        document.forms["Frm_User"].elements["txtName"].value = "";
        document.forms["Frm_User"].elements["txtFName"].value = "";
        document.forms["Frm_User"].elements["txtMName"].value = "";
     }
     });
}
</script>
<form id="Frm_User" name="Frm_User" method="POST" action="Algorithm/UserRegistration-SaveDetails.php">
  <label for="txtName">Name</label>
  <input type="text" name="txtName" placeholder="Name" required>

  <label for="txtFName">Father Name</label>
  <input type="text" name="txtFName" placeholder="Father Name" required>

  <label for="txtMName">Mother Name</label>
  <input type="text" name="txtMName" placeholder="Mother Name" required>
</form>

<input type="button" onclick="FillRecord(1);">//1 is fixed at the moment
</body>
</html>

This is my PHP class named UserRegistration-FillUserRecords.php

<?php
session_start();

include_once 'Connection.php';

if ($dbcon->connect_error)
{
    die("Connection failed: " . $dbcon->connect_error);
    header('Location: ../UserRegistration.php');
    exit();
}

//Search data from database on all fields except "SNo"
//----------------------------------------------------------------------------
$sql =  "Select * from usertable where id=".$_POST["Id"];
$result = $dbcon->query($sql);

$rows = array();
foreach ($result as $RowRecord)
{
    $_SESSION['UserRegistration_txtName'] = $RowRecord["Name"];
    $_SESSION['UserRegistration_txtFName'] = $RowRecord["FName"];
    $_SESSION['UserRegistration_txtMName'] = $RowRecord["MName"];
}
exit();
?>

The Algorithm/UserRegistration-SaveDetails.php is used to save the user details into database which is working perfectly.

Problem

I want to show the data which is being retrieved by UserRegistration-FillUserRecords.php into UserRegistration.php's already created textbox when the function FillRecord is called but i have no clue as to how to assign the session variable value to my input boxes.

I Tried

1) alert(<?php echo $_SESSION['UserRegistration_txtName']; ?>); but the statement doesn't seem to work even when i have used

2) success: function(data) in AJAX reponse has the value which i need but when i echo it, it shows the value in continuation like:-

abc
----------------
a (Name)
b (Father Name)
c (Mother Name)

and i cant seperate it as the string can be anything, it can be full of comma's, new line characters and any special symbols

5
  • 1
    sidenotes: in foreach ($result.. you need to fetch the data/array from the result first. Usually done in a while($row = $result->fetch_row()) {.. (or fetch_assoc, fetch_array,..) Commented Jan 11, 2019 at 15:11
  • 2nd: in this foreach you overwrite $_SESSION['UserRegistration_txtName'] in each iteration, so only the last value will persist - this might be ok here, since you'd only expect one row anyway. Commented Jan 11, 2019 at 15:12
  • 1
    You really need to fix your SQL injection bug if you want this to work. See here acunetix.com/websitesecurity/sql-injection Commented Jan 11, 2019 at 15:13
  • @Jeff thanks for the hints but in my case it will just get 1 record so that wont be the issue but i will try to fix it too BUT can you tell me how to use the session variable in my case to show the value Commented Jan 11, 2019 at 15:15
  • You need to echo the values (no need for a session var here) you want to receive in ajax' data, best as json (use json_encode for that): echo json_encode($RowRecord);. Then you'll get an array in javascript's data Commented Jan 11, 2019 at 15:47

1 Answer 1

1

Your PHP code doesn't actually output those session variables you've created to the browser. To do that, you need something like this (I'm using JSON as the format in which to send the data, as it's easiest to work with on the receiving end).

foreach ($result as $RowRecord)
{
    $_SESSION['UserRegistration_txtName'] = $RowRecord["Name"];
    $_SESSION['UserRegistration_txtFName'] = $RowRecord["FName"];
    $_SESSION['UserRegistration_txtMName'] = $RowRecord["MName"];
}
// Create an array to send the data
$data = [
    'Name'  => $_SESSION['UserRegistration_txtName'],
    'FName' => $_SESSION['UserRegistration_txtFName'],
    'MName' => $_SESSION['UserRegistration_txtMName']
];
// Tell the browser that a JSON data file is coming
header('Content-type: application/json');
print json_encode($data);
exit();

Your jQuery AJAX handler function can then easily populate the form with these values:

function FillRecord(Id)
{
     $.ajax({
     type: "POST",
     url: "Algorithm/UserRegistration-FillUserRecords.php",
     data:'Id='+Id,
     dataType: "json", //Add this so data comes back as an Object
     success: function(data)
     {
        document.forms["Frm_User"].elements["txtName"].value = data.Name;
        document.forms["Frm_User"].elements["txtFName"].value = data.FName;
        document.forms["Frm_User"].elements["txtMName"].value = data.MName;
     }
     });
}

I hope I've correctly understood (and satisfied) what you want to achieve, please feel free to say if not.

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

2 Comments

Thanks it worked for me but i wanted to know that why wasn't i able to use the $_SESSION variable in the AJAX response as the value was set to the browser?
The browser doesn't automatically have any of the session variables unless you explicitly output them in your PHP code somehow (like how I've done in this answer, by printing them in the AJAX response). Otherwise, all the browser has is a session ID (which is sent as a cookie) to tell the server which session is yours. If those values are set before your page is loaded and aren't going to change, you could contain them in the page as Javascript variables, then change your FillRecord() function to just write them into the form when the button was clicked (then you wouldn't need AJAX).

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.