0

In my js file i am sending array of data to my php file and i want to print name in #NAME and password in #PASSWORD but i am getting both values name and password in #NAME and #PASSWORD, its something like this:

enter image description here

how i want it to print:

enter image description here

$("#name").keyup(function() {
  var form = $("#form").serialize();
  $.ajax({
    type: "POST",
    url: "index.php",
    data: form,
    success: function(data) {
      $("#NAME").html(data);
    }
  });
});

$("#password").keyup(function() {
  var form = $("#form").serialize();
  $.ajax({
    type: "POST",
    url: "index.php",
    data: form,
    success: function(data) {
      $("#PASSWORD").html(data);
    }
  });
});
<html>

<body>

  <form id="form" action="index.php" method="post">

    Name :
    <input type="text" name="name" id="name" /><span id="NAME">I want name here from index.php, but it returns both name and password</span>
    <br/>
    <br/>Password :
    <input type="password" name="password" id="password" /><span id="PASSWORD">I want password here from index.php, but it returns both</span>
    <br/>
    <br/>
    is there any other way of doing it in the same index.php file?

  </form>

  <script src="jquery.js"></script>
  <script src="js.js"></script>

</body>

</html>

1 Answer 1

1

Since you're sending the same form for both calls it would be easier to wrap it up into 1 call and handle both instances and return the data via an array.

PHP

$arr = array();
$arr[0] = "John Doe";
$arr[1] = "password";

echo json_encode($arr);
exit();

jQuery

$.ajax({
  type: "POST",
  url: "index.php",
  data: form,
  dataType: "json",
  success: function(data) {
    $("#NAME").html(data[0]);
    $("#PASSWORD").html(data[1]);
  }
});

Note that you should make sure to include the dataType in your $.ajax call so that jQuery knows how to parse the response.

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

Comments

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.