-1

I am novice in Programming and searching answer for the below problem in this site over days but couldn’t figure anything yet.

Firstly, A input form will prompt to the user, then the user will define how many rows there will be.
Then in the HTML table, each rows has 3 input fields(ID, Name, Number). When a user gives an ID, the name and number of that ID will be placed in the next input fields of that row. For better understanding I am attaching an img. demo_img.png

studentInfo.php page, Ajax response will set here:

<form class="" action="" method="POST">
 <?php
   $count = $_REQUEST["countID"]; //<--get the number from the user
   for($i=1; $i<=$count; $i++){
 ?>
 <tr>
   <td>
     <input type="number" name="id[]" class="id">
   </td>
   <td>
     <input type="text" name="fname[]" class="fname">
   </td>
   <td>
     <input type="number" name="num[]" class="num">
   </td>
 </tr>
 <?php
   }
 ?>
</form>

The Ajax portion:

$(".id").change(function(){
  var sid = $(this).val();
  $.ajax({
    method: "GET",
    url: "getData.php",
    data: {sid: sid},
    dataType: "json",
    success: function(data, textStatus, jqXHR){
      if(data.length == 0){
        alert("No data found");
      } else {
        // I am stuck here. If I console.log(data) the JSON format coming from getData.php is showing like this: {name: 'JACKS DONUTS', num: '185'}
      }
    },
    error: function(jqXHR, textStatus, errorThrown) {
      //Show the error msg
    }
  });
});

Now, How do I set the result to the input fields.
Any suggestion in my code will be greatly appreciated. Thanks in advance.

Hasib Hosen
  • 27
  • 1
  • 7
  • `id` attributes **must** be unique so adding multiple elements in the loop violates that uniqueness principle and any javascript code that relies upon `id`s will fail – Professor Abronsius Aug 05 '22 at 06:30
  • Your SQL is vulnerable to SQL Injection because of the use of request variables being used directly rather than using a prepared statement with bound parameters. – Professor Abronsius Aug 05 '22 at 06:32
  • Your HTML is invalid- there are no `table` element tags so you cannot simply add table-rows to a form – Professor Abronsius Aug 05 '22 at 06:39
  • Remove the duplicate IDs, and work with class names instead. Use the relationship the elements have in the DOM, to find the correct input fields you need to populate - from the current element that your event occurred on, go up to the parent `tr` element (`parents()` method), and then find the input fields within that one using their class (using `find()`). – CBroe Aug 05 '22 at 07:48
  • Can you print response what u get when u do echo json_encode($result); – Jaymin Aug 05 '22 at 07:51
  • @ProfessorAbronsius Great observation. Some how I missed that out. As for now I don't need the ID attribute, so I will remove that. And in future if I need ID attribute, then I will append the ID with my counter variable-'i' like this: "; ?> – Hasib Hosen Aug 05 '22 at 11:02
  • @ProfessorAbronsius I found out on google that, in PHP **"mysqli_real_escape_string()"** function can sanitize the input, which will avoid the SQL injection. So I am going to use this function. – Hasib Hosen Aug 05 '22 at 11:02
  • @Jaymin The JSON preview is like this: {name: "JACKS DONUTS", num: "185"} – Hasib Hosen Aug 05 '22 at 11:03
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Aug 05 '22 at 11:14
  • @CBroe Your idea helps me, Thanks – Hasib Hosen Aug 09 '22 at 02:31

1 Answers1

0

Your requirement can be achieve by post an array of IDs to an URL e.g. getData.php using ajax.

['1001', '1002', '1003']

Then the getData.php will return an array of student data with ID as key.

{
  "1001": {
    "name": "Student A",
    "number": 20
  },
  "1002": {
    "name": "Student B",
    "number": 21
  },
  "1003": {
    "name": "Student C",
    "number": 23
  }
}

Once you retrieved the student data, try to look for the student data by using the input ID as key, if the data exists, append the data to the form.

if (data[inputId]) {
    const studentData = data[inputId];
    /* following methods will find input with class name and set the input value with given value */
    setValue('name', studentData.name);
    setValue('number', studentData.number);
}

Following is the SAMPLE by post the IDs to an API placeholder URL and SIMULATE the return data:

/* bind click event to buttons */
$(document).ready(function() {
  $("#add-row").click(addRow);
  $("#get-data").click(getData);
});

/* add extra row for input ID */
function addRow() {
  $rowHtml = `
    <tr class="student-data">
      <td><input type="text" class="id" name="id[]" /></td>
      <td><input type="text" class="name" /></td>
      <td><input type="text" class="number" /></td>
    </tr>
  `;

  $("#form-table").append($rowHtml);
}

/* get data when user submit */
function getData() {
  const fieldset = $('#fieldset')
  const message = $('#message')
  const inputs = $(`input[name="id[]"]`)

  /* get multiple ids as array where which by the user */
  const ids = inputs.toArray().map(function(input) {
    return input.value
  })

  /* store ids in a data object */
  const dataToSubmit = {
    ids: ids
  }

  /* url to post to submit the data e.g. "getData.php" */
  /* following is just a demo url */
  const url = "https://jsonplaceholder.typicode.com/posts"

  $.ajax({
    method: "POST",
    url: url,
    data: dataToSubmit,
    dataType: "json",
    beforeSend: function() {
      /* disable the form when submitting */
      fieldset.prop("disabled", true);
      message.html('Getting data...');
    },
    success: function(data, textStatus, jqXHR) {
      /* your data should return an array of objects with the key is the id */
      /* e.g. {1001: {name: "Student A", number: 20}, 1002: {name: "Student B", number: 21},…} */

      /* THIS IS NOT PART OF THE CODE! this is just a simulation of fetching the data */
      data = JSON.parse(`{"1001":{"name":"Student A","number":20},"1002":{"name":"Student B","number":21},"1003":{"name":"Student C","number":23}}`);

      /* fill the student data once retrieved data  */
      fillStudentData(data);
    },
    complete: function() {
      /* enable back the form after form was submitted */
      fieldset.prop("disabled", false);
      message.html('');
    }
  });
}

function fillStudentData(data) {
  $('.student-data').each(function() {
    /* get the id by find the input with "id" class */
    const inputId = $(this).children().find(".id")[0].value;

    /* get student data using id key */
    const studentData = data[inputId];

    /* set the name and number if there is data found */
    if (studentData) {
      /* this function will find the inputs in "student-data" class and filled the input with value */
      const setValue = (className, value) => {
        $(this).children().find("." + className)[0].value = value;
      };

      setValue('name', studentData.name);
      setValue('number', studentData.number);
    }
  })
}
<form style="display: flex;">
  <fieldset id="fieldset">
    <table id="form-table" border="1" cellpadding="10">
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Number</th>
        </tr>
      </thead>
      <tbody>
        <tr class="student-data">
          <td><input type="text" class="id" name="id[]" /></td>
          <td><input type="text" class="name" /></td>
          <td><input type="text" class="number" /></td>
        </tr>
      </tbody>
    </table>
    <span>Sample ID: 1001, 1002, 1003</span>
    <button type="button" id="add-row">Add Row</button>
    <button type="button" id="get-data">Get Data</button>
    <span id="message"></span>
  </fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Stern Chen
  • 303
  • 1
  • 8